PostScript::File - Base class for creating Adobe PostScript files


PostScript::File - Base class for creating Adobe PostScript files


    use PostScript::File qw(check_tilde check_file
                    incpage_label incpage_roman);


An 'hello world' program:
    use PostScript::File;
    my $ps = new PostScript::File();

    $ps->add_to_page( <<END_PAGE );
        /Helvetica findfont 
        12 scalefont 
        72 300 moveto
        (hello world) show

    $ps->output( "~/test" );

All options

    my $ps = new PostScript::File(
        paper => 'Letter',
        height => 500,
        width => 400,
        bottom => 30,
        top => 30,
        left => 30,
        right => 30,
        clip_command => 'stroke',
        clipping => 1,
        eps => 1,
        dir => '~/foo',
        file => "bar",
        landscape => 0,
        headings => 1,
        reencode => 'ISOLatin1Encoding',
        font_suffix => '-iso',
        errors => 1,
        errmsg => 'Failed:',
        errfont => 'Helvetica',
        errsize => 12,
        errx => 72,
        erry => 300,

        debug => 2,
        db_active => 1,
        db_xgap => 120,
        db_xtab => 8,
        db_base => 300,
        db_ytop => 500,
        db_color => '1 0 0 setrgbcolor',
        db_font => 'Times-Roman',
        db_fontsize => 11,
        db_bufsize => 256,


This module is designed as a supporting part of the PostScript::Graph suite. For top level modules that output something useful, see


An outline Adobe PostScript file is constructed. Functions allow access to each of Adobe's Document Structuring Convention (DSC) sections and control how the pages are constructed. It is possible to construct and output files in either normal PostScript (*.ps files) or as Encapsulated Postscript (*.epsf or *.epsi files). By default a minimal file is output, but support for font encoding, postscript error reporting and debugging can be built in if required.

Documents can typically be built using only these functions:

    new           The constructor, with many options
    add_function  Add postscript functions to the prolog
    add_to_page   Add postscript to construct each page 
    newpage       Begins a new page in the document
    output        Construct the file and saves it

The rest of the module involves fine-tuning this. Some settings only really make sense when given once, while others can control each page independently. See new for the functions that duplicate option settings, they all have get_ counterparts. The following provide additional support.


The functions which insert entries into each of the DSC sections all begin with 'add_'. They also have get_ counterparts.


Finally, there are a few stand-alone functions. These are not methods and are available for export if requested.



new( options )

Create a new PostScript::File object, either a set of pages or an Encapsulated PostScript (EPS) file. Options are hash keys and values. All values should be in the native postscript units of 1/72 inch.


    $ref = new PostScript::File ( 
                eps => 1,
                landscape => 1,
                width => 216,
                height => 288,
                left => 36,
                right => 44,
                clipping => 1 );

This creates an encapsulated postscript document, 4 by 3 inch pages printing landscape with left and right margins of around half an inch. The width is always the shortest side, even in landscape mode. 3*72=216 and 4*72=288. Being in landscape mode, these would be swapped. The bounding box used for clipping would then be from (50,0) to (244,216).

options may be a single hash reference instead of an options list, but the hash must have the same structure. This is more convenient when used as a base class.

In addition, the following keys are recognized.

File size keys

There are four options which control how much gets put into the resulting file.


No debug code is added to the file. Of course there must be no calls to debug functions in the postscript code.

  • db_ functions are replaced by dummy functions which do nothing.

  • A range of functions are added to the file to support debugging postscript. This switch is similar to the 'C' NDEBUG macro in that debugging statements may be left in the postscript code but their effect is removed.

    Of course, being an interpreted language, it is not quite the same as the calls still takes up space - they just do nothing. See POSTSCRIPT DEBUGGING SUPPORT for details of the functions.

  • Loads the debug functions and gives some reassuring output at the start and a stack dump at the end of each page.

    A mark is placed on the stack at the beginning of each page and 'cleartomark' is given at the end, avoiding potential invalidrestore errors. Note, however, that if the page does not end with a clean stack, it will fail when debugging is turned off.

  • errors

    PostScript has a nasty habit of failing silently. Setting this to 1 prints fatal error messages on the bottom left of the paper. For user functions, a postscript function report_error is defined. This expects a message string on the stack, which it prints before stopping. (Default: 1)


    Enable PostScript comments such as the date of creation and user's name.


    Requests that a font re-encode function be added and that the 13 standard PostScript fonts get re-encoded in the specified encoding. The only recognized value so far is 'ISOLatin1Encoding' which selects the iso8859-1 encoding and fits most of western Europe, including the Scandinavia.

    Initialization keys

    There are a few initialization settings that are only relevant when the file object is constructed.


    The margin in from the paper's bottom edge, specifying the non-printable area. Remember to specify clipping if that is what is wanted. (Default: 28)


    The bounding box is used for clipping if this is set to ``clip'' or is drawn with ``stroke''. This also makes the whole page area available for debugging output. (Default: ``clip'').


    Set whether printing will be clipped to the file's bounding box. (Default: 0)


    An optional directory for the output file. See </set_filename>.


    Set to 1 to produce Encapsulated PostScript. get_eps returns the value set here. (Default: 0)


    The name of the output file. See </set_filename>.


    This string is appended to each font name as it is reencoded. (Default: ``-iso'')

    The standard fonts are named Courier, Courier-Bold, Courier-BoldOblique, Courier-Oblique, Helvetica, Helvetica-Bold, Helvetica-BoldOblique, Helvetica-Oblique, Times-Roman, Times-Bold, Times-BoldItalic, Times-Italic, and Symbol. The string value is appended to these to make the new names.


        $ps = new PostScript::File( 
                    font_suffix => "-iso",
                    reencode => "ISOLatin1Encoding"
    "Courier" still has the standard mapping while "Courier-iso" includes the additional European characters.


    Set the page height, the longest edge of the paper. (Default taken from paper)

    The paper size is set to ``Custom''. get_width and get_height return the values set here.


    Set whether the page is oriented horizontally (1) or vertically (0). (Default: 0)

    In landscape mode the coordinates are rotated 90 degrees and the origin moved to the bottom left corner. Thus the coordinate system appears the same to the user, with the origin at the bottom left.


    The margin in from the paper's left edge, specifying the non-printable area. Remember to specify clipping if that is what is wanted. (Default: 28)


    Set the paper size of each page. A document can be created using a standard paper size without having to remember the size of paper using PostScript points. Valid choices are currently A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, Executive, Folio, 'Half-Letter', Letter, 'US-Letter', Legal, 'US-Legal', Tabloid, 'SuperB', Ledger, 'Comm #10 Envelope', 'Envelope-Monarch', 'Envelope-DL', 'Envelope-C5', 'EuroPostcard'. (Default: ``A4'')

    This also sets width and height. get_paper returns the value set here.


    The margin in from the paper's right edge. It is a positive offset, so right=36 will leave a half inch no-go margin on the right hand side of the page. Remember to specify clipping if that is what is wanted. (Default: 28)


    The margin in from the paper's top edge. It is a positive offset, so top=36 will leave a half inch no-go margin at the top of the page. Remember to specify clipping if that is what is wanted. (Default: 28)


    Set the page width, the shortest edge of the paper. (Default taken from paper)

    Debugging support keys

    This makes most sense in the postscript code rather than perl. However, it is convenient to be able to set defaults for the output position and so on. See POSTSCRIPT DEBUGGING SUPPORT for further details.


    Set to 0 to temporarily suppress the debug output. (Default: 1)


    Debug printing will not occur below this point. (Default: 6)


    The size of string buffers used. Output must be no longer than this. (Default: 256)


    This is the whole postscript command (with any parameters) to specify the colour of the text printed by the debug routines. (Default: ``0 setgray'')


    The name of the font to use. (Default: ``Courier'')



    The size of the font. Postscript uses its own units, but they are almost points. (Default: 10)


    Typically, the output comprises single values such as a column showing the stack contents. db_xgap specifies the width of each column. By default, this is calculated to allow 4 columns across the page.


    The left edge, where debug output starts. (Default: 6)


    The amount indented by db_indent. (Default: 10)


    The top line of debugging output. Defaults to 6 below the top of the page.

    Error handling keys

    If errors is set, the position of any fatal error message can be controlled with the following options. Each value is placed into a postscript variable of the same name, so they can be overridden from within the code if necessary.


    The name of the font used to show the error message. (Default: ``Courier-Bold'')


    The error message comprises two lines. The second is the name of the postscript error. This sets the first line. (Default: ``ERROR:'')


    Size of the error message font. (Default: 12)


    X position of the error message on the page. (Default: (72))


    Y position of the error message on the page. (Default: (72))

    Document structure

    There are options which only affect the DSC comments. They all have get_ functions which return the values set here, e.g. get_title returns the value given to the title option.


    Declare and PostScript language extensions that need to be available. (No default)


    Set the PostScript language level. (No default)


    Set the order the pages have been defined. It should one of ``ascend'', ``descend'' or ``special'' if a document manager must not reorder the pages. (No default)


    Set the document's title as recorded in PostScript's Document Structuring Conventions. (No default)


    Set the document's version as recorded in PostScript's Document Structuring Conventions. This should be a string with a major, minor and revision numbers. For example ``1.5 8'' signifies revision 8 of version 1.5. (No default)


    A few options that may be changed between pages or set here for the first page.


    Set the initial value for the function which increments page labels. See set_incpage_handler.


    Set the label (text or number) for the initial page. See set_page_label. (Default: ``1'')


    Set whether the postscript code is filtered. space strips leading spaces so the user can indent freely without increasing the file size. comments remove lines beginning with '%' as well. (Default: ``space'')


    newpage( [page] )

    Generate a new PostScript page, unless in a EPS file when it is ignored.

    If page is not specified the page number is increased each time a new page is requested.

    page can be a string or a number. If anything other than a simple integer, you probably should register your own counting function with set_incpage_handler. Of course there is no need to do this if a page string is given to every newpage call.

    output( [filename [, dir]] )

    Writes the current PostScript out to the named file provided a filename has been given either here, to new or set_filename. If no filename is given, the text is returned by the function.

    Use this option whenever output is required to disk. The current PostScript document in memory is not cleared, and can still be extended.


    Use these get_ and set_ methods to access a PostScript::File object's data.


    set_filename( file, [dir] )

    An optional fully qualified path-and-file, a simple file name, or ``'' which stands for the special file File::Spec->devnull().

    An optional directory dir. If present (and file is not already an absolute path), it is prepended to file.

    Specify the root file name for the output file(s) and ensure the resulting absolute path exists. This should not include any extension. .ps will be added for ordinary postscript files. EPS files have an extension of .epsf without or .epsi with a preview image.

    If eps has been set, multiple pages will have the page label appendend to the file name.


        $ps->new PostScript::File( eps => 1 );
        $ps->set_filename( "pics", "~/book" );
            ... draw page
            ... draw page
            ... draw page

    The three pages for user 'chris' on a unix system would be:


    It would be wise to use set_page_bounding_box explicitly for each page if using multiple pages in EPS files.


    set_strip( ``none'' | ``space'' | ``comments'' )

    Determine whether the postscript code is filtered. space strips leading spaces so the user can indent freely without increasing the file size. comments remove lines beginning with '%' as well.

    get_page_landscape( [page] )

    set_page_landscape( [[page,] landscape] )

    Inspect and change whether the page specified is oriented horizontally (1) or vertically (0). The default is the global setting as returned by get_landscape. If page is omitted, the current page is assumed.

    get_page_clipping( [page] )

    set_page_clipping( [[page,] clipping] )

    Inspect and change whether printing will be clipped to the page's bounding box. (Default: 0)


    set_page_label( [page] )

    Inspect and change the number or label for the current page. (Default: ``1'')

    This will be automatically incremented using the function set by set_incpage_hander.


    set_incpage_handler( [handler] )

    Inspect and change the function used to increment the page number or label. The following suitable values for handler refer to functions defined in the module:


    The default (incpage_label) increments numbers and letters, the other one handles roman numerals up to 39. handler should be a reference to a subroutine that takes the current page label as its only argument and returns the new one. Use this to increment pages using roman numerals or custom orderings.


    set_bounding_box( x0, y0, x1, y1 )

    Inspect or change the bounding box for the whole document, showing only the area inside.

    Clipping is enabled. Call with set_clipping with 0 to stop clipping.

    get_page_bounding_box( [page] )

    set_page_bounding_box( [page], x0, y0, x1, y1 )

    Inspect or change the bounding box for a specified page. If page is not specified, the current page is assumed, otherwise it should be a page label already given to newpage or set_page_label. The page bounding box defaults to the paper area.

    Note that this automatically enables clipping for the page. If this isn't what you want, call set_page_clipping with 0.

    set_page_margins( [page], left, bottom, right, top )

    An alternative way of changing a single page's bounding box. Unlike the options given to new, the parameters here are the gaps around the image, not the paper. So left=36 will set the left side in by half an inch, this might be a short side if landscape is set.

    Note that this automatically enables clipping for the page. If this isn't what you want, call set_page_clipping with 0.


    Return the number of pages currently known.

    set_variable( key, value )

    Assign a user defined hash key and value. Provided to keep track of states within the PostScript code, such as which dictionaries are currently open. PostScript::File does not use this - it is provided for client programs. It is recommended that key is the module name to avoid clashes. This entry could then be a hash holding any number of user variables.


    Retrieve a user defined value.

    set_page_variable( key, value )

    Assign a user defined hash key and value only valid on the current page. Provided to keep track of states within the PostScript code, such as which styles are currently active. PostScript::File does not use this (except to clear it at the start of each page). It is recommended that key is the module name to avoid clashes. This entry could then be a hash holding any number of user variables.


    Retrieve a user defined value.


    Return the ghostscript interpreter that would be used to output a Portable Network Graphics file.



    add_comment( comment )

    Most of the required and recommended comments are set directly, so this function should rarely be needed. It is provided for completeness so that comments such as DocumentNeededResources: can be added. The comment should be the bare PostScript DSC name and value, with additional lines merely prefixed by +.


        $ps->add_comment("ProofMode: NotifyMe");
        $ps->add_comment("Requirements: manualfeed");
        $ps->add_comment("+ Paladin");
        $ps->add_comment("+ Paladin-Bold");


    add_preview( width, height, depth, lines, preview )

    Use this to add a Preview in EPSI format - an ASCII representation of a bitmap. If an EPS file has a preview it becomes an EPSI file rather than EPSF.


    add_default( default )

    Use this to add any PostScript DSC comments to the Defaults section. These would be typically values like PageCustomColors: or PageRequirements:.


    add_resource( type, name, params, resource )

    A string indicating the DSC type of the resource. It should be one of Document, Resource, File, Font, ProcSet or Feature (case sensitive).

    An arbitrary identifier of this resource.

    Some resource types require parameters. See the Adobe documentation for details.

    A string containing the postscript code. Probably best provided a 'here' document.

    Use this to add fonts or images. add_function is provided for functions.


        $ps->add_resource( "File", "My_File1", 
                           "", <<END_FILE1 );
            ...postscript resource definition

    Note that get_resources returns all resources added, including those added by any inheriting modules.


    add_function( name, code )

    Add user defined functions to the PostScript prolog. Despite the name, it is better to add related functions in the same code section. name is an arbitrary identifier of this resource. Best used with a 'here' document.


        $ps->add_function( "My_Functions", <<END_FUNCTIONS );
            % postscript code can be freely indented
            % as leading spaces and blank lines 
            % (and comments, if desired) are stripped
            % foo does this...
            /foo {
                ... definition of foo
            } bind def
            % bar does that...
            /bar {
                ... definition of bar
            } bind def

    Note that get_functions (in common with the others) will return all user defined functions possibly including those added by other classes.


    sub has_function { my ($o, $name) = @_; return ($o->{DocSupplied} =~ /$name/); }

    has_function( name )

    This returns true if name has already been included in the file. The name should identical to that given to add_function.


    set_setup( code )

    Direct access to the %%Begin(End)Setup section. Use this for setpagedevice, statusdict or other settings that initialize the device or document.


    set_page_setup( code )

    Code added here is output before each page. As there is no special provision for %%Page... DSC comments, they should be included here.

    Note that any settings defined here will be active for each page seperately. Use add_setup if you want to carry settings from one page to another.

    get_page( [page] )

    add_to_page( [page], code )

    The main function for building the postscript output. page can be any label, typically one given to set_page_label. (Default: current page)

    If page is not recognized, a new page is added with that label. Note that this is added on the end, not in the order you might expect. So adding ``vi'' to page set ``iii, iv, v, 6, 7, 8'' would create a new page after ``8'' not after ``v''.


        $ps->add_to_page( <<END_PAGE );
            ...postscript building this page
        $ps->add_to_page( "3", <<END_PAGE );
            ...postscript building page 3
    The first example adds code onto the end of the current page.  The second one either adds additional code to page
    3 if it exists, or starts a new one.

    sub get_page_trailer { my $o = shift; return $o->{PageTrailer}; }

    sub add_page_trailer { my ($o, $entry) = @_; $entry =~ s/$o->{strip}//gm; $o->{PageTrailer} = $entry if (defined $entry); }


    set_page_trailer( code )

    Code added here is output after each page. It may refer to settings made during set_page_setup or add_to_page.


    set_trailer( code )

    Add code to the PostScript %%Trailer section. Use this for any tidying up after all the pages are output.


    This section documents the postscript functions which provide debugging output. Please note that any clipping or bounding boxes will also hide the debugging output which by default starts at the top left of the page. Typical new options required for debugging would include the following.

        $ps = PostScript::File->new ( 
                errors => "page",
                debug => 2,
                clipcmd => "stroke" );

    The debugging output is printed on the page being drawn. In practice this works fine, especially as it is possible to move the output around. Where the text appears is controlled by a number of postscript variables, most of which may also be given as options to new.

    The main controller is db_active which needs to be non-zero for any output to be seen. It might be useful to set this to 0 in new, then at some point in your code enable it. Remember that the debugdict dictionary needs to be selected in order for any of its variables to be changed. This is better done with db_on but it illustrates the point.

        /debugdict begin
            /db_active 1 def
        (this will now show) db_show

    At any time, the next output will appear at db_xpos and db_ypos. These can of course be set directly. However, after most prints, the equivalent of a 'newline' is executed. It moves down db_fontsize and left to db_xpos. If, however, that would take it below db_ybase, db_ypos is reset to db_ytop and the x coordinate will have db_xgap added to it, starting a new column.

    The positioning of the debug output is changed by setting db_xpos and db_ytop to the top left starting position, with db_ybase guarding the bottom. Extending to the right is controlled by not printing too much! Judicious use of db_active can help there.

    Postscript functions

    x0 y0 x1 y1 cliptobox

    This function is only available if 'clipping' is set. By calling the perl method draw_bounding_box (and resetting with clip_bounding_box) it is possible to use this to identify areas on the page.

        $ps->add_to_page( <<END_CODE );
            my_l my_b my_r my_t cliptobox

    msg report_error

    If 'errors' is enabled, this call allows you to report a fatal error from within your postscript code. It expects a string on the stack and it does not return.

    All the db_ variables (including function names) are defined within their own dictionary (debugdict). But this can be ignored by all calls originating from within code passed to add_to_page (usually including add_function code) as the dictionary is automatically put on the stack before each page and taken off as each finishes.

    any db_show

    The workhorse of the system. This takes the item off the top of the stack and outputs a string representation of it. So you can call it on numbers or strings and it will show them. Arrays are printed using db_array and marks are shown as '--mark--'.

    n msg db_nshow

    This shows top n items on the stack. It requires a number and a string on the stack, which it removes. It prints out msg then the top n items on the stack, assuming there are that many. It can be used to do a labelled stack dump. Note that if new was given the option debug = 2>, There will always be a '--mark--' entry at the base of the stack. See debug.

        count (at this point) db_nshow


    Prints out the contents of the stack. No stack requirements.

    The stack contents is printed top first, the last item printed is the lowest one inspected.

    array db_print

    The closest this module has to a print statement. It takes an array of strings and/or numbers off the top of the stack and prints them with a space in between each item.

        [ (myvar1=) myvar1 (str2=) str2 ] db_print

    will print something like the following.

        myvar= 23.4 str2= abc

    When printing something from the stack you need to take into account the array-building items, too. In the next example, at the point '2 index' fetches 111, the stack holds '222 111 [ (top=)' but 'index' requires 5 to get at 222 because the stack now holds '222 111 [ (top=) 111 (next=)'.

        222 111
        [ (top=) 2 index (next=) 5 index ] db_print

    willl output this.

        top= 111 next= 222
    It is important that the output does not exceed the string buffer size.  The default is 256, but it can be changed
    by giving B<new> the option C<bufsize>.

    x y msg db_point

    It is common to have coordinates as the top two items on the stack. This call inspects them. It pops the message off the stack, leaving x and y in place, then prints all three.

        450 666
        (starting point=) db_print

    would produce:

        starting point= ( 450 , 666 )

    array db_array

    Like db_print but the array is printed enclosed within square brackets.

    var db_where

    A 'where' search is made to find the dictionary containing var. The messages 'found' or 'not found' are output accordingly. Of course, var should be quoted with '/' to put the name on the stack, otherwise it will either be executed or force an error.


    Starts the next debugging column. No stack requirements.


    Enable debug output


    Disable debug output


    Does a 'carriage-return, line-feed'. No stack requirements.


    Moves output right by db_xtab. No stack requirements. Useful for indenting output within loops.


    Moves output left by db_xtab. No stack requirements.


    No functions are exported by default, they must be named as required.

        use PostScript::File qw(
                check_tilde check_file 
                incpage_label incpage_roman 
                array_as_string str

    incpage_label( label )

    The default function for set_incpage_handler which just increases the number passed to it. A useful side effect is that letters are also incremented.

    incpage_roman( label )

    An alternative function for set_incpage_handler which increments lower case roman numerals. It only handles values from ``i'' to ``xxxix'', but that should be quite enough for numbering the odd preface.

    check_file( file, [dir, [create]] )

    An optional fully qualified path-and-file or a simple file name. If omitted, the special file File::Spec->devnull() is returned.

    An optional directory dir. If present (and file is not already an absolute path), it is prepended to file.

    If non-zero, ensure the file exists. It may be necessary to set dir to ``'' or undef.

    This ensures the filename returned is valid and in a directory tree which is created if it doesn't exist.

    Any leading '~' is expanded to the users home directory. If no absolute directory is given either as part of file, it is placed within the current directory. Intervening directories are always created. If create is set, file is created as an empty file, possible erasing any previous file of the same name.

    File::Spec|File::Spec is used throughout so file access should be portable.

    check_tilde( dir )

    Expands any leading '~' to the home directory.

    array_as_string( array )

    Converts a perl array to its postscript representation.

    str( arrayref )

    Converts the referenced array to a string representation suitable for postscript code. If arrayref is not an array reference, it is passed through unchanged. This function was designed to simplify passing colours for the postscript function b<gpapercolor> which expects either an RGB array or a greyscale decimal. See gpapercolor in the PostScript::Graph::Paper manpage.


    Chris Willmot,

    Thanks to Johan Vromans for the ISOLatin1Encoding.


    PostScript Language Document Structuring Conventions Specification Version 3.0 published by Adobe, 1992.

    Encapsulated PostScript File Format Specification Version 3.0 published by Adobe, 1992.

    the PostScript::Graph::Paper manpage, the PostScript::Graph::Style manpage, the PostScript::Graph::Key manpage, the PostScript::Graph::XY manpage, the PostScript::Graph::Bar manpage. the PostScript::Graph::Stock manpage.

     PostScript::File - Base class for creating Adobe PostScript files