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

use strict;
no warnings qw[ deprecated recursion uninitialized ];

our $VERSION = '2.033'; # VERSION

use Carp;
use Encode qw(:all);
use FileHandle;

use PDF::API2::Basic::PDF::Utils;
use PDF::API2::Util;

use PDF::API2::Basic::PDF::File;
use PDF::API2::Basic::PDF::Pages;
use PDF::API2::Page;

use PDF::API2::Resource::XObject::Form::Hybrid;

use PDF::API2::Resource::ExtGState;
use PDF::API2::Resource::Pattern;
use PDF::API2::Resource::Shading;

use PDF::API2::NamedDestination;

use Scalar::Util qw(weaken);

our @FontDirs = ( (map { "$_/PDF/API2/fonts" } @INC),
                  qw[ /usr/share/fonts /usr/local/share/fonts c:/windows/fonts c:/winnt/fonts ] );

=head1 NAME

PDF::API2 - Facilitates the creation and modification of PDF files

=head1 SYNOPSIS

    use PDF::API2;

    # Create a blank PDF file
    $pdf = PDF::API2-&gt;new();

    # Open an existing PDF file
    $pdf = PDF::API2-&gt;open('some.pdf');

    # Add a blank page
    $page = $pdf-&gt;page();

    # Retrieve an existing page
    $page = $pdf-&gt;openpage($page_number);

    # Set the page size
    $page-&gt;mediabox('Letter');

    # Add a built-in font to the PDF
    $font = $pdf-&gt;corefont('Helvetica-Bold');

    # Add an external TTF font to the PDF
    $font = $pdf-&gt;ttfont('/path/to/font.ttf');

    # Add some text to the page
    $text = $page-&gt;text();
    $text-&gt;font($font, 20);
    $text-&gt;translate(200, 700);
    $text-&gt;text('Hello World!');

    # Save the PDF
    $pdf-&gt;saveas('/path/to/new.pdf');

=head1 GENERIC METHODS

=over

=item $pdf = PDF::API2-&gt;new(%options)

Creates a new PDF object.  If you will be saving it as a file and
already know the filename, you can give the '-file' option to minimize
possible memory requirements later on.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new();
    ...
    print $pdf-&gt;stringify();

    $pdf = PDF::API2-&gt;new();
    ...
    $pdf-&gt;saveas('our/new.pdf');

    $pdf = PDF::API2-&gt;new(-file =&gt; 'our/new.pdf');
    ...
    $pdf-&gt;save();

=cut

sub new {
    my ($class, %options) = @_;

    my $self = {};
    bless $self, $class;
    $self-&gt;{'pdf'} = PDF::API2::Basic::PDF::File-&gt;new();

    $self-&gt;{'pdf'}-&gt;{' version'} = 4;
    $self-&gt;{'pages'} = PDF::API2::Basic::PDF::Pages-&gt;new($self-&gt;{'pdf'});
    $self-&gt;{'pages'}-&gt;proc_set(qw(PDF Text ImageB ImageC ImageI));
    $self-&gt;{'pages'}-&gt;{'Resources'} ||= PDFDict();
    $self-&gt;{'pdf'}-&gt;new_obj($self-&gt;{'pages'}-&gt;{'Resources'}) unless $self-&gt;{'pages'}-&gt;{'Resources'}-&gt;is_obj($self-&gt;{'pdf'});
    $self-&gt;{'catalog'} = $self-&gt;{'pdf'}-&gt;{'Root'};
    weaken $self-&gt;{'catalog'};
    $self-&gt;{'fonts'} = {};
    $self-&gt;{'pagestack'} = [];
    $self-&gt;{'forcecompress'} = 1;
    $self-&gt;preferences(%options);
    if ($options{'-file'}) {
        $self-&gt;{' filed'} = $options{'-file'};
        $self-&gt;{'pdf'}-&gt;create_file($options{'-file'});
    }
    $self-&gt;{'infoMeta'}=[qw(Author CreationDate ModDate Creator Producer Title Subject Keywords)];

    my $version = eval { $PDF::API2::VERSION } || '(Unreleased Version)';
    $self-&gt;info('Producer' =&gt; "PDF::API2 $version [$^O]");

    return $self;
}

=item $pdf = PDF::API2-&gt;open($pdf_file)

Opens an existing PDF file.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;open('our/old.pdf');
    ...
    $pdf-&gt;saveas('our/new.pdf');

    $pdf = PDF::API2-&gt;open('our/to/be/updated.pdf');
    ...
    $pdf-&gt;update();

=cut

sub open {
    my ($class, $file, %options) = @_;
    croak "File '$file' does not exist" unless -f $file;
    croak "File '$file' is not readable" unless -r $file;

    my $content;
    my $scalar_fh = FileHandle-&gt;new();
    CORE::open($scalar_fh, '+&lt;', \$content) or die "Can't begin scalar IO";
    binmode $scalar_fh, ':raw';

    my $disk_fh = FileHandle-&gt;new();
    CORE::open($disk_fh, '&lt;', $file) or die "Can't open $file for reading: $!";
    binmode $disk_fh, ':raw';
    $disk_fh-&gt;seek(0, 0);
    my $data;
    while (not $disk_fh-&gt;eof()) {
        $disk_fh-&gt;read($data, 512);
        $scalar_fh-&gt;print($data);
    }
    $disk_fh-&gt;close();
    $scalar_fh-&gt;seek(0, 0);

    my $self = $class-&gt;open_scalar($content, %options);
    $self-&gt;{'pdf'}-&gt;{' fname'} = $file;

    return $self;
}

=item $pdf = PDF::API2-&gt;open_scalar($pdf_string)

Opens a PDF contained in a string.

B&lt;Example:&gt;

    # Read a PDF into a string, for the purpose of demonstration
    open $fh, 'our/old.pdf' or die $@;
    undef $/;  # Read the whole file at once
    $pdf_string = &lt;$fh&gt;;

    $pdf = PDF::API2-&gt;open_scalar($pdf_string);
    ...
    $pdf-&gt;saveas('our/new.pdf');

=cut

# Deprecated (renamed)
sub openScalar { return open_scalar(@_); } ## no critic

sub open_scalar {
    my ($class, $content, %options) = @_;

    my $self = {};
    bless $self, $class;
    foreach my $parameter (keys %options) {
        $self-&gt;default($parameter, $options{$parameter});
    }

    $self-&gt;{'content_ref'} = \$content;
    my $fh;
    CORE::open($fh, '+&lt;', \$content) or die "Can't begin scalar IO";

    $self-&gt;{'pdf'} = PDF::API2::Basic::PDF::File-&gt;open($fh, 1);
    $self-&gt;{'pdf'}-&gt;{'Root'}-&gt;realise();
    $self-&gt;{'pages'} = $self-&gt;{'pdf'}-&gt;{'Root'}-&gt;{'Pages'}-&gt;realise();
    weaken $self-&gt;{'pages'};
    $self-&gt;{'pdf'}-&gt;{' version'} ||= 3;
    my @pages = proc_pages($self-&gt;{'pdf'}, $self-&gt;{'pages'});
    $self-&gt;{'pagestack'} = [sort { $a-&gt;{' pnum'} &lt;=&gt; $b-&gt;{' pnum'} } @pages];
    weaken $self-&gt;{'pagestack'}-&gt;[$_] for (0 .. scalar @{$self-&gt;{'pagestack'}});
    $self-&gt;{'catalog'} = $self-&gt;{'pdf'}-&gt;{'Root'};
    weaken $self-&gt;{'catalog'};
    $self-&gt;{'reopened'} = 1;
    $self-&gt;{'forcecompress'} = 1;
    $self-&gt;{'fonts'} = {};
    $self-&gt;{'infoMeta'} = [qw(Author CreationDate ModDate Creator Producer Title Subject Keywords)];

    return $self;
}

=item $pdf-&gt;preferences(%options)

Controls viewing preferences for the PDF.

B&lt;Page Mode Options:&gt;

=over

=item -fullscreen

Full-screen mode, with no menu bar, window controls, or any other window visible.

=item -thumbs

Thumbnail images visible.

=item -outlines

Document outline visible.

=back

B&lt;Page Layout Options:&gt;

=over

=item -singlepage

Display one page at a time.

=item -onecolumn

Display the pages in one column.

=item -twocolumnleft

Display the pages in two columns, with oddnumbered pages on the left.

=item -twocolumnright

Display the pages in two columns, with oddnumbered pages on the right.

=back

B&lt;Viewer Options:&gt;

=over

=item -hidetoolbar

Specifying whether to hide tool bars.

=item -hidemenubar

Specifying whether to hide menu bars.

=item -hidewindowui

Specifying whether to hide user interface elements.

=item -fitwindow

Specifying whether to resize the document's window to the size of the displayed page.

=item -centerwindow

Specifying whether to position the document's window in the center of the screen.

=item -displaytitle

Specifying whether the window's title bar should display the
document title taken from the Title entry of the document information
dictionary.

=item -afterfullscreenthumbs

Thumbnail images visible after Full-screen mode.

=item -afterfullscreenoutlines

Document outline visible after Full-screen mode.

=item -printscalingnone

Set the default print setting for page scaling to none.

=item -simplex

Print single-sided by default.

=item -duplexflipshortedge

Print duplex by default and flip on the short edge of the sheet.

=item -duplexfliplongedge

Print duplex by default and flip on the long edge of the sheet.

=back

B&lt;Initial Page Options&gt;:

=over

=item -firstpage =&gt; [ $page, %options ]

Specifying the page (either a page number or a page object) to be
displayed, plus one of the following options:

=over

=item -fit =&gt; 1

Display the page designated by page, with its contents magnified just
enough to fit the entire page within the window both horizontally and
vertically. If the required horizontal and vertical magnification
factors are different, use the smaller of the two, centering the page
within the window in the other dimension.

=item -fith =&gt; $top

Display the page designated by page, with the vertical coordinate top
positioned at the top edge of the window and the contents of the page
magnified just enough to fit the entire width of the page within the
window.

=item -fitv =&gt; $left

Display the page designated by page, with the horizontal coordinate
left positioned at the left edge of the window and the contents of the
page magnified just enough to fit the entire height of the page within
the window.

=item -fitr =&gt; [ $left, $bottom, $right, $top ]

Display the page designated by page, with its contents magnified just
enough to fit the rectangle specified by the coordinates left, bottom,
right, and top entirely within the window both horizontally and
vertically. If the required horizontal and vertical magnification
factors are different, use the smaller of the two, centering the
rectangle within the window in the other dimension.

=item -fitb =&gt; 1

Display the page designated by page, with its contents magnified just
enough to fit its bounding box entirely within the window both
horizontally and vertically. If the required horizontal and vertical
magnification factors are different, use the smaller of the two,
centering the bounding box within the window in the other dimension.

=item -fitbh =&gt; $top

Display the page designated by page, with the vertical coordinate top
positioned at the top edge of the window and the contents of the page
magnified just enough to fit the entire width of its bounding box
within the window.

=item -fitbv =&gt; $left

Display the page designated by page, with the horizontal coordinate
left positioned at the left edge of the window and the contents of the
page magnified just enough to fit the entire height of its bounding
box within the window.

=item -xyz =&gt; [ $left, $top, $zoom ]

Display the page designated by page, with the coordinates (left, top)
positioned at the top-left corner of the window and the contents of
the page magnified by the factor zoom. A zero (0) value for any of the
parameters left, top, or zoom specifies that the current value of that
parameter is to be retained unchanged.

=back

=back

B&lt;Example:&gt;

    $pdf-&gt;preferences(
        -fullscreen =&gt; 1,
        -onecolumn =&gt; 1,
        -afterfullscreenoutlines =&gt; 1,
        -firstpage =&gt; [$page, -fit =&gt; 1],
    );

=cut

sub preferences {
    my ($self, %options) = @_;

    # Page Mode Options
    if ($options{'-fullscreen'}) {
        $self-&gt;{'catalog'}-&gt;{'PageMode'} = PDFName('FullScreen');
    }
    elsif ($options{'-thumbs'}) {
        $self-&gt;{'catalog'}-&gt;{'PageMode'} = PDFName('UseThumbs');
    }
    elsif ($options{'-outlines'}) {
        $self-&gt;{'catalog'}-&gt;{'PageMode'} = PDFName('UseOutlines');
    }
    else {
        $self-&gt;{'catalog'}-&gt;{'PageMode'} = PDFName('UseNone');
    }

    # Page Layout Options
    if ($options{'-singlepage'}) {
        $self-&gt;{'catalog'}-&gt;{'PageLayout'} = PDFName('SinglePage');
    }
    elsif ($options{'-onecolumn'}) {
        $self-&gt;{'catalog'}-&gt;{'PageLayout'} = PDFName('OneColumn');
    }
    elsif ($options{'-twocolumnleft'}) {
        $self-&gt;{'catalog'}-&gt;{'PageLayout'} = PDFName('TwoColumnLeft');
    }
    elsif ($options{'-twocolumnright'}) {
        $self-&gt;{'catalog'}-&gt;{'PageLayout'} = PDFName('TwoColumnRight');
    }
    else {
        $self-&gt;{'catalog'}-&gt;{'PageLayout'} = PDFName('SinglePage');
    }

    # Viewer Preferences
    $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'} ||= PDFDict();
    $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;realise();

    if ($options{'-hidetoolbar'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'HideToolbar'} = PDFBool(1);
    }
    if ($options{'-hidemenubar'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'HideMenubar'} = PDFBool(1);
    }
    if ($options{'-hidewindowui'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'HideWindowUI'} = PDFBool(1);
    }
    if ($options{'-fitwindow'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'FitWindow'} = PDFBool(1);
    }
    if ($options{'-centerwindow'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'CenterWindow'} = PDFBool(1);
    }
    if ($options{'-displaytitle'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'DisplayDocTitle'} = PDFBool(1);
    }
    if ($options{'-righttoleft'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'Direction'} = PDFName('R2L');
    }

    if ($options{'-afterfullscreenthumbs'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'NonFullScreenPageMode'} = PDFName('UseThumbs');
    }
    elsif ($options{'-afterfullscreenoutlines'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'NonFullScreenPageMode'} = PDFName('UseOutlines');
    }
    else {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'NonFullScreenPageMode'} = PDFName('UseNone');
    }

    if ($options{'-printscalingnone'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'PrintScaling'} = PDFName('None');
    }

    if ($options{'-simplex'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'Duplex'} = PDFName('Simplex');
    }
    elsif ($options{'-duplexfliplongedge'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'Duplex'} = PDFName('DuplexFlipLongEdge');
    }
    elsif ($options{'-duplexflipshortedge'}) {
        $self-&gt;{'catalog'}-&gt;{'ViewerPreferences'}-&gt;{'Duplex'} = PDFName('DuplexFlipShortEdge');
    }

    # Open Action
    if ($options{'-firstpage'}) {
        my ($page, %args) = @{$options{-firstpage}};
        $args{'-fit'} = 1 unless scalar keys %args;

        # $page can be either a page number (which needs to be wrapped
        # in PDFNum) or a page object (which doesn't).
        $page = PDFNum($page) unless ref($page);

        if (defined $args{'-fit'}) {
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('Fit'));
        }
        elsif (defined $args{'-fith'}) {
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('FitH'), PDFNum($args{'-fith'}));
        }
        elsif (defined $args{'-fitb'}) {
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('FitB'));
        }
        elsif (defined $args{'-fitbh'}) {
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('FitBH'), PDFNum($args{'-fitbh'}));
        }
        elsif (defined $args{'-fitv'}) {
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('FitV'), PDFNum($args{'-fitv'}));
        }
        elsif (defined $args{'-fitbv'}) {
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('FitBV'), PDFNum($args{'-fitbv'}));
        }
        elsif (defined $args{'-fitr'}) {
            croak 'insufficient parameters to -fitr =&gt; []' unless scalar @{$args{'-fitr'}} == 4;
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('FitR'), map { PDFNum($_) } @{$args{'-fitr'}});
        }
        elsif (defined $args{'-xyz'}) {
            croak 'insufficient parameters to -xyz =&gt; []' unless scalar @{$args{'-xyz'}} == 3;
            $self-&gt;{'catalog'}-&gt;{'OpenAction'} = PDFArray($page, PDFName('XYZ'), map { PDFNum($_) } @{$args{'-xyz'}});
        }
    }
    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'catalog'});

    return $self;
}

=item $val = $pdf-&gt;default($parameter)

=item $pdf-&gt;default($parameter, $value)

Gets/sets the default value for a behaviour of PDF::API2.

B&lt;Supported Parameters:&gt;

=over

=item nounrotate

prohibits API2 from rotating imported/opened page to re-create a
default pdf-context.

=item pageencaps

enables than API2 will add save/restore commands upon imported/opened
pages to preserve graphics-state for modification.

=item copyannots

enables importing of annotations (B&lt;*EXPERIMENTAL*&gt;).

=back

=cut

sub default {
    my ($self, $parameter, $value) = @_;

    # Parameter names may consist of lowercase letters, numbers, and underscores
    $parameter = lc $parameter;
    $parameter =~ s/[^a-z\d_]//g;

    my $previous_value = $self-&gt;{$parameter};
    if (defined $value) {
        $self-&gt;{$parameter} = $value;
    }
    return $previous_value;
}

=item $version = $pdf-&gt;version([$new_version])

Get/set the PDF version (e.g. 1.4)

=cut

sub version {
    my $self = shift();
    if (scalar @_) {
        my $version = shift();
        croak "Invalid version $version" unless $version =~ /^(?:1\.)?([0-9]+)$/;
        $self-&gt;{'pdf'}-&gt;{' version'} = $1;
    }
    return '1.' . $self-&gt;{'pdf'}-&gt;{' version'};
}

=item $bool = $pdf-&gt;isEncrypted()

Checks if the previously opened PDF is encrypted.

=cut

sub isEncrypted {
    my $self = shift();
    return defined($self-&gt;{'pdf'}-&gt;{'Encrypt'}) ? 1 : 0;
}

=item %infohash = $pdf-&gt;info(%infohash)

Gets/sets the info structure of the document.

B&lt;Example:&gt;

    %h = $pdf-&gt;info(
        'Author'       =&gt; "Alfred Reibenschuh",
        'CreationDate' =&gt; "D:20020911000000+01'00'",
        'ModDate'      =&gt; "D:YYYYMMDDhhmmssOHH'mm'",
        'Creator'      =&gt; "fredos-script.pl",
        'Producer'     =&gt; "PDF::API2",
        'Title'        =&gt; "some Publication",
        'Subject'      =&gt; "perl ?",
        'Keywords'     =&gt; "all good things are pdf"
    );
    print "Author: $h{Author}\n";

=cut

sub info {
    my ($self, %opt) = @_;

    if (not defined($self-&gt;{'pdf'}-&gt;{'Info'})) {
        $self-&gt;{'pdf'}-&gt;{'Info'} = PDFDict();
        $self-&gt;{'pdf'}-&gt;new_obj($self-&gt;{'pdf'}-&gt;{'Info'});
    }
    else {
        $self-&gt;{'pdf'}-&gt;{'Info'}-&gt;realise();
    }

    # Maintenance Note: Since we're not shifting at the beginning of
    # this sub, this "if" will always be true
    if (scalar @_) {
        foreach my $k (@{$self-&gt;{'infoMeta'}}) {
            next unless defined $opt{$k};
            if (is_utf8($opt{$k})) {
                $self-&gt;{'pdf'}-&gt;{'Info'}-&gt;{$k} = PDFUtf($opt{$k} || 'NONE');
            }
            #elsif (is_utf8($opt{$k}) || utf8::valid($opt{$k})) {
            #    $self-&gt;{'pdf'}-&gt;{'Info'}-&gt;{$k} = PDFUtf($opt{$k} || 'NONE');
            #}
            else {
                $self-&gt;{'pdf'}-&gt;{'Info'}-&gt;{$k} = PDFStr($opt{$k} || 'NONE');
            }
        }
        $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pdf'}-&gt;{'Info'});
    }

    if (defined $self-&gt;{'pdf'}-&gt;{'Info'}) {
        %opt = ();
        foreach my $k (@{$self-&gt;{'infoMeta'}}) {
            next unless defined $self-&gt;{'pdf'}-&gt;{'Info'}-&gt;{$k};
            $opt{$k} = $self-&gt;{'pdf'}-&gt;{'Info'}-&gt;{$k}-&gt;val();
            if ((unpack('n', $opt{$k}) == 0xfffe) or (unpack('n', $opt{$k}) == 0xfeff)) {
                $opt{$k} = decode('UTF-16', $self-&gt;{'pdf'}-&gt;{'Info'}-&gt;{$k}-&gt;val());
            }
        }
    }

    return %opt;
}

=item @metadata_attributes = $pdf-&gt;infoMetaAttributes(@metadata_attributes)

Gets/sets the supported info-structure tags.

B&lt;Example:&gt;

    @attributes = $pdf-&gt;infoMetaAttributes;
    print "Supported Attributes: @attr\n";

    @attributes = $pdf-&gt;infoMetaAttributes('CustomField1');
    print "Supported Attributes: @attributes\n";

=cut

sub infoMetaAttributes {
    my ($self, @attr) = @_;

    if (scalar @attr) {
        my %at = map { $_ =&gt; 1 } @{$self-&gt;{'infoMeta'}}, @attr;
        @{$self-&gt;{'infoMeta'}} = keys %at;
    }

    return @{$self-&gt;{'infoMeta'}};
}

=item $xml = $pdf-&gt;xmpMetadata($xml)

Gets/sets the XMP XML data stream.

B&lt;Example:&gt;

    $xml = $pdf-&gt;xmpMetadata();
    print "PDFs Metadata reads: $xml\n";
    $xml=&lt;&lt;EOT;
    &lt;?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?&gt;
    &lt;?adobe-xap-filters esc="CRLF"?&gt;
    &lt;x:xmpmeta
      xmlns:x='adobe:ns:meta/'
      x:xmptk='XMP toolkit 2.9.1-14, framework 1.6'&gt;
        &lt;rdf:RDF
          xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
          xmlns:iX='http://ns.adobe.com/iX/1.0/'&gt;
            &lt;rdf:Description
              rdf:about='uuid:b8659d3a-369e-11d9-b951-000393c97fd8'
              xmlns:pdf='http://ns.adobe.com/pdf/1.3/'
              pdf:Producer='Acrobat Distiller 6.0.1 for Macintosh'&gt;&lt;/rdf:Description&gt;
            &lt;rdf:Description
              rdf:about='uuid:b8659d3a-369e-11d9-b951-000393c97fd8'
              xmlns:xap='http://ns.adobe.com/xap/1.0/'
              xap:CreateDate='2004-11-14T08:41:16Z'
              xap:ModifyDate='2004-11-14T16:38:50-08:00'
              xap:CreatorTool='FrameMaker 7.0'
              xap:MetadataDate='2004-11-14T16:38:50-08:00'&gt;&lt;/rdf:Description&gt;
            &lt;rdf:Description
              rdf:about='uuid:b8659d3a-369e-11d9-b951-000393c97fd8'
              xmlns:xapMM='http://ns.adobe.com/xap/1.0/mm/'
              xapMM:DocumentID='uuid:919b9378-369c-11d9-a2b5-000393c97fd8'/&gt;&lt;/rdf:Description&gt;
            &lt;rdf:Description
              rdf:about='uuid:b8659d3a-369e-11d9-b951-000393c97fd8'
              xmlns:dc='http://purl.org/dc/elements/1.1/'
              dc:format='application/pdf'&gt;
                &lt;dc:description&gt;
                  &lt;rdf:Alt&gt;
                    &lt;rdf:li xml:lang='x-default'&gt;Adobe Portable Document Format (PDF)&lt;/rdf:li&gt;
                  &lt;/rdf:Alt&gt;
                &lt;/dc:description&gt;
                &lt;dc:creator&gt;
                  &lt;rdf:Seq&gt;
                    &lt;rdf:li&gt;Adobe Systems Incorporated&lt;/rdf:li&gt;
                  &lt;/rdf:Seq&gt;
                &lt;/dc:creator&gt;
                &lt;dc:title&gt;
                  &lt;rdf:Alt&gt;
                    &lt;rdf:li xml:lang='x-default'&gt;PDF Reference, version 1.6&lt;/rdf:li&gt;
                  &lt;/rdf:Alt&gt;
                &lt;/dc:title&gt;
            &lt;/rdf:Description&gt;
        &lt;/rdf:RDF&gt;
    &lt;/x:xmpmeta&gt;
    &lt;?xpacket end='w'?&gt;
    EOT

    $xml = $pdf-&gt;xmpMetadata($xml);
    print "PDF metadata now reads: $xml\n";

=cut

sub xmpMetadata {
    my ($self, $value) = @_;

    if (not defined($self-&gt;{'catalog'}-&gt;{'Metadata'})) {
        $self-&gt;{'catalog'}-&gt;{'Metadata'} = PDFDict();
        $self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;{'Type'} = PDFName('Metadata');
        $self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;{'Subtype'} = PDFName('XML');
        $self-&gt;{'pdf'}-&gt;new_obj($self-&gt;{'catalog'}-&gt;{'Metadata'});
    }
    else {
        $self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;realise();
        $self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;{' stream'} = unfilter($self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;{'Filter'}, $self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;{' stream'});
        delete $self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;{' nofilt'};
        delete $self-&gt;{'catalog'}-&gt;{'Metadata'}-&gt;{'Filter'};
    }

    my $md = $self-&gt;{'catalog'}-&gt;{'Metadata'};

    if (defined $value) {
        $md-&gt;{' stream'} = $value;
        delete $md-&gt;{'Filter'};
        delete $md-&gt;{' nofilt'};
        $self-&gt;{'pdf'}-&gt;out_obj($md);
        $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'catalog'});
    }

    return $md-&gt;{' stream'};
}

=item $pdf-&gt;pageLabel($index, $options)

Sets page label options.

B&lt;Supported Options:&gt;

=over

=item -style

Roman, roman, decimal, Alpha or alpha.

=item -start

Restart numbering at given number.

=item -prefix

Text prefix for numbering.

=back

B&lt;Example:&gt;

    # Start with Roman Numerals
    $pdf-&gt;pageLabel(0, {
        -style =&gt; 'roman',
    });

    # Switch to Arabic
    $pdf-&gt;pageLabel(4, {
        -style =&gt; 'decimal',
    });

    # Numbering for Appendix A
    $pdf-&gt;pageLabel(32, {
        -start =&gt; 1,
        -prefix =&gt; 'A-'
    });

    # Numbering for Appendix B
    $pdf-&gt;pageLabel( 36, {
        -start =&gt; 1,
        -prefix =&gt; 'B-'
    });

    # Numbering for the Index
    $pdf-&gt;pageLabel(40, {
        -style =&gt; 'Roman'
        -start =&gt; 1,
        -prefix =&gt; 'Index '
    });

=cut

sub pageLabel {
    my $self = shift();

    $self-&gt;{'catalog'}-&gt;{'PageLabels'} ||= PDFDict();
    $self-&gt;{'catalog'}-&gt;{'PageLabels'}-&gt;{'Nums'} ||= PDFArray();

    my $nums = $self-&gt;{'catalog'}-&gt;{'PageLabels'}-&gt;{'Nums'};
    while (scalar @_) {
        my $index = shift();
        my $opts = shift();

        $nums-&gt;add_elements(PDFNum($index));

        my $d = PDFDict();
        $d-&gt;{'S'} = PDFName($opts-&gt;{'-style'} eq 'Roman' ? 'R' :
                            $opts-&gt;{'-style'} eq 'roman' ? 'r' :
                            $opts-&gt;{'-style'} eq 'Alpha' ? 'A' :
                            $opts-&gt;{'-style'} eq 'alpha' ? 'a' : 'D');

        if (defined $opts-&gt;{'-prefix'}) {
            $d-&gt;{'P'} = PDFStr($opts-&gt;{'-prefix'});
        }

        if (defined $opts-&gt;{'-start'}) {
            $d-&gt;{'St'} = PDFNum($opts-&gt;{'-start'});
        }

        $nums-&gt;add_elements($d);
    }
}

=item $pdf-&gt;finishobjects(@objects)

Force objects to be written to file if possible.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new(-file =&gt; 'our/new.pdf');
    ...
    $pdf-&gt;finishobjects($page, $gfx, $txt);
    ...
    $pdf-&gt;save();

=cut

sub finishobjects {
    my ($self, @objs) = @_;

    if ($self-&gt;{'reopened'}) {
        die "invalid method invocation: no file, use 'saveas' instead.";
    }
    elsif ($self-&gt;{' filed'}) {
        $self-&gt;{'pdf'}-&gt;ship_out(@objs);
    }
    else {
        die "invalid method invocation: no file, use 'saveas' instead.";
    }
}

sub proc_pages {
    my ($pdf, $object) = @_;

    if (defined $object-&gt;{'Resources'}) {
        eval {
            $object-&gt;{'Resources'}-&gt;realise();
        };
    }

    my @pages;
    $pdf-&gt;{' apipagecount'} ||= 0;
    foreach my $page ($object-&gt;{'Kids'}-&gt;elementsof()) {
        $page-&gt;realise();
        if ($page-&gt;{'Type'}-&gt;val() eq 'Pages') {
            push @pages, proc_pages($pdf, $page);
        }
        else {
            $pdf-&gt;{' apipagecount'}++;
            $page-&gt;{' pnum'} = $pdf-&gt;{' apipagecount'};
            if (defined $page-&gt;{'Resources'}) {
                eval {
                    $page-&gt;{'Resources'}-&gt;realise();
                };
            }
            push @pages, $page;
        }
    }

    return @pages;
}

=item $pdf-&gt;update()

Saves a previously opened document.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;open('our/to/be/updated.pdf');
    ...
    $pdf-&gt;update();

=cut

sub update {
    my $self = shift();
    $self-&gt;saveas($self-&gt;{'pdf'}-&gt;{' fname'});
}

=item $pdf-&gt;saveas($file)

Save the document to $file and remove the object structure from memory.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new();
    ...
    $pdf-&gt;saveas('our/new.pdf');

=cut

sub saveas {
    my ($self, $file) = @_;

    if ($self-&gt;{'reopened'}) {
        $self-&gt;{'pdf'}-&gt;append_file();
        my $fh;
        CORE::open($fh, '&gt;', $file) or die "Unable to open $file for writing: $!";
        binmode($fh, ':raw');
        print $fh ${$self-&gt;{'content_ref'}};
        CORE::close($fh);
    }
    elsif ($self-&gt;{' filed'}) {
        $self-&gt;{'pdf'}-&gt;close_file();
    }
    else {
        $self-&gt;{'pdf'}-&gt;out_file($file);
    }

    $self-&gt;end();
}

sub save {
    my ($self, $file) = @_;

    if ($self-&gt;{'reopened'}) {
        die "invalid method invocation: use 'saveas' instead.";
    }
    elsif ($self-&gt;{' filed'}) {
        $self-&gt;{'pdf'}-&gt;close_file();
    }
    else {
        die "invalid method invocation: use 'saveas' instead.";
    }

    $self-&gt;end();
}

=item $string = $pdf-&gt;stringify()

Return the document as a string and remove the object structure from memory.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new();
    ...
    print $pdf-&gt;stringify();

=cut

# Maintainer's note: The object is being destroyed because it contains
# circular references that would otherwise result in memory not being
# freed if the object merely goes out of scope.  If possible, the
# circular references should be eliminated so that stringify doesn't
# need to be destructive.
#
# I've opted not to just require a separate call to release() because
# it would likely introduce memory leaks in many existing programs
# that use this module.

sub stringify {
    my $self = shift();

    my $str;
    if ((defined $self-&gt;{'reopened'}) and ($self-&gt;{'reopened'} == 1)) {
        $self-&gt;{'pdf'}-&gt;append_file();
        $str = ${$self-&gt;{'content_ref'}};
    }
    else {
        my $fh = FileHandle-&gt;new();
        CORE::open($fh, '&gt;', \$str) || die "Can't begin scalar IO";
        $self-&gt;{'pdf'}-&gt;out_file($fh);
        $fh-&gt;close();
    }
    $self-&gt;end();

    return $str;
}

sub release {
    my $self = shift();
    $self-&gt;end();
    return;
}

=item $pdf-&gt;end()

Remove the object structure from memory.  PDF::API2 contains circular
references, so this call is necessary in long-running processes to
keep from running out of memory.

This will be called automatically when you save or stringify a PDF.
You should only need to call it explicitly if you are reading PDF
files and not writing them.

=cut

sub end {
    my $self = shift();
    $self-&gt;{'pdf'}-&gt;release() if defined $self-&gt;{'pdf'};

    foreach my $key (keys %$self) {
        $self-&gt;{$key} = undef;
        delete $self-&gt;{$key};
    }

    return;
}

=back

=head1 PAGE METHODS

=over

=item $page = $pdf-&gt;page()

=item $page = $pdf-&gt;page($page_number)

Returns a new page object.  By default, the page is added to the end
of the document.  If you include an existing page number, the new page
will be inserted in that position, pushing existing pages back.

If $page_number is -1, the new page is inserted as the second-last page;
if $page_number is 0, the new page is inserted as the last page.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new();

    # Add a page.  This becomes page 1.
    $page = $pdf-&gt;page();

    # Add a new first page.  $page becomes page 2.
    $another_page = $pdf-&gt;page(1);

=cut

sub page {
    my $self = shift();
    my $index = shift() || 0;
    my $page;
    if ($index == 0) {
        $page = PDF::API2::Page-&gt;new($self-&gt;{'pdf'}, $self-&gt;{'pages'});
    }
    else {
        $page = PDF::API2::Page-&gt;new($self-&gt;{'pdf'}, $self-&gt;{'pages'}, $index - 1);
    }
    $page-&gt;{' apipdf'} = $self-&gt;{'pdf'};
    $page-&gt;{' api'} = $self;
    weaken $page-&gt;{' apipdf'};
    weaken $page-&gt;{' api'};
    $self-&gt;{'pdf'}-&gt;out_obj($page);
    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    if ($index == 0) {
        push @{$self-&gt;{'pagestack'}}, $page;
        weaken $self-&gt;{'pagestack'}-&gt;[-1];
    }
    elsif ($index &lt; 0) {
        splice @{$self-&gt;{'pagestack'}}, $index, 0, $page;
        weaken $self-&gt;{'pagestack'}-&gt;[$index];
    }
    else {
        splice @{$self-&gt;{'pagestack'}}, $index - 1, 0, $page;
        weaken $self-&gt;{'pagestack'}-&gt;[$index - 1];
    }
    # $page-&gt;{'Resources'} = $self-&gt;{'pages'}-&gt;{'Resources'};
    return $page;
}

=item $page = $pdf-&gt;openpage($page_number)

Returns the L&lt;PDF::API2::Page&gt; object of page $page_number.

If $page_number is 0 or -1, it will return the last page in the
document.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;open('our/99page.pdf');
    $page = $pdf-&gt;openpage(1);   # returns the first page
    $page = $pdf-&gt;openpage(99);  # returns the last page
    $page = $pdf-&gt;openpage(-1);  # returns the last page
    $page = $pdf-&gt;openpage(999); # returns undef

=cut

sub openpage {
    my $self = shift();
    my $index = shift() || 0;
    my ($page, $rotate, $media, $trans);

    if ($index == 0) {
        $page = $self-&gt;{'pagestack'}-&gt;[-1];
    }
    elsif ($index &lt; 0) {
        $page = $self-&gt;{'pagestack'}-&gt;[$index];
    }
    else {
        $page = $self-&gt;{'pagestack'}-&gt;[$index - 1];
    }
    return unless ref($page);

    if (ref($page) ne 'PDF::API2::Page') {
        bless $page, 'PDF::API2::Page';
        $page-&gt;{' apipdf'} = $self-&gt;{'pdf'};
        $page-&gt;{' api'} = $self;
        weaken $page-&gt;{' apipdf'};
        weaken $page-&gt;{' api'};
        $self-&gt;{'pdf'}-&gt;out_obj($page);
        if (($rotate = $page-&gt;find_prop('Rotate')) and (not defined($page-&gt;{' fixed'}) or $page-&gt;{' fixed'} &lt; 1)) {
            $rotate = ($rotate-&gt;val() + 360) % 360;

            if ($rotate != 0 and not $self-&gt;default('nounrotate')) {
                $page-&gt;{'Rotate'} = PDFNum(0);
                foreach my $mediatype (qw(MediaBox CropBox BleedBox TrimBox ArtBox)) {
                    if ($media = $page-&gt;find_prop($mediatype)) {
                        $media = [ map { $_-&gt;val() } $media-&gt;elementsof() ];
                    }
                    else {
                        $media = [0, 0, 612, 792];
                        next if $mediatype ne 'MediaBox';
                    }
                    if ($rotate == 90) {
                        $trans = "0 -1 1 0 0 $media-&gt;[2] cm" if $mediatype eq 'MediaBox';
                        $media = [$media-&gt;[1], $media-&gt;[0], $media-&gt;[3], $media-&gt;[2]];
                    }
                    elsif ($rotate == 180) {
                        $trans = "-1 0 0 -1 $media-&gt;[2] $media-&gt;[3] cm" if $mediatype eq 'MediaBox';
                    }
                    elsif ($rotate == 270) {
                        $trans = "0 1 -1 0 $media-&gt;[3] 0 cm" if $mediatype eq 'MediaBox';
                        $media = [$media-&gt;[1], $media-&gt;[0], $media-&gt;[3], $media-&gt;[2]];
                    }
                    $page-&gt;{$mediatype} = PDFArray(map { PDFNum($_) } @$media);
                }
            }
            else {
                $trans = '';
            }
        }
        else {
            $trans = '';
        }

        if (defined $page-&gt;{'Contents'} and (not defined($page-&gt;{' fixed'}) or $page-&gt;{' fixed'} &lt; 1)) {
            $page-&gt;fixcontents();
            my $uncontent = delete $page-&gt;{'Contents'};
            my $content = $page-&gt;gfx();
            $content-&gt;add(" $trans ");

            if ($self-&gt;default('pageencaps')) {
                $content-&gt;{' stream'} .= ' q ';
            }
            foreach my $k ($uncontent-&gt;elementsof()) {
                $k-&gt;realise();
                $content-&gt;{' stream'} .= ' ' . unfilter($k-&gt;{'Filter'}, $k-&gt;{' stream'}) . ' ';
            }
            if ($self-&gt;default('pageencaps')) {
                $content-&gt;{' stream'} .= ' Q ';
            }

            ## $content-&gt;{'Length'} = PDFNum(length($content-&gt;{' stream'}));
            # this will be fixed by the following code or content or filters

            ## if we like compress we will do it now to do quicker saves
            if ($self-&gt;{'forcecompress'} &gt; 0) {
                # $content-&gt;compressFlate();
                $content-&gt;{' stream'} = dofilter($content-&gt;{'Filter'}, $content-&gt;{' stream'});
                $content-&gt;{' nofilt'} = 1;
                delete $content-&gt;{'-docompress'};
                $content-&gt;{'Length'} = PDFNum(length($content-&gt;{' stream'}));
            }
        }
        $page-&gt;{' fixed'} = 1;
    }

    $self-&gt;{'pdf'}-&gt;out_obj($page);
    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    $page-&gt;{' apipdf'} = $self-&gt;{'pdf'};
    $page-&gt;{' api'} = $self;
    weaken $page-&gt;{' apipdf'};
    weaken $page-&gt;{' api'};
    $page-&gt;{' reopened'} = 1;
    return $page;
}


sub walk_obj {
    my ($object_cache, $source_pdf, $target_pdf, $source_object, @keys) = @_;

    if (ref($source_object) =~ /Objind$/) {
        $source_object-&gt;realise();
    }

    return $object_cache-&gt;{scalar $source_object} if defined $object_cache-&gt;{scalar $source_object};
    # die "infinite loop while copying objects" if $source_object-&gt;{' copied'};

    my $target_object = $source_object-&gt;copy($source_pdf); ## thanks to: yaheath // Fri, 17 Sep 2004

    # $source_object-&gt;{' copied'} = 1;
    $target_pdf-&gt;new_obj($target_object) if $source_object-&gt;is_obj($source_pdf);

    $object_cache-&gt;{scalar $source_object} = $target_object;

    if (ref($source_object) =~ /Array$/) {
        $target_object-&gt;{' val'} = [];
        foreach my $k ($source_object-&gt;elementsof()) {
            $k-&gt;realise() if ref($k) =~ /Objind$/;
            $target_object-&gt;add_elements(walk_obj($object_cache, $source_pdf, $target_pdf, $k));
        }
    }
    elsif (ref($source_object) =~ /Dict$/) {
        @keys = keys(%$target_object) unless scalar @keys;
        foreach my $k (@keys) {
            next if $k =~ /^ /;
            next unless defined $source_object-&gt;{$k};
            $target_object-&gt;{$k} = walk_obj($object_cache, $source_pdf, $target_pdf, $source_object-&gt;{$k});
        }
        if ($source_object-&gt;{' stream'}) {
            if ($target_object-&gt;{'Filter'}) {
                $target_object-&gt;{' nofilt'} = 1;
            }
            else {
                delete $target_object-&gt;{' nofilt'};
                $target_object-&gt;{'Filter'} = PDFArray(PDFName('FlateDecode'));
            }
            $target_object-&gt;{' stream'} = $source_object-&gt;{' stream'};
        }
    }
    delete $target_object-&gt;{' streamloc'};
    delete $target_object-&gt;{' streamsrc'};

    return $target_object;
}

=item $xoform = $pdf-&gt;importPageIntoForm($source_pdf, $source_page_number)

Returns a Form XObject created by extracting the specified page from $source_pdf.

This is useful if you want to transpose the imported page somewhat
differently onto a page (e.g. two-up, four-up, etc.).

If $source_page_number is 0 or -1, it will return the last page in the
document.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new();
    $old = PDF::API2-&gt;open('our/old.pdf');
    $page = $pdf-&gt;page();
    $gfx = $page-&gt;gfx();

    # Import Page 2 from the old PDF
    $xo = $pdf-&gt;importPageIntoForm($old, 2);

    # Add it to the new PDF's first page at 1/2 scale
    $gfx-&gt;formimage($xo, 0, 0, 0.5);

    $pdf-&gt;saveas('our/new.pdf');

B&lt;Note:&gt; You can only import a page from an existing PDF file.

=cut

sub importPageIntoForm {
    my ($self, $s_pdf, $s_idx) = @_;
    $s_idx ||= 0;

    unless (ref($s_pdf) and $s_pdf-&gt;isa('PDF::API2')) {
        die "Invalid usage: first argument must be PDF::API2 instance, not: " . ref($s_pdf);
    }

    my ($s_page, $xo);

    $xo = $self-&gt;xo_form();

    if (ref($s_idx) eq 'PDF::API2::Page') {
        $s_page = $s_idx;
    }
    else {
        $s_page = $s_pdf-&gt;openpage($s_idx);
    }

    $self-&gt;{'apiimportcache'} ||= {};
    $self-&gt;{'apiimportcache'}-&gt;{$s_pdf} ||= {};

    # This should never get past MediaBox, since it's a required object.
    foreach my $k (qw(MediaBox ArtBox TrimBox BleedBox CropBox)) {
        # next unless defined $s_page-&gt;{$k};
        # my $box = walk_obj($self-&gt;{'apiimportcache'}-&gt;{$s_pdf}, $s_pdf-&gt;{'pdf'}, $self-&gt;{'pdf'}, $s_page-&gt;{$k});
        next unless defined $s_page-&gt;find_prop($k);
        my $box = walk_obj($self-&gt;{'apiimportcache'}-&gt;{$s_pdf}, $s_pdf-&gt;{'pdf'}, $self-&gt;{'pdf'}, $s_page-&gt;find_prop($k));
        $xo-&gt;bbox(map { $_-&gt;val() } $box-&gt;elementsof());
        last;
    }
    $xo-&gt;bbox(0, 0, 612, 792) unless defined $xo-&gt;{'BBox'};

    foreach my $k (qw(Resources)) {
        $s_page-&gt;{$k} = $s_page-&gt;find_prop($k);
        next unless defined $s_page-&gt;{$k};
        $s_page-&gt;{$k}-&gt;realise() if ref($s_page-&gt;{$k}) =~ /Objind$/;

        foreach my $sk (qw(XObject ExtGState Font ProcSet Properties ColorSpace Pattern Shading)) {
            next unless defined $s_page-&gt;{$k}-&gt;{$sk};
            $s_page-&gt;{$k}-&gt;{$sk}-&gt;realise() if ref($s_page-&gt;{$k}-&gt;{$sk}) =~ /Objind$/;
            foreach my $ssk (keys %{$s_page-&gt;{$k}-&gt;{$sk}}) {
                next if $ssk =~ /^ /;
                $xo-&gt;resource($sk, $ssk, walk_obj($self-&gt;{'apiimportcache'}-&gt;{$s_pdf}, $s_pdf-&gt;{'pdf'}, $self-&gt;{'pdf'}, $s_page-&gt;{$k}-&gt;{$sk}-&gt;{$ssk}));
            }
        }
    }

    # create a whole content stream
    ## technically it is possible to submit an unfinished
    ## (eg. newly created) source-page, but thats nonsense,
    ## so we expect a page fixed by openpage and die otherwise
    die "page not processed via openpage ..." unless $s_page-&gt;{' fixed'} == 1;

    # since the source page comes from openpage it may already
    # contain the required starting 'q' without the final 'Q'
    # if forcecompress is in effect
    if (defined $s_page-&gt;{'Contents'}) {
        $s_page-&gt;fixcontents();

        $xo-&gt;{' stream'} = '';
        # openpage pages only contain one stream
        my ($k) = $s_page-&gt;{'Contents'}-&gt;elementsof();
        $k-&gt;realise();
        if ($k-&gt;{' nofilt'}) {
          # we have a finished stream here
          # so we unfilter
          $xo-&gt;add('q', unfilter($k-&gt;{'Filter'}, $k-&gt;{' stream'}), 'Q');
        }
        else {
            # stream is an unfinished/unfiltered content
            # so we just copy it and add the required "qQ"
            $xo-&gt;add('q', $k-&gt;{' stream'}, 'Q');
        }
        $xo-&gt;compressFlate() if $self-&gt;{'forcecompress'} &gt; 0;
    }

    return $xo;
}

=item $page = $pdf-&gt;import_page($source_pdf, $source_page_number, $target_page_number)

Imports a page from $source_pdf and adds it to the specified position
in $pdf.

If $source_page_number or $target_page_number is 0 or -1, the last
page in the document is used.

B&lt;Note:&gt; If you pass a page object instead of a page number for
$target_page_number, the contents of the page will be merged into the
existing page.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new();
    $old = PDF::API2-&gt;open('our/old.pdf');

    # Add page 2 from the old PDF as page 1 of the new PDF
    $page = $pdf-&gt;import_page($old, 2);

    $pdf-&gt;saveas('our/new.pdf');

B&lt;Note:&gt; You can only import a page from an existing PDF file.

=cut

# Deprecated (renamed)
sub importpage { return import_page(@_); } ## no critic

sub import_page {
    my ($self, $s_pdf, $s_idx, $t_idx) = @_;
    $s_idx ||= 0;
    $t_idx ||= 0;
    my ($s_page, $t_page);

    unless (ref($s_pdf) and $s_pdf-&gt;isa('PDF::API2')) {
        die "Invalid usage: first argument must be PDF::API2 instance, not: " . ref($s_pdf);
    }

    if (ref($s_idx) eq 'PDF::API2::Page') {
        $s_page = $s_idx;
    }
    else {
        $s_page = $s_pdf-&gt;openpage($s_idx);
    }

    if (ref($t_idx) eq 'PDF::API2::Page') {
        $t_page = $t_idx;
    }
    else {
        if ($self-&gt;pages() &lt; $t_idx) {
            $t_page = $self-&gt;page();
        }
        else {
            $t_page = $self-&gt;page($t_idx);
        }
    }

    $self-&gt;{'apiimportcache'} = $self-&gt;{'apiimportcache'} || {};
    $self-&gt;{'apiimportcache'}-&gt;{$s_pdf} = $self-&gt;{'apiimportcache'}-&gt;{$s_pdf} || {};

    # we now import into a form to keep
    # all that nasty resources from polluting
    # our very own resource naming space.
    my $xo = $self-&gt;importPageIntoForm($s_pdf, $s_page);

    # copy all page dimensions
    foreach my $k (qw(MediaBox ArtBox TrimBox BleedBox CropBox)) {
        my $prop = $s_page-&gt;find_prop($k);
        next unless defined $prop;

        my $box = walk_obj({}, $s_pdf-&gt;{'pdf'}, $self-&gt;{'pdf'}, $prop);
        my $method = lc $k;

        $t_page-&gt;$method(map { $_-&gt;val() } $box-&gt;elementsof());
    }

    $t_page-&gt;gfx-&gt;formimage($xo, 0, 0, 1);

    # copy annotations and/or form elements as well
    if (exists $s_page-&gt;{'Annots'} and $s_page-&gt;{'Annots'} and $self-&gt;{'copyannots'}) {
        # first set up the AcroForm, if required
        my $AcroForm;
        if (my $a = $s_pdf-&gt;{'pdf'}-&gt;{'Root'}-&gt;realise-&gt;{'AcroForm'}) {
            $a-&gt;realise();

            $AcroForm = walk_obj({}, $s_pdf-&gt;{'pdf'}, $self-&gt;{'pdf'}, $a, qw(NeedAppearances SigFlags CO DR DA Q));
        }
        my @Fields = ();
        my @Annots = ();
        foreach my $a ($s_page-&gt;{'Annots'}-&gt;elementsof()) {
            $a-&gt;realise();
            my $t_a = PDFDict();
            $self-&gt;{'pdf'}-&gt;new_obj($t_a);
            # these objects are likely to be both annotations and Acroform fields
            # key names are copied from PDF Reference 1.4 (Tables)
            my @k = (
                qw( Type Subtype Contents P Rect NM M F BS Border AP AS C CA T Popup A AA StructParent Rotate
                ),                                      # Annotations - Common (8.10)
                qw( Subtype Contents Open Name ),       # Text Annotations (8.15)
                qw( Subtype Contents Dest H PA ),       # Link Annotations (8.16)
                qw( Subtype Contents DA Q ),            # Free Text Annotations (8.17)
                qw( Subtype Contents L BS LE IC ) ,     # Line Annotations (8.18)
                qw( Subtype Contents BS IC ),           # Square and Circle Annotations (8.20)
                qw( Subtype Contents QuadPoints ),      # Markup Annotations (8.21)
                qw( Subtype Contents Name ),            # Rubber Stamp Annotations (8.22)
                qw( Subtype Contents InkList BS ),      # Ink Annotations (8.23)
                qw( Subtype Contents Parent Open ),     # Popup Annotations (8.24)
                qw( Subtype FS Contents Name ),         # File Attachment Annotations (8.25)
                qw( Subtype Sound Contents Name ),      # Sound Annotations (8.26)
                qw( Subtype Movie Contents A ),         # Movie Annotations (8.27)
                qw( Subtype Contents H MK ),            # Widget Annotations (8.28)
                                                        # Printers Mark Annotations (none)
                                                        # Trap Network Annotations (none)
            );

            push @k, (
                qw( Subtype FT Parent Kids T TU TM Ff V DV AA
                ),                                      # Fields - Common (8.49)
                qw( DR DA Q ),                          # Fields containing variable text (8.51)
                qw( Opt ),                              # Checkbox field (8.54)
                qw( Opt ),                              # Radio field (8.55)
                qw( MaxLen ),                           # Text field (8.57)
                qw( Opt TI I ),                         # Choice field (8.59)
            ) if $AcroForm;

            # sorting out dups
            my %ky = map { $_ =&gt; 1 } @k;
            # we do P separately, as it points to the page the Annotation is on
            delete $ky{'P'};
            # copy everything else
            foreach my $k (keys %ky) {
                next unless defined $a-&gt;{$k};
                $a-&gt;{$k}-&gt;realise();
                $t_a-&gt;{$k} = walk_obj({}, $s_pdf-&gt;{'pdf'}, $self-&gt;{'pdf'}, $a-&gt;{$k});
            }
            $t_a-&gt;{'P'} = $t_page;
            push @Annots, $t_a;
            push @Fields, $t_a if ($AcroForm and $t_a-&gt;{'Subtype'}-&gt;val() eq 'Widget');
        }
        $t_page-&gt;{'Annots'} = PDFArray(@Annots);
        $AcroForm-&gt;{'Fields'} = PDFArray(@Fields) if $AcroForm;
        $self-&gt;{'pdf'}-&gt;{'Root'}-&gt;{'AcroForm'} = $AcroForm;
    }
    $t_page-&gt;{' imported'} = 1;

    $self-&gt;{'pdf'}-&gt;out_obj($t_page);
    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $t_page;
}

=item $count = $pdf-&gt;pages()

Returns the number of pages in the document.

=cut

sub pages {
    my $self = shift();
    return scalar @{$self-&gt;{'pagestack'}};
}

=item $pdf-&gt;mediabox($name)

=item $pdf-&gt;mediabox($w, $h)

=item $pdf-&gt;mediabox($llx, $lly, $urx, $ury)

Sets the global mediabox.

B&lt;Example:&gt;

    $pdf = PDF::API2-&gt;new();
    $pdf-&gt;mediabox('A4');
    ...
    $pdf-&gt;saveas('our/new.pdf');

    $pdf = PDF::API2-&gt;new();
    $pdf-&gt;mediabox(595, 842);
    ...
    $pdf-&gt;saveas('our/new.pdf');

    $pdf = PDF::API2-&gt;new;
    $pdf-&gt;mediabox(0, 0, 595, 842);
    ...
    $pdf-&gt;saveas('our/new.pdf');

=cut

sub mediabox {
    my ($self, $x1, $y1, $x2, $y2) = @_;
    $self-&gt;{'pages'}-&gt;{'MediaBox'} = PDFArray(map { PDFNum(float($_)) } page_size($x1, $y1, $x2, $y2));
    return $self;
}

=item $pdf-&gt;cropbox($name)

=item $pdf-&gt;cropbox($w, $h)

=item $pdf-&gt;cropbox($llx, $lly, $urx, $ury)

Sets the global cropbox.

=cut

sub cropbox {
    my ($self, $x1, $y1, $x2, $y2) = @_;
    $self-&gt;{'pages'}-&gt;{'CropBox'} = PDFArray(map { PDFNum(float($_)) } page_size($x1, $y1, $x2, $y2));
    return $self;
}

=item $pdf-&gt;bleedbox($name)

=item $pdf-&gt;bleedbox($w, $h)

=item $pdf-&gt;bleedbox($llx, $lly, $urx, $ury)

Sets the global bleedbox.

=cut

sub bleedbox {
    my ($self, $x1, $y1, $x2, $y2) = @_;
    $self-&gt;{'pages'}-&gt;{'BleedBox'} = PDFArray(map { PDFNum(float($_)) } page_size($x1, $y1, $x2, $y2));
    return $self;
}

=item $pdf-&gt;trimbox($name)

=item $pdf-&gt;trimbox($w, $h)

=item $pdf-&gt;trimbox($llx, $lly, $urx, $ury)

Sets the global trimbox.

=cut

sub trimbox {
    my ($self, $x1, $y1, $x2, $y2) = @_;
    $self-&gt;{'pages'}-&gt;{'TrimBox'} = PDFArray(map { PDFNum(float($_)) } page_size($x1, $y1, $x2, $y2));
    return $self;
}

=item $pdf-&gt;artbox($name)

=item $pdf-&gt;artbox($w, $h)

=item $pdf-&gt;artbox($llx, $lly, $urx, $ury)

Sets the global artbox.

=cut

sub artbox {
    my ($self, $x1, $y1, $x2, $y2) = @_;
    $self-&gt;{'pages'}-&gt;{'ArtBox'} = PDFArray(map { PDFNum(float($_)) } page_size($x1, $y1, $x2, $y2));
    return $self;
}

=back

=head1 FONT METHODS

=over

=item @directories = PDF::API2::addFontDirs($dir1, $dir2, ...)

Adds one or more directories to the search path for finding font
files.

Returns the list of searched directories.

=cut

sub addFontDirs {
    my @dirs = @_;
    push @FontDirs, @dirs;
    return @FontDirs;
}

sub _findFont {
    my $font = shift();
    my @fonts = ($font, map { "$_/$font" } @FontDirs);
    shift @fonts while scalar(@fonts) and not -f $fonts[0];
    return $fonts[0];
}

=item $font = $pdf-&gt;corefont($fontname, [%options])

Returns a new Adobe core font object.

B&lt;Examples:&gt;

    $font = $pdf-&gt;corefont('Times-Roman');
    $font = $pdf-&gt;corefont('Times-Bold');
    $font = $pdf-&gt;corefont('Helvetica');
    $font = $pdf-&gt;corefont('ZapfDingbats');

Valid %options are:

=over

=item -encode

Changes the encoding of the font from its default.

=item -dokern

Enables kerning if data is available.

=back

See Also: L&lt;PDF::API2::Resource::Font::CoreFont&gt;.

=cut

sub corefont {
    my ($self, $name, %opts) = @_;
    require PDF::API2::Resource::Font::CoreFont;
    my $obj = PDF::API2::Resource::Font::CoreFont-&gt;new($self-&gt;{'pdf'}, $name, %opts);
    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    $obj-&gt;tounicodemap() if $opts{-unicodemap} == 1;
    return $obj;
}

=item $font = $pdf-&gt;psfont($ps_file, [%options])

Returns a new Adobe Type1 font object.

B&lt;Examples:&gt;

    $font = $pdf-&gt;psfont('Times-Book.pfa', -afmfile =&gt; 'Times-Book.afm');
    $font = $pdf-&gt;psfont('/fonts/Synest-FB.pfb', -pfmfile =&gt; '/fonts/Synest-FB.pfm');

Valid %options are:

=over

=item -encode

Changes the encoding of the font from its default.

=item -afmfile

Specifies the location of the font metrics file.

=item -pfmfile

Specifies the location of the printer font metrics file.  This option
overrides the -encode option.

=item -dokern

Enables kerning if data is available.

=back

=cut

sub psfont {
    my ($self, $psf, %opts) = @_;

    foreach my $o (qw(-afmfile -pfmfile)) {
        next unless defined $opts{$o};
        $opts{$o} = _findFont($opts{$o});
    }
    $psf = _findFont($psf);
    require PDF::API2::Resource::Font::Postscript;
    my $obj = PDF::API2::Resource::Font::Postscript-&gt;new($self-&gt;{'pdf'}, $psf, %opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    $obj-&gt;tounicodemap() if $opts{-unicodemap} == 1;

    return $obj;
}

=item $font = $pdf-&gt;ttfont($ttf_file, [%options])

Returns a new TrueType or OpenType font object.

B&lt;Examples:&gt;

    $font = $pdf-&gt;ttfont('Times.ttf');
    $font = $pdf-&gt;ttfont('Georgia.otf');

Valid %options are:

=over

=item -encode

Changes the encoding of the font from its default.

=item -isocmap

Use the ISO Unicode Map instead of the default MS Unicode Map.

=item -dokern

Enables kerning if data is available.

=item -noembed

Disables embedding of the font file.

=back

=cut

sub ttfont {
    my ($self, $file, %opts) = @_;

    # PDF::API2 doesn't set BaseEncoding for TrueType fonts, so text
    # isn't searchable unless a ToUnicode CMap is included.  Include
    # the ToUnicode CMap by default, but allow it to be disabled (for
    # performance and file size reasons) by setting -unicodemap to 0.
    $opts{-unicodemap} = 1 unless exists $opts{-unicodemap};

    $file = _findFont($file);
    require PDF::API2::Resource::CIDFont::TrueType;
    my $obj = PDF::API2::Resource::CIDFont::TrueType-&gt;new($self-&gt;{'pdf'}, $file, %opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    $obj-&gt;tounicodemap() if $opts{-unicodemap};

    return $obj;
}

=item $font = $pdf-&gt;cjkfont($cjkname, [%options])

Returns a new CJK font object.

B&lt;Examples:&gt;

    $font = $pdf-&gt;cjkfont('korean');
    $font = $pdf-&gt;cjkfont('traditional');

Valid %options are:

=over

=item -encode

Changes the encoding of the font from its default.

=back

See Also: L&lt;PDF::API2::Resource::CIDFont::CJKFont&gt;

=cut

sub cjkfont {
    my ($self, $name, %opts) = @_;

    require PDF::API2::Resource::CIDFont::CJKFont;
    my $obj = PDF::API2::Resource::CIDFont::CJKFont-&gt;new($self-&gt;{'pdf'}, $name, %opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    $obj-&gt;tounicodemap() if $opts{-unicodemap} == 1;

    return $obj;
}

=item $font = $pdf-&gt;synfont($basefont, [%options])

Returns a new synthetic font object.

B&lt;Examples:&gt;

    $cf  = $pdf-&gt;corefont('Times-Roman', -encode =&gt; 'latin1');
    $sf  = $pdf-&gt;synfont($cf, -slant =&gt; 0.85);  # compressed 85%
    $sfb = $pdf-&gt;synfont($cf, -bold =&gt; 1);      # embolden by 10em
    $sfi = $pdf-&gt;synfont($cf, -oblique =&gt; -12); # italic at -12 degrees

Valid %options are:

=over

=item -slant

Slant/expansion factor (0.1-0.9 = slant, 1.1+ = expansion).

=item -oblique

Italic angle (+/-)

=item -bold

Emboldening factor (0.1+, bold = 1, heavy = 2, ...)

=item -space

Additional character spacing in ems (0-1000)

=back

See Also: L&lt;PDF::API2::Resource::Font::SynFont&gt;

=cut

sub synfont {
    my ($self, $font, %opts) = @_;

    # PDF::API2 doesn't set BaseEncoding for TrueType fonts, so text
    # isn't searchable unless a ToUnicode CMap is included.  Include
    # the ToUnicode CMap by default, but allow it to be disabled (for
    # performance and file size reasons) by setting -unicodemap to 0.
    $opts{-unicodemap} = 1 unless exists $opts{-unicodemap};

    require PDF::API2::Resource::Font::SynFont;
    my $obj = PDF::API2::Resource::Font::SynFont-&gt;new($self-&gt;{'pdf'}, $font, %opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    $obj-&gt;tounicodemap() if $opts{-unicodemap};

    return $obj;
}

=item $font = $pdf-&gt;bdfont($bdf_file)

Returns a new BDF font object, based on the specified Adobe BDF file.

See Also: L&lt;PDF::API2::Resource::Font::BdFont&gt;

=cut

sub bdfont {
    my ($self, @opts) = @_;

    require PDF::API2::Resource::Font::BdFont;
    my $obj = PDF::API2::Resource::Font::BdFont-&gt;new($self-&gt;{'pdf'}, @opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});
    # $obj-&gt;tounicodemap(); # does not support Unicode

    return $obj;
}

=item $font = $pdf-&gt;unifont(@fontspecs, %options)

Returns a new uni-font object, based on the specified fonts and options.

B&lt;BEWARE:&gt; This is not a true pdf-object, but a virtual/abstract font definition!

See Also: L&lt;PDF::API2::Resource::UniFont&gt;.

Valid %options are:

=over

=item -encode

Changes the encoding of the font from its default.

=back

=cut

sub unifont {
    my ($self, @opts) = @_;

    require PDF::API2::Resource::UniFont;
    my $obj = PDF::API2::Resource::UniFont-&gt;new($self-&gt;{'pdf'}, @opts);

    return $obj;
}

=back

=head1 IMAGE METHODS

=over

=item $jpeg = $pdf-&gt;image_jpeg($file)

Imports and returns a new JPEG image object.  C&lt;$file&gt; may be either a filename or a filehandle.

=cut

sub image_jpeg {
    my ($self, $file, %opts) = @_;

    require PDF::API2::Resource::XObject::Image::JPEG;
    my $obj = PDF::API2::Resource::XObject::Image::JPEG-&gt;new($self-&gt;{'pdf'}, $file);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $tiff = $pdf-&gt;image_tiff($file)

Imports and returns a new TIFF image object.  C&lt;$file&gt; may be either a filename or a filehandle.

=cut

sub image_tiff {
    my ($self, $file, %opts) = @_;

    require PDF::API2::Resource::XObject::Image::TIFF;
    my $obj = PDF::API2::Resource::XObject::Image::TIFF-&gt;new($self-&gt;{'pdf'}, $file);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $pnm = $pdf-&gt;image_pnm($file)

Imports and returns a new PNM image object.  C&lt;$file&gt; may be either a filename or a filehandle.

=cut

sub image_pnm {
    my ($self, $file, %opts) = @_;

    require PDF::API2::Resource::XObject::Image::PNM;
    my $obj = PDF::API2::Resource::XObject::Image::PNM-&gt;new($self-&gt;{'pdf'}, $file);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $png = $pdf-&gt;image_png($file)

Imports and returns a new PNG image object.  C&lt;$file&gt; may be either a filename or a filehandle.

=cut

sub image_png {
    my ($self, $file, %opts) = @_;

    require PDF::API2::Resource::XObject::Image::PNG;
    my $obj = PDF::API2::Resource::XObject::Image::PNG-&gt;new($self-&gt;{'pdf'}, $file);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $gif = $pdf-&gt;image_gif($file)

Imports and returns a new GIF image object.  C&lt;$file&gt; may be either a filename or a filehandle.

=cut

sub image_gif {
    my ($self, $file, %opts) = @_;

    require PDF::API2::Resource::XObject::Image::GIF;
    my $obj = PDF::API2::Resource::XObject::Image::GIF-&gt;new($self-&gt;{'pdf'}, $file);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $gdf = $pdf-&gt;image_gd($gd_object, %options)

Imports and returns a new image object from GD::Image.

B&lt;Options:&gt; The only option currently supported is C&lt;&lt; -lossless =&gt; 1 &gt;&gt;.

=cut

sub image_gd {
    my ($self, $gd, %opts) = @_;

    require PDF::API2::Resource::XObject::Image::GD;
    my $obj = PDF::API2::Resource::XObject::Image::GD-&gt;new($self-&gt;{'pdf'}, $gd, undef, %opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=back

=head1 COLORSPACE METHODS

=over

=item $cs = $pdf-&gt;colorspace_act($file)

Returns a new colorspace object based on an Adobe Color Table file.

See L&lt;PDF::API2::Resource::ColorSpace::Indexed::ACTFile&gt; for a
reference to the file format's specification.

=cut

sub colorspace_act {
    my ($self, $file, %opts) = @_;

    require PDF::API2::Resource::ColorSpace::Indexed::ACTFile;
    my $obj = PDF::API2::Resource::ColorSpace::Indexed::ACTFile-&gt;new($self-&gt;{'pdf'}, $file);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $cs = $pdf-&gt;colorspace_web()

Returns a new colorspace-object based on the web color palette.

=cut

sub colorspace_web {
    my ($self, $file, %opts) = @_;

    require PDF::API2::Resource::ColorSpace::Indexed::WebColor;
    my $obj = PDF::API2::Resource::ColorSpace::Indexed::WebColor-&gt;new($self-&gt;{'pdf'});

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $cs = $pdf-&gt;colorspace_hue()

Returns a new colorspace-object based on the hue color palette.

See L&lt;PDF::API2::Resource::ColorSpace::Indexed::Hue&gt; for an explanation.

=cut

sub colorspace_hue {
    my ($self, $file, %opts)=@_;

    require PDF::API2::Resource::ColorSpace::Indexed::Hue;
    my $obj = PDF::API2::Resource::ColorSpace::Indexed::Hue-&gt;new($self-&gt;{'pdf'});

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $cs = $pdf-&gt;colorspace_separation($tint, $color)

Returns a new separation colorspace object based on the parameters.

I&lt;$tint&gt; can be any valid ink identifier, including but not limited
to: 'Cyan', 'Magenta', 'Yellow', 'Black', 'Red', 'Green', 'Blue' or
'Orange'.

I&lt;$color&gt; must be a valid color specification limited to: '#rrggbb',
'!hhssvv', '%ccmmyykk' or a "named color" (rgb).

The colorspace model will automatically be chosen based on the
specified color.

=cut

sub colorspace_separation {
    my ($self, $name, @clr)=@_;

    require PDF::API2::Resource::ColorSpace::Separation;
    my $obj = PDF::API2::Resource::ColorSpace::Separation-&gt;new($self-&gt;{'pdf'}, pdfkey(), $name, @clr);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $cs = $pdf-&gt;colorspace_devicen(\@tintCSx, [$samples])

Returns a new DeviceN colorspace object based on the parameters.

B&lt;Example:&gt;

    $cy = $pdf-&gt;colorspace_separation('Cyan',    '%f000');
    $ma = $pdf-&gt;colorspace_separation('Magenta', '%0f00');
    $ye = $pdf-&gt;colorspace_separation('Yellow',  '%00f0');
    $bk = $pdf-&gt;colorspace_separation('Black',   '%000f');

    $pms023 = $pdf-&gt;colorspace_separation('PANTONE 032CV', '%0ff0');

    $dncs = $pdf-&gt;colorspace_devicen( [ $cy,$ma,$ye,$bk,$pms023 ] );

The colorspace model will automatically be chosen based on the first
colorspace specified.

=cut

sub colorspace_devicen {
    my ($self, $clrs, $samples) = @_;
    $samples ||= 2;

    require PDF::API2::Resource::ColorSpace::DeviceN;
    my $obj = PDF::API2::Resource::ColorSpace::DeviceN-&gt;new($self-&gt;{'pdf'}, pdfkey(), $clrs, $samples);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=back

=head1 BARCODE METHODS

=over

=item $bc = $pdf-&gt;xo_codabar(%options)

=item $bc = $pdf-&gt;xo_code128(%options)

=item $bc = $pdf-&gt;xo_2of5int(%options)

=item $bc = $pdf-&gt;xo_3of9(%options)

=item $bc = $pdf-&gt;xo_ean13(%options)

Creates the specified barcode object as a form XObject.

=cut

sub xo_code128 {
    my ($self, @opts) = @_;

    require PDF::API2::Resource::XObject::Form::BarCode::code128;
    my $obj = PDF::API2::Resource::XObject::Form::BarCode::code128-&gt;new($self-&gt;{'pdf'}, @opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

sub xo_codabar {
    my ($self, @opts) = @_;

    require PDF::API2::Resource::XObject::Form::BarCode::codabar;
    my $obj = PDF::API2::Resource::XObject::Form::BarCode::codabar-&gt;new($self-&gt;{'pdf'}, @opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

sub xo_2of5int {
    my ($self, @opts) = @_;

    require PDF::API2::Resource::XObject::Form::BarCode::int2of5;
    my $obj = PDF::API2::Resource::XObject::Form::BarCode::int2of5-&gt;new($self-&gt;{'pdf'}, @opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

sub xo_3of9 {
    my ($self, @opts) = @_;

    require PDF::API2::Resource::XObject::Form::BarCode::code3of9;
    my $obj = PDF::API2::Resource::XObject::Form::BarCode::code3of9-&gt;new($self-&gt;{'pdf'}, @opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

sub xo_ean13 {
    my ($self, @opts) = @_;

    require PDF::API2::Resource::XObject::Form::BarCode::ean13;
    my $obj = PDF::API2::Resource::XObject::Form::BarCode::ean13-&gt;new($self-&gt;{'pdf'}, @opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=back

=head1 OTHER METHODS

=over

=item $xo = $pdf-&gt;xo_form()

Returns a new form XObject.

=cut

sub xo_form {
    my $self = shift();

    my $obj = PDF::API2::Resource::XObject::Form::Hybrid-&gt;new($self-&gt;{'pdf'});

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $egs = $pdf-&gt;egstate()

Returns a new extended graphics state object.

=cut

sub egstate {
    my $self = shift();

    my $obj = PDF::API2::Resource::ExtGState-&gt;new($self-&gt;{'pdf'}, pdfkey());

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $obj = $pdf-&gt;pattern()

Returns a new pattern object.

=cut

sub pattern {
    my ($self, %opts) = @_;

    my $obj = PDF::API2::Resource::Pattern-&gt;new($self-&gt;{'pdf'}, undef, %opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $obj = $pdf-&gt;shading()

Returns a new shading object.

=cut

sub shading {
    my ($self, %opts) = @_;

    my $obj = PDF::API2::Resource::Shading-&gt;new($self-&gt;{'pdf'}, undef, %opts);

    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pages'});

    return $obj;
}

=item $otls = $pdf-&gt;outlines()

Returns a new or existing outlines object.

=cut

sub outlines {
    my $self = shift();

    require PDF::API2::Outlines;
    $self-&gt;{'pdf'}-&gt;{'Root'}-&gt;{'Outlines'} ||= PDF::API2::Outlines-&gt;new($self);

    my $obj = $self-&gt;{'pdf'}-&gt;{'Root'}-&gt;{'Outlines'};

    $self-&gt;{'pdf'}-&gt;new_obj($obj) unless $obj-&gt;is_obj($self-&gt;{'pdf'});
    $self-&gt;{'pdf'}-&gt;out_obj($obj);
    $self-&gt;{'pdf'}-&gt;out_obj($self-&gt;{'pdf'}-&gt;{'Root'});

    return $obj;
}

sub named_destination {
    my ($self, $cat, $name, $obj) = @_;
    my $root = $self-&gt;{'catalog'};

    $root-&gt;{'Names'} ||= PDFDict();
    $root-&gt;{'Names'}-&gt;{$cat} ||= PDFDict();
    $root-&gt;{'Names'}-&gt;{$cat}-&gt;{'-vals'}  ||= {};
    $root-&gt;{'Names'}-&gt;{$cat}-&gt;{'Limits'} ||= PDFArray();
    $root-&gt;{'Names'}-&gt;{$cat}-&gt;{'Names'}  ||= PDFArray();

    unless (defined $obj) {
        $obj = PDF::API2::NamedDestination-&gt;new($self-&gt;{'pdf'});
    }
    $root-&gt;{'Names'}-&gt;{$cat}-&gt;{'-vals'}-&gt;{$name} = $obj;

    my @names = sort {$a cmp $b} keys %{$root-&gt;{'Names'}-&gt;{$cat}-&gt;{'-vals'}};

    $root-&gt;{'Names'}-&gt;{$cat}-&gt;{'Limits'}-&gt;{' val'}-&gt;[0] = PDFStr($names[0]);
    $root-&gt;{'Names'}-&gt;{$cat}-&gt;{'Limits'}-&gt;{' val'}-&gt;[1] = PDFStr($names[-1]);

    @{$root-&gt;{'Names'}-&gt;{$cat}-&gt;{'Names'}-&gt;{' val'}} = ();

    foreach my $k (@names) {
        push @{$root-&gt;{'Names'}-&gt;{$cat}-&gt;{'Names'}-&gt;{' val'}}, (
            PDFStr($k),
            $root-&gt;{'Names'}-&gt;{$cat}-&gt;{'-vals'}-&gt;{$k}
        );
    }

    return $obj;
}

1;

__END__

=back

=head1 KNOWN ISSUES

This module does not work with perl's -l command-line switch.

=head1 AUTHOR

PDF::API2 was originally written by Alfred Reibenschuh.

It is currently being maintained by Steve Simms.

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