<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package HTML::FormatPS;

# ABSTRACT: Format HTML as PostScript


use 5.008;
use strict;
use warnings;
use Carp;
use Encode;
use IO::File;
use utf8;    # for the is_utf8 function

use base 'HTML::Formatter';

our $VERSION = '2.12'; # VERSION
our $AUTHORITY = 'cpan:NIGELM'; # AUTHORITY

# We now use Smart::Comments in place of the old DEBUG framework.
# this should be commented out in release versions....
##use Smart::Comments;

# ------------------------------------------------------------------------
# A few routines that convert lengths into points
sub mm { $_[0] * 72 / 25.4; }
sub in { $_[0] * 72; }

# ------------------------------------------------------------------------
my %PaperSizes = (
    A3        =&gt; [ mm(297), mm(420) ],
    A4        =&gt; [ mm(210), mm(297) ],
    A5        =&gt; [ mm(148), mm(210) ],
    B4        =&gt; [ 729,     1032 ],
    B5        =&gt; [ 516,     729 ],
    Letter    =&gt; [ in(8.5), in(11) ],
    Legal     =&gt; [ in(8.5), in(14) ],
    Executive =&gt; [ in(7.5), in(10) ],
    Tabloid   =&gt; [ in(11),  in(17) ],
    Statement =&gt; [ in(5.5), in(8.5) ],
    Folio     =&gt; [ in(8.5), in(13) ],
    "10x14"   =&gt; [ in(10),  in(14) ],
    Quarto    =&gt; [ 610,     780 ],
);

# ------------------------------------------------------------------------
my %FontFamilies = (
    Courier =&gt; [
        qw(Courier
            Courier-Bold
            Courier-Oblique
            Courier-BoldOblique)
    ],

    Helvetica =&gt; [
        qw(Helvetica
            Helvetica-Bold
            Helvetica-Oblique
            Helvetica-BoldOblique)
    ],

    Times =&gt; [
        qw(Times-Roman
            Times-Bold
            Times-Italic
            Times-BoldItalic)
    ],
);

# ------------------------------------------------------------------------
# size            0  1  2  3   4   5   6   7   8
my @FontSizes = ( 5, 6, 8, 10, 12, 14, 18, 24, 32 );

sub BOLD   { 0x01; }
sub ITALIC { 0x02; }

my %param = (
    papersize        =&gt; 'papersize',
    paperwidth       =&gt; 'paperwidth',
    paperheight      =&gt; 'paperheigth',
    leftmargin       =&gt; 'lmW',
    rightmargin      =&gt; 'rmW',
    horizontalmargin =&gt; 'mW',
    topmargin        =&gt; 'tmH',
    bottommargin     =&gt; 'bmH',
    verticalmargin   =&gt; 'mH',
    no_prolog        =&gt; 'no_prolog',
    no_trailer       =&gt; 'no_trailer',
    pageno           =&gt; 'printpageno',
    startpage        =&gt; 'startpage',
    fontfamily       =&gt; 'family',
    fontscale        =&gt; 'fontscale',
    leading          =&gt; 'leading',
);

# ------------------------------------------------------------------------


sub new {
    my $class = shift;

    my $self = $class-&gt;SUPER::new(@_);

    # Obtained from the &lt;title&gt; element
    $self-&gt;{title} = "";

    # The font ID last sent to the PostScript output (this may be
    # temporarily different from the "current font" as read from
    # the HTML input).  Initially none.
    $self-&gt;{psfontid} = "";

    # Pending horizontal space.  A list [ " ", $fontid, $width ],
    # or undef if no space is pending.
    $self-&gt;{hspace} = undef;

    # add an encoder object for perl native to Latin1 output
    $self-&gt;{encoder} = find_encoding('iso-8859-1');

    $self;
}

# ------------------------------------------------------------------------
sub default_values {
    (   shift-&gt;SUPER::default_values(),

        family      =&gt; "Times",
        mH          =&gt; mm(40),
        mW          =&gt; mm(20),
        printpageno =&gt; 1,
        startpage   =&gt; 1,         # yes, you can start numbering at 10, or whatever.
        fontscale   =&gt; 1,
        leading     =&gt; 0.1,
        papersize   =&gt; 'A4',
        paperwidth  =&gt; mm(210),
        paperheight =&gt; mm(297),
    );
}

# ------------------------------------------------------------------------
sub configure {
    my ( $self, $hash ) = @_;

    my ( $key, $val );
    while ( ( $key, $val ) = each %$hash ) {
        $key = lc $key;
        croak "Illegal parameter ($key =&gt; $val)" unless exists $param{$key};
        $key = $param{$key};
        {
            $key eq "family" &amp;&amp; do {
                $val = "\u\L$val";
                croak "Unknown font family ($val)"
                    unless exists $FontFamilies{$val};
                $self-&gt;{family} = $val;
                last;
            };
            $key eq "papersize" &amp;&amp; do {
                $self-&gt;papersize($val)
                    || croak sprintf "Unknown papersize '%s'.\nThe knowns are: %s.\nAborting",
                    $val,
                    join( ', ', sort keys %PaperSizes );
                last;
            };
            $self-&gt;{$key} = lc $val;
        }
    }
}

# ------------------------------------------------------------------------
sub papersize {
    my ( $self, $val ) = @_;

    $val = "\u\L$val";
    my ( $width, $height ) = @{ $PaperSizes{$val} || return 0 };
    return 0 unless defined $width;
    $self-&gt;{papersize}   = $val;
    $self-&gt;{paperwidth}  = $width;
    $self-&gt;{paperheight} = $height;
    1;
}

# ------------------------------------------------------------------------
sub fontsize {
    my $self = shift;

    my $size = $self-&gt;{font_size}[-1];
    $size = 8 if $size &gt; 8;
    $size = 3 if $size &lt; 0;
    $FontSizes[$size] * $self-&gt;{fontscale};
}

# Determine the current font and set font-related members.
# If $plain_with_size is given (a number), use a plain font
# of that size.  Otherwise, use the font specified by the
# HTML context.  Returns the "font ID" of the current font.

# ------------------------------------------------------------------------
sub setfont {
    my ( $self, $plain_with_size ) = @_;

    my $index  = 0;
    my $family = $self-&gt;{family} || 'Times';
    my $size   = $plain_with_size;
    unless ($plain_with_size) {
        $index |= BOLD if $self-&gt;{bold};
        $index |= ITALIC if $self-&gt;{italic} || $self-&gt;{underline};
        $family = 'Courier' if $self-&gt;{teletype};
        $size = $self-&gt;fontsize;
    }
    my $font           = $FontFamilies{$family}[$index];
    my $font_with_size = "$font-$size";
    if ( $self-&gt;{currentfont} eq $font_with_size ) {
        return $self-&gt;{currentfontid};
    }
    $self-&gt;{currentfont} = $font_with_size;
    $self-&gt;{pointsize}   = $size;
    my $fontmod = "Font::Metrics::$font";
    $fontmod =~ s/-//g;
    my $fontfile = $fontmod . ".pm";
    $fontfile =~ s,::,/,g;
    require $fontfile;
    {
        ## no critic
        no strict 'refs';
        $self-&gt;{wx} = \@{"${fontmod}::wx"};
        ## use critic
    }
    $font = $self-&gt;{fonts}{$font_with_size} || do {
        my $fontID = "F" . ++$self-&gt;{fno};
        $self-&gt;{fonts}{$font_with_size} = $fontID;
        $fontID;
    };
    $self-&gt;{currentfontid} = $font;
    return $font;
}

# ------------------------------------------------------------------------
# Construct PostScript code for setting the current font according
# to $fontid, or an empty string if no font change is needed.
# Assumes the return string will always be output as PostScript if
# nonempty, so that our notion of the current PostScript font
# stays in sync with that of the PostScript interpreter.
#
sub switchfont {
    my ( $self, $fontid ) = @_;

    if ( $self-&gt;{psfontid} eq $fontid ) {
        return "";
    }
    else {
        $self-&gt;{psfontid} = $fontid;
        return "$fontid SF";
    }
}

# ------------------------------------------------------------------------
# Like setfont + switchfont.
sub findfont {
    my ( $self, $plain_with_size ) = @_;

    return $self-&gt;switchfont( $self-&gt;setfont($plain_with_size) );
}

# ------------------------------------------------------------------------
sub width {
    my $self = shift;
    my $str  = shift;

    my $w  = 0;
    my $wx = $self-&gt;{wx};
    my $sz = $self-&gt;{pointsize};

    # need to encode to same encoding as font before getting width
    for ( unpack( "C*", $self-&gt;encode_string($str) ) ) {

        # if the character is outside the table, assume its m sized
        $w += ( ( $_ &gt; $#{$wx} ) ? $wx-&gt;[ ord('m') ] : $wx-&gt;[$_] ) * $sz    # unless  $_ eq 0xAD; # optional hyphen
    }
    $w;
}

# ------------------------------------------------------------------------
sub begin {
    my $self = shift;

    $self-&gt;SUPER::begin;

    # Margins are in points
    $self-&gt;{lm} = $self-&gt;{lmW} || $self-&gt;{mW};
    $self-&gt;{rm} = $self-&gt;{paperwidth} -  ( $self-&gt;{rmW} || $self-&gt;{mW} );
    $self-&gt;{tm} = $self-&gt;{paperheight} - ( $self-&gt;{tmH} || $self-&gt;{mH} );
    $self-&gt;{bm} = $self-&gt;{bmH} || $self-&gt;{mH};

    $self-&gt;{'orig_margins'} =    # used only by the debug-mode print-area marker
        [ map { sprintf "%.1f", $_ } @{$self}{qw(lm bm rm tm)} ];

    # Font setup
    $self-&gt;{fno}   = 0;
    $self-&gt;{fonts} = {};
    $self-&gt;{en}    = 0.55 * $self-&gt;fontsize(3);

    # Initial position
    $self-&gt;{xpos} = $self-&gt;{lm};    # top of the current line
    $self-&gt;{ypos} = $self-&gt;{tm};

    $self-&gt;{pageno}              = 1;
    $self-&gt;{visible_page_number} = $self-&gt;{startpage};

    $self-&gt;{line}              = "";
    $self-&gt;{showstring}        = "";
    $self-&gt;{currentfont}       = "";
    $self-&gt;{prev_currentfont}  = "";
    $self-&gt;{largest_pointsize} = 0;

    $self-&gt;newpage;
}

# ------------------------------------------------------------------------
sub end {
    my $self = shift;

    $self-&gt;showline;
    $self-&gt;endpage if $self-&gt;{'out'};
    my $pages = $self-&gt;{pageno} - 1;

    my @prolog = ();
    push( @prolog, "%!PS-Adobe-3.0\n" );

    #push(@prolog,"%%Title: No title\n"); # should look for the &lt;title&gt; element
    push( @prolog, "%%Creator: " . $self-&gt;version_tag . "\n" );
    push( @prolog, "%%CreationDate: " . localtime() . "\n" );
    push( @prolog, "%%Pages: $pages\n" );
    push( @prolog, "%%PageOrder: Ascend\n" );
    push( @prolog, "%%Orientation: Portrait\n" );
    my ( $pw, $ph ) = map { int($_); } @{$self}{qw(paperwidth paperheight)};

    push( @prolog, "%%DocumentMedia: Plain $pw $ph 0 white ()\n" );
    push( @prolog, "%%DocumentNeededResources: \n" );
    my %seenfont;
    for my $full ( sort keys %{ $self-&gt;{fonts} } ) {
        $full =~ s/-\d+$//;
        next if $seenfont{$full}++;
        push( @prolog, "%%+ font $full\n" );
    }
    push( @prolog, "%%DocumentSuppliedResources: procset newencode 1.0 0\n" );
    push( @prolog, "%%+ encoding ISOLatin1Encoding\n" );
    push( @prolog, "%%EndComments\n" );
    push( @prolog, &lt;&lt;'EOT');

%%BeginProlog
/S/show load def
/M/moveto load def
/SF/setfont load def

%%BeginResource: encoding ISOLatin1Encoding
systemdict /ISOLatin1Encoding known not {
    /ISOLatin1Encoding [
    /space /space /space /space /space /space /space /space
    /space /space /space /space /space /space /space /space
    /space /space /space /space /space /space /space /space
    /space /space /space /space /space /space /space /space

    /space /exclam /quotedbl /numbersign /dollar /percent /ampersand
        /quoteright
    /parenleft /parenright /asterisk /plus /comma /minus /period /slash
    /zero /one /two /three /four /five /six /seven
    /eight /nine /colon /semicolon /less /equal /greater /question
    /at /A /B /C /D /E /F /G
    /H /I /J /K /L /M /N /O
    /P /Q /R /S /T /U /V /W
    /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore
    /quoteleft /a /b /c /d /e /f /g
    /h /i /j /k /l /m /n /o
    /p /q /r /s /t /u /v /w
    /x /y /z /braceleft /bar /braceright /asciitilde /space

    /space /space /space /space /space /space /space /space
    /space /space /space /space /space /space /space /space
    /dotlessi /grave /acute /circumflex /tilde /macron /breve /dotaccent
    /dieresis /space /ring /cedilla /space /hungarumlaut /ogonek /caron

    /space /exclamdown /cent /sterling /currency /yen /brokenbar /section
    /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen
        /registered /macron
    /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph
        /periodcentered
    /cedillar /onesuperior /ordmasculine /guillemotright /onequarter
        /onehalf /threequarters /questiondown
    /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla
    /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex
        /Idieresis
    /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply
    /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn
        /germandbls
    /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla
    /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex
        /idieresis
    /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide
    /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn
        /ydieresis
    ] def
} if
%%EndResource
%%BeginResource: procset newencode 1.0 0
/NE { %def
   findfont begin
      currentdict dup length dict begin
     { %forall
        1 index/FID ne {def} {pop pop} ifelse
     } forall
     /FontName exch def
     /Encoding exch def
     currentdict dup
      end
   end
   /FontName get exch definefont pop
} bind def
%%EndResource
%%EndProlog
EOT

    push( @prolog, "\n%%BeginSetup\n" );
    for my $full ( sort keys %{ $self-&gt;{fonts} } ) {
        my $short = $self-&gt;{fonts}{$full};
        $full =~ s/-(\d+)$//;
        my $size = $1;
        push( @prolog, "ISOLatin1Encoding/$full-ISO/$full NE\n" );
        push( @prolog, "/$short/$full-ISO findfont $size scalefont def\n" );
    }
    push( @prolog, "%%EndSetup\n" );

    $self-&gt;collect("\n%%Trailer\n%%EOF\n")
        unless $self-&gt;{'no_trailer'};

    unshift( @{ $self-&gt;{output} }, @prolog )
        unless $self-&gt;{'no_prolog'};
}

# ------------------------------------------------------------------------
sub header_start {
    my ( $self, $level ) = @_;

    # If we are close enough to be bottom of the page, start a new page
    # instead of this:
    ### Heading of level: $level
    $self-&gt;vspace( 1 + ( 6 - $level ) * 0.4 );
    $self-&gt;{bold}++;
    push( @{ $self-&gt;{font_size} }, 8 - $level );
    1;
}

# ------------------------------------------------------------------------
sub header_end {
    my ($self) = @_;

    $self-&gt;vspace(1);
    $self-&gt;{bold}--;
    pop( @{ $self-&gt;{font_size} } );
    1;
}

# ------------------------------------------------------------------------
sub hr_start {
    my $self = shift;

    ### Making an HR...
    $self-&gt;showline;
    $self-&gt;vspace(0.5);
    $self-&gt;skip_vspace;
    my $lm = $self-&gt;{lm};
    my $rm = $self-&gt;{rm};
    my $y  = $self-&gt;{ypos};
    $self-&gt;collect( sprintf "newpath %.1f %.1f M %.1f %.1f lineto stroke\n", $lm, $y, $rm, $y );
    $self-&gt;vspace(0.5);
}

# ------------------------------------------------------------------------
sub skip_vspace {
    my $self = shift;

    ### Skipping some amount of vspace...
    if ( defined $self-&gt;{vspace} ) {
        $self-&gt;showline;
        if ( $self-&gt;{'out'} ) {
            $self-&gt;{ypos} -= $self-&gt;{vspace} * 10 * $self-&gt;{fontscale};

            if ( $self-&gt;{ypos} &lt; $self-&gt;{bm} ) {
                ### vspace skip forced new page...
                $self-&gt;newpage;
            }
            else {
                ### Skipped vspace making y: $self-&gt;{'ypos'},
            }
        }
        else {
            ### Not skipping vspace as out is false: $self-&gt;{ypos}
        }
        $self-&gt;{xpos}   = $self-&gt;{lm};
        $self-&gt;{vspace} = undef;
        $self-&gt;{hspace} = undef;
    }
    else {
        ### No vspace to skip...
    }

    return;
}

# ------------------------------------------------------------------------
sub show {
    my $self = shift;

    my $str = $self-&gt;{showstring};
    $str =~ tr/\x01//d;
    return unless length $str;

    # must escape parentheses and backslash
    $str =~ s/([\(\)\\])/\\$1/g;

    # encode output to latin1 when pushing it out
    $self-&gt;{line} .= "(" . $self-&gt;encode_string($str) . ")S\n";
    $self-&gt;{showstring} = "";
}

# ------------------------------------------------------------------------
sub showline {
    my $self = shift;

    $self-&gt;show;
    my $line = $self-&gt;{line};
    unless ( length $line ) {
        ### Showline is a no-op because line buffer is empty...
        return;
    }

    ### Showline emitting: $line

    $self-&gt;{ypos} -= $self-&gt;{largest_pointsize} || $self-&gt;{pointsize};
    if ( $self-&gt;{ypos} &lt; $self-&gt;{bm} ) {
        ### Showline forcing new page...
        $self-&gt;newpage;

        # newpage might alter currentfont!
        ### Showline sets vspace: $self-&gt;{vspace} || 0

        $self-&gt;{ypos} -= $self-&gt;{pointsize};
        #### Showline/Newpage x: $self-&gt;{xpos}
        #### Showline/Newpage y: $self-&gt;{ypos}

        # must set current font again
        my $font = $self-&gt;{prev_currentfont};
        if ($font) {
            $self-&gt;collect("$self-&gt;{fonts}{$font} SF\n\n");
        }

        ### End of doing newpage...
    }

    my $lm = $self-&gt;{lm};
    my $x  = $lm;
    if ( $self-&gt;{center} ) {

        # Unfortunately, the center attribute is gone when we get here,
        # so this code is never activated
        my $linewidth = $self-&gt;{xpos} - $lm;
        $x += ( $self-&gt;{rm} - $lm - $linewidth ) / 2;
    }

    $self-&gt;collect( sprintf "%.1f %.1f M\n", $x, $self-&gt;{ypos} );    # moveto
    $line =~ s/\s\)S$/)S/;                                           # many lines will end uselessly with space
    $self-&gt;collect($line);
    $self-&gt;{'out'}++;

    if ( $self-&gt;{bullet} ) {

        # Putting this behind the first line of the list item
        # makes it more likely that we get the right font.  We should
        # really set the font that we want to use.
        my $bullet = $self-&gt;{bullet};
        if ( $bullet eq '*' ) {

            # There is no character that is really suitable.  Let's make
            # a medium-sized filled circle ourself.
            my $radius = $self-&gt;{pointsize} / 8;
            ### Adding code for a '*' bullet for that line...

            $self-&gt;collect(
                sprintf "newpath %.1f %.1f %.1f 0 360 arc fill\n",
                $self-&gt;{bullet_pos} + $radius,
                $self-&gt;{ypos} + $radius * 2, $radius,
            );
        }
        else {
            ### Adding code for other bullet for that line...

            $self-&gt;collect(
                sprintf "%.1f (%s) stringwidth pop sub %.1f add %.1f M\n",    # moveto
                $self-&gt;{bullet_pos},
                $bullet,
                $self-&gt;{pointsize} * 0.62,
                $self-&gt;{ypos},
            );
            $self-&gt;collect("($bullet)S\n");
        }
        $self-&gt;{bullet} = '';

    }

    $self-&gt;{prev_currentfont}  = $self-&gt;{currentfont};
    $self-&gt;{largest_pointsize} = 0;
    $self-&gt;{line}              = "";
    $self-&gt;{xpos}              = $lm;

    # Additional linespacing

    $self-&gt;{ypos} -= $self-&gt;{leading} * $self-&gt;{pointsize};
    #### Showline/end x: $self-&gt;{xpos}
    #### Showline/end y: $self-&gt;{ypos}

    return;
}

# ------------------------------------------------------------------------
sub endpage {
    my $self = shift;

    ### End page: $self-&gt;{pageno}
    # End previous page
    $self-&gt;collect("showpage\n");
    $self-&gt;{visible_page_number}++;
    $self-&gt;{pageno}++;
}

# ------------------------------------------------------------------------
sub newpage {
    my $self = shift;

    local $self-&gt;{'pointsize'} = $self-&gt;{'pointsize'};

    # That's needed for protecting against one bit of the
    # potential side-effects from page-numbering code

    if ( $self-&gt;{'out'} ) {    # whether we've sent anything to the current page so far.
        ### Newpage calls endpage...
        $self-&gt;endpage;
        $self-&gt;collect( sprintf "%% %s has sent %s write-events to the above page.\n", ref($self), $self-&gt;{'out'}, );
    }

    $self-&gt;{'out'} = 0;
    my $pageno              = $self-&gt;{pageno};
    my $visible_page_number = $self-&gt;{visible_page_number};

    $self-&gt;collect("\n%%Page: $pageno $pageno\n");
    ### Starting page: $pageno

    # Print page number
    if ( $self-&gt;{printpageno} ) {
        ### Printing page number: $visible_page_number
        $self-&gt;collect("%% Title and pageno\n");
        my $f = $self-&gt;findfont(8);
        $self-&gt;collect("$f\n") if $f;
        my $x = $self-&gt;{paperwidth};
        if ($x) { $x -= 30; }
        else    { $x = 30; }
        $self-&gt;collect( sprintf "%.1f 30.0 M($visible_page_number)S\n", $x );
        $x = $self-&gt;{lm};
        $self-&gt;{title} =~ tr/\x01//d;
        $self-&gt;collect( sprintf "%.1f 30.0 M($self-&gt;{title})S\n", $x );
    }
    else {
        ### Pointedly not printing page number...
    }
    $self-&gt;collect("\n");

    $self-&gt;{xpos} = $self-&gt;{lm};
    $self-&gt;{ypos} = $self-&gt;{tm};
    #### Newpage/end x: $self-&gt;{xpos}
    #### Newpage/end y: $self-&gt;{ypos}
}

# ------------------------------------------------------------------------
sub encode_string {    # converts string into latin1 charset
    my ( $self, $str ) = @_;

    # the string from the parser is normally unicode, and may contain
    # some punctuation characters in the 'General Punctuation' block
    # which can be expressed in latin1, but Encode module fails on them
    # so we will manually hack these...
    # Theres no usable latin1 for the double quote chars so map to "
    if ( utf8::is_utf8($str) ) {
        $str =~ tr/\x{2018}\x{2019}\x{201A}\x{201C}\x{201D}\x{201F}\x{2033}\x{2036}/`',"""""/;
    }

    return $self-&gt;{encoder}-&gt;encode($str);
}

# ------------------------------------------------------------------------
sub out {    # Output a word
    my ( $self, $text ) = @_;

    $text =~ tr/\xA0\xAD/ /d;
    ### Trapping new word: $text

    if ( $self-&gt;{collectingTheTitle} ) {

        # Both collect and print the title
        $text =~ s/([\(\)\\])/\\$1/g;    # Escape parens and the backslash
        $self-&gt;{title} .= $text;
        return;
    }

    my $fontid = $self-&gt;setfont();
    my $w      = $self-&gt;width($text);

    if ( $text =~ /^\s*$/ ) {
        $self-&gt;{hspace} = [ " ", $fontid, $w ];
        return;
    }

    $self-&gt;skip_vspace;

    # determine spacing / line breaks needed before text
    if ( $self-&gt;{hspace} ) {
        my ( $stext, $sfont, $swidth ) = @{ $self-&gt;{hspace} };
        if ( $self-&gt;{xpos} + $swidth + $w &gt; $self-&gt;{rm} ) {

            # line break
            $self-&gt;showline;
        }
        else {

            # no line break; output a space
            $self-&gt;show_with_font( $stext, $sfont, $swidth );
        }
        $self-&gt;{hspace} = undef;
    }

    # output the text
    $self-&gt;show_with_font( $text, $fontid, $w );
}

# ------------------------------------------------------------------------
sub show_with_font {
    my ( $self, $text, $fontid, $w ) = @_;

    my $fontps = $self-&gt;switchfont($fontid);
    if ( length $fontps ) {
        $self-&gt;show;
        $self-&gt;{line} .= "$fontps\n";
    }

    $self-&gt;{xpos} += $w;
    $self-&gt;{showstring} .= $text;

    #### Append to string buffer: $text
    #### with font: $fontid
    #### with xpos: $self-&gt;{xpos}

    $self-&gt;{largest_pointsize} = $self-&gt;{pointsize}
        if $self-&gt;{largest_pointsize} &lt; $self-&gt;{pointsize};
    $self-&gt;{'out'}++;
}

# ------------------------------------------------------------------------
sub pre_out {
    my ( $self, $text ) = @_;

    $self-&gt;skip_vspace;
    $self-&gt;tt_start;
    my $font = $self-&gt;findfont();
    if ( length $font ) {
        $self-&gt;show;
        $self-&gt;{line} .= "$font\n";
    }
    while ( $text =~ s/(.*)\n// ) {
        $self-&gt;{'out'}++;
        $self-&gt;{showstring} .= $1;
        $self-&gt;showline;
    }
    $self-&gt;{showstring} .= $text;
    $self-&gt;tt_end;
    1;
}

# ------------------------------------------------------------------------
sub bullet {
    my ( $self, $bullet ) = @_;

    $self-&gt;{bullet}     = $bullet;
    $self-&gt;{bullet_pos} = $self-&gt;{lm};
}

# ------------------------------------------------------------------------
sub adjust_lm {
    my $self = shift;

    $self-&gt;showline;

    $self-&gt;{lm} += $_[0] * $self-&gt;{en};
    1;
}

# ------------------------------------------------------------------------
sub adjust_rm {
    my $self = shift;

    $self-&gt;showline;

    $self-&gt;{rm} += $_[0] * $self-&gt;{en};
}

# ------------------------------------------------------------------------
sub head_start { 1; }
sub head_end   { 1; }

sub title_start {
    my ($self) = @_;

    $self-&gt;{collectingTheTitle} = 1;
    1;
}

sub title_end {
    my ($self) = @_;

    $self-&gt;{collectingTheTitle} = 0;
    1;
}

# ------------------------------------------------------------------------
my ( $counter, $last_state_filename );

# For use in circumstances of total desperation:

sub dump_state {
    my $self = shift;
    require Data::Dumper;

    ++$counter;
    my $filename = sprintf( "state%04d.txt", $counter );
    my $state = IO::File-&gt;new( $filename, 'w' ) or die "Can't write-open $filename: $!";
    $state-&gt;printf( "%s line %s\n", ( caller(1) )[ 3, 2 ] );
    {
        local ( $self-&gt;{'wx'} )     = '&lt;SUPPRESSED&gt;';
        local ( $self-&gt;{'output'} ) = '&lt;SUPPRESSED&gt;';
        $state-&gt;print( Data::Dumper::Dumper($self) );
    }
    $state-&gt;close;
    sleep 0;

    if ($last_state_filename) {
        system("perl -S diff.bat $last_state_filename $filename &gt; $filename.diff");
    }

    $last_state_filename = $filename;
    return 1;
}

# ------------------------------------------------------------------------


1;

__END__

=pod

=for test_synopsis 1;
__END__

=for stopwords bottommargin fontfamily fontscale helvetica
    horizontalmargin leftmargin noprolog notrailer pageno
    paperheight papersize paperwidth postscript rightmargin
    startpage topmargin verticalmargin ledding leeding prolog
    CPAN Quarto Tabloid Unicode homepage

=head1 NAME

HTML::FormatPS - Format HTML as PostScript

=head1 VERSION

version 2.12

=head1 SYNOPSIS

    use HTML::TreeBuilder;
    $tree = HTML::TreeBuilder-&gt;new-&gt;parse_file("test.html");

    use HTML::FormatPS;
    $formatter = HTML::FormatPS-&gt;new(
        FontFamily =&gt; 'Helvetica',
        PaperSize  =&gt; 'Letter',
    );
    print $formatter-&gt;format($tree);

Or, for short:

    use HTML::FormatPS;
    print HTML::FormatPS-&gt;format_file(
        "test.html",
        'FontFamily' =&gt; 'Helvetica',
        'PaperSize'  =&gt; 'Letter',
    );

=head1 DESCRIPTION

The HTML::FormatPS is a formatter that outputs PostScript code. Formatting of
HTML tables and forms is not implemented.

HTML::FormatPS is built on top of L&lt;HTML::Formatter&gt; and so further detail may
be found in the documentation for L&lt;HTML::Formatter&gt;.

You might specify the following parameters when constructing the formatter
object (or when calling format_file or format_string):

=over 4

=item PaperSize

What kind of paper should we format for.  The value can be one of these: A3,
A4, A5, B4, B5, Letter, Legal, Executive, Tabloid, Statement, Folio, 10x14,
Quarto.

The default is "A4".

=item PaperWidth

The width of the paper, in points.  Setting PaperSize also defines this value.

=item PaperHeight

The height of the paper, in points.  Setting PaperSize also defines this value.

=item LeftMargin

The left margin, in points.

=item RightMargin

The right margin, in points.

=item HorizontalMargin

Both left and right margin at the same time.  The default value is 4 cm.

=item TopMargin

The top margin, in points.

=item BottomMargin

The bottom margin, in points.

=item VerticalMargin

Both top and bottom margin at the same time.  The default value is 2 cm,

=item PageNo

This parameter determines if we should put page numbers on the pages. The
default value is true; so you have to set this value to 0 in order to suppress
page numbers.  (The "No" in "PageNo" means number/numero!)

=item FontFamily

This parameter specifies which family of fonts to use for the formatting. Legal
values are "Courier", "Helvetica" and "Times".  The default is "Times".

=item FontScale

This is a scaling factor for all the font sizes.  The default value is 1.

For example, if you want everything to be almost three times as large, you
could set this to 2.7.  If you wanted things just a bit smaller than normal,
you could set it to .92.

=item Leading

This option (pronounced "ledding", not "leeding") controls how much is space
between lines. This is a factor of the font size used for that line.  Default
is 0.1 -- so between two 12-point lines, there will be 1.2 points of space.

=item StartPage

Assuming you have PageNo on, StartPage controls what the page number of the
first page will be. By default, it is 1. So if you set this to 87, the first
page would say "87" on it, the next "88", and so on.

=item NoProlog

If this option is set to a true value, HTML::FormatPS will make a point of
I&lt;not&gt; emitting the PostScript prolog before the document. By default, this is
off, meaning that HTML::FormatPS I&lt;will&gt; emit the prolog. This option is of
interest only to advanced users.

=item NoTrailer

If this option is set to a true value, HTML::FormatPS will make a point of
I&lt;not&gt; emitting the PostScript trailer at the end of the document. By default,
this is off, meaning that HTML::FormatPS I&lt;will&gt; emit the bit of PostScript
that ends the document. This option is of interest only to advanced users.

=back

=head1 METHODS

=head2 new

    my $formatter = FormatterClass-&gt;new(
        option1 =&gt; value1, option2 =&gt; value2, ...
    );

This creates a new formatter object with the given options.

=head1 SEE ALSO

L&lt;HTML::Formatter&gt;

=head1 ISSUES

=over

=item *

Output is in ISO Latin1 format. The underlying HTML parsers tend to now work in
Unicode (perl native) code points. There is an impedance mismatch between
these, which may give issues with complex characters within HTML.

=back

=head1 TO DO

=over

=item *

Support for some more character styles, notably including: strike-through,
underlining, superscript, and subscript.

=item *

Support for Unicode.

=item *

Support for Win-1252 encoding, since that's what most people mean when they use
characters in the range 0x80-0x9F in HTML.

=item *

And, if it's ever even reasonably possible, support for tables.

=back

I would welcome email from people who can help me out or advise me on the
above.

=head1 INSTALLATION

See perlmodinstall for information and options on installing Perl modules.

=head1 BUGS AND LIMITATIONS

You can make new bug reports, and view existing ones, through the
web interface at L&lt;http://rt.cpan.org/Public/Dist/Display.html?Name=HTML-Format&gt;.

=head1 AVAILABILITY

The project homepage is L&lt;https://metacpan.org/release/HTML-Format&gt;.

The latest version of this module is available from the Comprehensive Perl
Archive Network (CPAN). Visit L&lt;http://www.perl.com/CPAN/&gt; to find a CPAN
site near you, or see L&lt;https://metacpan.org/module/HTML::Format/&gt;.

=head1 AUTHORS

=over 4

=item *

Nigel Metheringham &lt;nigelm@cpan.org&gt;

=item *

Sean M Burke &lt;sburke@cpan.org&gt;

=item *

Gisle Aas &lt;gisle@ActiveState.com&gt;

=back

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by Nigel Metheringham, 2002-2005 Sean M Burke, 1999-2002 Gisle Aas.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
</pre></body></html>