The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

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

VERSION

This document describes version 2.02 of PostScript::File, released December 24, 2010 as part of PostScript-File version 2.02.

SYNOPSIS

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

Simplest

An 'hello world' program:

    use PostScript::File;

    my $ps = PostScript::File->new();

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

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

All options

    my $ps = PostScript::File->new(
        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 => 'cp1252',
        font_suffix => '-iso',
        need_fonts  => [qw(Helvetica Helvetica-Bold)],

        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,
    );

DESCRIPTION

This module is designed to support other PostScript:: modules. For top level modules that output something useful, see

    PostScript::Calendar
    PostScript::Report
    PostScript::Graph::Bar
    PostScript::Graph::Stock
    PostScript::Graph::XY

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.

    get/set_bounding_box
    get/set_page_bounding_box
    get/set_page_clipping
    get/set_page_landscape
    set_page_margins
    get_ordinal
    get_pagecount
    draw_bounding_box
    clip_bounding_box

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

    add_comment
    add_preview
    add_default
    add_resource
    add_function
    add_setup
    add_page_setup
    add_to_page
    add_page_trailer
    add_trailer

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

    check_tilde
    check_file
    incpage_label
    incpage_roman

Hyphens and Minus Signs

In ASCII, the character \x2D (\055) is used as both a hyphen and a minus sign. Unicode calls this character HYPHEN-MINUS (U+002D). PostScript has two characters, which it calls /hyphen and /minus. The difference is that /minus is usually wider than /hyphen (except in Courier, of course).

In PostScript's StandardEncoding (what you get if you don't use "reencode"), character \x2D is /hyphen, and /minus is not available. In the Latin1-based encodings created by reencode, character \x2D is /minus, and character \xAD is /hyphen. (\xAD is supposed to be a "soft hyphen" (U+00AD) that appears only if the line is broken at that point, but it doesn't work that way in PostScript.)

Unicode has additional non-ambiguous characters: HYPHEN (U+2010), NON-BREAKING HYPHEN (U+2011), and MINUS SIGN (U+2212). The first two always indicate /hyphen, and the last is always /minus. When you set reencode to cp1252 or iso-8859-1, those characters will be handled automatically.

To make it easier to handle strings containing HYPHEN-MINUS, PostScript::File provides the "auto_hyphen" attribute. When this is true (the default when using cp1252 or iso-8859-1), the pstr method will automatically translate HYPHEN-MINUS to either HYPHEN or MINUS SIGN. (This happens only when pstr is called as an object method.)

The rule is that if a HYPHEN-MINUS is surrounded by whitespace, or surrounded by digits, or it's preceded by whitespace or punctuation and followed by a digit, or it's followed by a currency symbol, it's translated to MINUS SIGN. Otherwise, it's translated to HYPHEN.

CONSTRUCTOR

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.

Example

    $ps = PostScript::File->new(
                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.

debug

undef

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

0

db_ functions are replaced by dummy functions which do nothing.

1

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.

2

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)

headings

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

reencode

Requests that a font re-encode function be added and that the fonts used by this document get re-encoded in the specified encoding. The only allowed values are cp1252, iso-8859-1, and ISOLatin1Encoding. In most cases, you should set this to cp1252, even if you are not using Windows.

The list of fonts to re-encode comes from the need_fonts parameter, the need_resource method, and all fonts added using embed_font or add_resource. The Symbol font is never re-encoded, because it uses a non-standard character set.

Setting this to cp1252 or iso-8859-1 also causes the document to be encoded in that character set. Any strings you add to the document that have the UTF8 flag set will be reencoded automatically. Strings that do not have the UTF8 flag are expected to be in the correct character set already. This means that you should be able to set this to cp1252, use Unicode characters in your code and the "-iso" versions of the fonts, and just have it do the right thing.

Windows code page 1252 (aka WinLatin1) is a superset of the printable characters in iso-8859-1 (aka Latin1). It adds a number of characters that are not in Latin1, especially common punctuation marks like the curly quotation marks, en & em dashes, Euro sign, and ellipsis. These characters exist in the standard PostScript fonts, but there's no easy way to access them when using the standard or ISOLatin1 encodings. http://en.wikipedia.org/wiki/Windows-1252

For backwards compatibility with versions of PostScript::File older than 1.05, setting this to ISOLatin1Encoding reencodes the fonts, but does not do any character set translation in the document.

Initialization keys

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

bottom

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)

clip_command

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").

clipping

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

dir

An optional directory for the output file. See </set_filename>. If no file is specified, dir is ignored.

eps

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

file

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

file_ext

The extension for the output file. See </set_file_ext>.

font_suffix

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

The string value is appended to these to make the new names.

Example

    $ps = PostScript::File->new(
                font_suffix => "-iso",
                reencode => "ISOLatin1Encoding"
            );

"Courier" still has the standard mapping while "Courier-iso" includes the additional European characters.

height

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.

landscape

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.

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)

need_fonts

An arrayref of font names required by this document. This is equivalent to calling $ps->need_resource(font => @$arrayref). See need_resource for details.

paper

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")

You can also give a string in the form 'WIDTHxHEIGHT', where WIDTH and HEIGHT are numbers (in points). This sets the paper size to "Custom".

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)

top

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)

width

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.

db_active

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

db_base

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

db_bufsize

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

db_color

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

db_font

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

    Courier
    Courier-Bold
    Courier-BoldOblique
    Courier-Oblique
    Helvetica
    Helvetica-Bold
    Helvetica-BoldOblique
    Helvetica-Oblique
    Times-Roman
    Times-Bold
    Times-BoldItalic
    Times-Italic
    Symbol

db_fontsize

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

db_xgap

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.

db_xpos

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

db_xtab

The amount indented by db_indent. (Default: 10)

db_ytop

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.

errfont

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

errmsg

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

errsize

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

errx

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

erry

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.

extensions

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

langlevel

Set the PostScript language level. (No default)

order

Set the order the pages are defined in the document. It should one of "Ascend", "Descend" or "Special" if a document manager must not reorder the pages. (No default)

title

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

version

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)

Miscellaneous

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

incpage_handler

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

page

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

strip

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. none does no filtering. (Default: "space")

auto_hyphen

Controls whether the "pstr" method does hyphen-minus translation as described in "Hyphens and Minus Signs". This can only be enabled when the document is using character set translation. (Default: 1).

MAIN METHODS

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]] )

If filename is an open filehandle, write the PostScript document to that filehandle and return nothing.

If a filename has been given either here, to new, or to set_filename, write the PostScript document to that file and return its pathname.

If no filename has been given, or filename is undef, return the PostScript document as a string.

In eps mode, each page of the document becomes a separate EPS file. In list context, returns a list of these files (either the pathname or the PostScript code as explained above). In scalar context, only the first page is returned (but all pages will still be processed). If you pass a filehandle when you have multiple pages, all the documents are written to that filehandle, which is probably not what you want.

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

as_string

This returns the PostScript document as a string. It is equivalent to $ps->output(undef).

testable_output( [verbatim] )

This returns the PostScript document as a string, but with the PostScript::File generated code removed (unless verbatim is true). This is intended for use in test scripts, so they won't see changes in the output caused by different versions of PostScript::File. The PostScript code returned by this method will probably not work in a PostScript interpreter.

If verbatim is true, this is equivalent to $ps->output(undef).

ACCESS METHODS

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

get_auto_hyphen()

set_auto_hyphen( translate )

If translate is a true value, then "pstr" will do automatic hyphen-minus translation when called as an object method (but only if the document uses character set translation). See "Hyphens and Minus Signs".

get_filename()

set_filename( file, [dir] )

file

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

dir

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

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. (Unless you set the extension manually; see "set_file_ext".)

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

Example

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

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

    /home/chris/book/pics-vi.epsf
    /home/chris/book/pics-7.epsf
    /home/chris/book/pics-8.epsf

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

get_file_ext()

set_file_ext( file_ext )

If the file_ext is undef (the default), then the extension is set automatically based on the output type, as explained under "set_filename". If file_ext is the empty string, then no extension will be added to the filename. Otherwise, it should be a string like '.ps' or '.eps'. (But setting this has no effect on the actual type of the output file, only its name.)

get_metrics( font, [size, [encoding]] )

Construct a PostScript::File::Metrics object for font. The encoding is normally determined automatically from the font name and the document's encoding. The default size is 1000.

If this document uses "reencode", and the font ends with "font_suffix", then the Metrics object will use that encoding. Otherwise, the encoding is std (except for the Symbol font, which always uses sym).

No matter what encoding the font uses, the Metrics object will always use the same Unicode translation setting as this document. It also inherits the current value of the "auto_hyphen" attribute.

get_strip

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)

get_page_label()

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.

get_incpage_handler()

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:

    \&PostScript::File::incpage_label
    \&PostScript::File::incpage_roman

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.

get_bounding_box()

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.

get_ordinal( [page] )

Return the internal number for the page label specified. (Default: current page)

Example

Say pages are numbered "i", "ii", "iii, "iv", "1", "2", "3".

    get_ordinal("i") == 0
    get_ordinal("iv") == 3
    get_ordinal("1") == 4

get_pagecount()

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.

get_variable

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.

get_page_variable

Retrieve a user defined value.

CONTENT METHODS

get_comments()

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 not otherwise supported can be added. The comment should be the bare PostScript DSC name and value, with additional lines merely prefixed by +.

Programs written for older versions of PostScript::File might use this to add a DocumentNeededResources comment. That is now deprecated; you should use need_resource instead.

Example

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

get_preview()

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.

get_defaults()

add_default( default )

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

get_resources()

add_resource( type, name, params, resource )

type

A string indicating the DSC type of the resource. It should be one of Document, Feature, encoding, file, font, form, or pattern (case sensitive).

name

An arbitrary identifier of this resource. (For a Font, it must be the PostScript name of the font, without a leading slash.)

params

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

resource

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

Use this to add fonts or images (although you may prefer embed_font or embed_document). add_function is provided for functions.

Example

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

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

get_functions()

add_function( name, code, [version, [revision]] )

Add a ProcSet containing 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. If the document already contains ProcSet name (as reported by has_function, then add_function does nothing.

version is a real number, and revision is an integer. They both default to 0. PostScript::File does not make any use of these, but a PostScript document manager may assume that a procset with a higher revision number may be substituted for a procset with the same name and version but a lower revision.

Returns true if the ProcSet was added, or false if it already existed.

Example

    $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
    END_FUNCTIONS

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

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".

embed_document( filename )

This reads the contents of filename, which should be a PostScript file. It returns a string with the contents of the file surrounded by %%BeginDocument and %%EndDocument comments, and adds filename to the list of document supplied resources.

You must pass the returned string to add_to_page or some other method that will actually include it in the document.

embed_font( filename, [type] )

This reads the contents of filename, which must contain a PostScript font. It calls add_resource to add the font to the document, and returns the name of the font (without a leading slash).

If type is omitted, the filename's extension is used as the type. Type names are not case sensitive. The currently supported types are:

PFA

A PostScript font in ASCII format

PFB

A PostScript font in binary format. This requires the t1ascii program from http://www.lcdf.org/type/#t1utils. (You can set $PostScript::File::t1ascii to the name of the program to use. It defaults to t1ascii.)

TTF

A TrueType font. This requires the ttftotype42 program from http://www.lcdf.org/type/#typetools. (You can set $PostScript::File::ttftotype42 to the name of the program to use. It defaults to ttftotype42.)

Since TrueType (aka Type42) font support was introduced in PostScript level 2, embedding a TTF font automatically sets langlevel to 2 (unless it was already set to a higher level). Be aware that not all printers can handle Type42 fonts. (Even PostScript level 2 printers need not support them.) Ghostscript does support Type42 fonts (when compiled with the ttfont option).

need_resource( type, resource... )

This adds a resource to the DocumentNeededResources comment. type is one of encoding, file, font, form, pattern, or procset (case sensitive).

Any number of resources (of a single type) may be added in one call. For most types, resource is just the resource name. But for procset, each resource should be an arrayref of 3 elements: [name, version, revision]. Names that contain special characters such as spaces will be quoted automatically.

If need_resource is never called for the font type (and need_fonts is not used), it assumes the document requires all 13 of the standard PostScript fonts: Courier, Courier-Bold, Courier-BoldOblique, Courier-Oblique, Helvetica, Helvetica-Bold, Helvetica-BoldOblique, Helvetica-Oblique, Times-Roman, Times-Bold, Times-BoldItalic, Times-Italic, and Symbol. But this behaviour is deprecated; a document should explicitly list the fonts it requires. If you don't use any of the standard fonts, pass need_fonts => [] to the constructor (or call $ps->need_resource('font')) to indicate that.

get_setup()

add_setup( code )

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

get_page_setup()

add_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".

Examples

    $ps->add_to_page( <<END_PAGE );
        ...PostScript building this page
    END_PAGE

    $ps->add_to_page( "3", <<END_PAGE );
        ...PostScript building page 3
    END_PAGE

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.

get_page_trailer()

add_page_trailer( code )

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

get_trailer()

add_trailer( code )

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

POSTSCRIPT DEBUGGING SUPPORT

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
    end
    (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->draw_bounding_box();
    $ps->add_to_page( <<END_CODE );
        ...
        my_l my_b my_r my_t cliptobox
        ...
    END_CODE
    $ps->clip_bounding_box();

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

db_stack

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 new the option 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
    moveto

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.

db_newcol

Starts the next debugging column. No stack requirements.

db_on

Enable debug output

db_off

Disable debug output

db_down

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

db_indent

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

db_unindent

Moves output left by db_xtab. No stack requirements.

EXPORTED FUNCTIONS

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]] )

file

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

dir

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

create

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 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 PostScript::Graph::Paper.

pstr( string )

Converts the string to a string representation suitable for PostScript code. If the result is more than 240 characters, it will be broken into multiple lines. (A PostScript file should not contain lines with more than 255 characters.)

This may also be called as a class or object method. In this case, you can pass a second parameter nowrap. If this optional parameter is true, then the string will not be wrapped.

When called as an object method, pstr will do automatic hyphen-minus translation if "auto_hyphen" is true. This has the side-effect of setting the UTF8 flag on the returned string. (If the UTF8 flag was not set on the input string, it will be decoded using the document's character set.) See "Hyphens and Minus Signs".

quote_text( string )

Quotes the string if it contains special characters, making it suitable for a DSC comment. Strings without special characters are returned unchanged.

This may also be called as a class or object method.

BUGS AND LIMITATIONS

When making EPS files, the landscape transformation throws the coordinates off. To work around this, avoid the landscape flag and set width and height differently.

Most of these functions have only had a couple of tests, so please feel free to report all you find.

AUTHOR

Chris Willmot <chris AT willmot.co.uk>

Thanks to Johan Vromans for the ISOLatin1Encoding.

As of September 2009, PostScript::File is now being maintained by Christopher J. Madsen <perl AT cjmweb.net>.

Please report any bugs or feature requests to <bug-PostScript-File AT rt.cpan.org>, or through the web interface at http://rt.cpan.org/Public/Bug/Report.html?Queue=PostScript-File

You can follow or contribute to PostScript::File's development at http://github.com/madsen/postscript-file.

COPYRIGHT AND LICENSE

Copyright 2002, 2003 Christopher P Willmot. All rights reserved.

Copyright 2010 Christopher J. Madsen. All rights reserved.

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

SEE ALSO

PostScript Language Document Structuring Conventions Specification Version 3.0 and Encapsulated PostScript File Format Specification Version 3.0 published by Adobe, 1992. http://partners.adobe.com/asn/developer/technotes/postscript.html

PostScript::Convert, for PDF or PNG output.

PostScript::Graph::Paper, PostScript::Graph::Style, PostScript::Graph::Key, PostScript::Graph::XY, PostScript::Graph::Bar. PostScript::Graph::Stock. PostScript::Calendar. PostScript::Report.

DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENSE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

3 POD Errors

The following errors were encountered while parsing the POD:

Around line 2063:

Expected text after =item, not a number

Around line 2067:

Expected text after =item, not a number

Around line 2075:

Expected text after =item, not a number