PDF::Builder(3) User Contributed Perl Documentation PDF::Builder(3)

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

use PDF::Builder;

# Create a blank PDF file
$pdf = PDF::Builder->new();

# Open an existing PDF file
$pdf = PDF::Builder->open('some.pdf');

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

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

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

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

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

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

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

See the file README (in downloadable package and on CPAN) for a summary of prerequisites and tools needed to install PDF::Builder, both mandatory and optional.

There are four levels of involvement with PDF::Builder. Depending on what you want to do, different kinds of installs are recommended. See "Software Development Kit" in PDF::Builder::Docs for suggestions.

PDF::Builder can make use of some optional libraries, which are not required for a successful installation, but improve speed and capabilities. See "Optional Libraries" in PDF::Builder::Docs for more information.

There are some things you should know about character encoding (for text), before you dive in to coding. Please go to "Strings (Character Text)" in PDF::Builder::Docs and have a read.

Invoking "text" and "graphics" methods can lead to unexpected results (a different ordering of output than intended). See "Rendering Order" in PDF::Builder::Docs for more information.

PDF::Builder is mostly PDF 1.4-compliant, but there are complications you should be aware of. Please read "PDF Versions Supported" in PDF::Builder::Docs for details.

PDF::Builder intends to support all major Perl versions that were released in the past six years, plus one, in order to continue working for the life of most long-term-stable (LTS) server distributions. See the https://www.cpan.org/src/ table First release in each branch of Perl x.xxxx0 "Major" release dates.

For example, a version of PDF::Builder released on 2018-06-05 would support the last major version of Perl released on or after 2012-06-05 (5.18), and then one before that, which would be 5.16. Alternatively, the last major version of Perl released before 2012-06-05 is 5.16.

The intent is to avoid expending unnecessary effort in supporting very old (obsolete) versions of Perl. If you need to use this module on a server with an extremely out-of-date version of Perl, consider using either plenv or Perlbrew to run a newer version of Perl without needing admin privileges.

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

There is a file INFO/KNOWN_INCOMP which lists known incompatibilities with PDF::API2, in case you're thinking of porting over something from that world, or have experience there and want to try PDF::Builder. There is also a file INFO/DEPRECATED, which lists things which are planned to be removed at some point.

The history of PDF::Builder is a complex and exciting saga... OK, it may be mildly interesting. Have a look at "History" in PDF::Builder::Docs section.

PDF::API2 was originally written by Alfred Reibenschuh. See the HISTORY section for more information.

It was maintained by Steve Simms.

PDF::Builder is currently being maintained by Phil M. Perry.

The full source is on https://github.com/PhilterPaper/Perl-PDF-Builder.

The release distribution is on CPAN: https://metacpan.org/pod/PDF::Builder.

Bug reports are on https://github.com/PhilterPaper/Perl-PDF-Builder/issues?q=is%3Aissue+sort%3Aupdated-desc (with "bug" label), feature requests have an "enhancement" label, and general discussions (architecture, roadmap, etc.) have a "general discussion" label.

Do not under any circumstances open a PR (Pull Request) to report a bug. It is a waste of both your and our time and effort. Open a regular ticket (issue), and attach a Perl (.pl) program illustrating the problem, if possible. If you believe that you have a program patch, and offer to share it as a PR, we may give the go-ahead. Unsolicited PRs may be closed without further action.

This software is Copyright (c) 2017-2021 by Phil M. Perry.

This is free software, licensed under:

The GNU Lesser General Public License (LGPL) Version 2.1, February 1999

(The master copy of this license lives on the GNU website.)
(A copy is provided in the INFO/LICENSE file for your convenience.)

This section of Builder.pm is intended only as a very brief summary of the license; please consider INFO/LICENSE to be the controlling version, if there is any conflict or ambiguity between the two.

This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License, as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version of this license.

NOTE: there are several files in this distribution which were incorporated from outside sources and carry different licenses. If a file states that it is under a license different than LGPL 2.1, that license and its terms will apply to that file, and not LGPL 2.1.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

$pdf = PDF::Builder->new(%options)
$pdf = PDF::Builder->new()
Creates a new PDF object.

Options

-file
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.
-compress
The '-compress' option can be given to specify stream compression: default is 'flate', 'none' is no compression. No other compression methods are currently supported.
-outver
The '-outver' option defaults to 1.4 as the output PDF version and the highest allowed feature version (attempts to use anything higher will give a warning). If an existing PDF with a higher version is read in, -outver will be increased to that version, with a warning.
-msgver
The '-msgver' option value of 1 (default) gives a warning message if the '-outver' PDF level has to be bumped up due to either a higher PDF level file being read in, or a higher level feature was requested. A value of 0 suppresses the warning message.
-diaglevel
The '-diaglevel' option can be given to specify the level of diagnostics given by IntegrityCheck(). The default is level 2 (errors and warnings). See "IntegrityCheck" in PDF::Builder::Docs for more information.

Example:

$pdf = PDF::Builder->new();
...
print $pdf->stringify();

$pdf = PDF::Builder->new(-compress => 'none');
# equivalent to $pdf->{'forcecompress'} = 'none'; (or older, 0)

$pdf = PDF::Builder->new();
...
$pdf->saveas('our/new.pdf');

$pdf = PDF::Builder->new(-file => 'our/new.pdf');
...
$pdf->save();
$pdf = PDF::Builder->open($pdf_file, %options)
$pdf = PDF::Builder->open($pdf_file)
Opens an existing PDF file. See "new()" for options.

Example:

$pdf = PDF::Builder->open('our/old.pdf');
...
$pdf->saveas('our/new.pdf');

$pdf = PDF::Builder->open('our/to/be/updated.pdf');
...
$pdf->update();
$pdf = PDF::Builder->open_scalar($pdf_string, %options)
$pdf = PDF::Builder->open_scalar($pdf_string)
Opens a PDF contained in a string. See "new()" for other options.
-diags => 1
Display warnings when non-conforming PDF structure is found, and fix up where possible. See PDF::Builder::Basic::PDF::File for more information.

Example:

# 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 = <$fh>;

$pdf = PDF::Builder->open_scalar($pdf_string);
...
$pdf->saveas('our/new.pdf');
$pdf->preferences(%options)
Controls viewing preferences for the PDF, including the Page Mode, Page Layout, Viewer, and Initial Page Options. See "Preferences - set user display preferences" in PDF::Builder::Docs for details on all these option groups.
$val = $pdf->default($parameter)
$pdf->default($parameter, $value)
Gets/sets the default value for a behavior of PDF::Builder.

Supported Parameters:

nounrotate
prohibits Builder from rotating imported/opened page to re-create a default pdf-context.
pageencaps
enables Builder's adding save/restore commands upon importing/opening pages to preserve graphics-state for modification.
copyannots
enables importing of annotations (*EXPERIMENTAL*).
$version = $pdf->version($new_version)
$version = $pdf->version()
Get/set the PDF version (e.g. 1.4).

For compatibility with earlier releases, if no decimal point is given, assume "1." precedes the number given.

A warning message is given if you attempt to decrease the PDF version, as you might have already read in a higher level file, or used a higher level feature.

$bool = $pdf->isEncrypted()
Checks if the previously opened PDF is encrypted.
%infohash = $pdf->info(%infohash)
Gets/sets the info structure of the document.

See "info Example" in PDF::Builder::Docs section for an example of the use of this method.

@metadata_attributes = $pdf->infoMetaAttributes(@metadata_attributes)
Gets/sets the supported info-structure tags.

Example:

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

@attributes = $pdf->infoMetaAttributes('CustomField1');
print "Supported Attributes: @attributes\n";
$xml = $pdf->xmpMetadata($xml)
Gets/sets the XMP XML data stream.

See "XMP XML example" in PDF::Builder::Docs section for an example of the use of this method.

$pdf->pageLabel($index, $options)
Sets page label options.

Supported Options:

-style
Roman, roman, decimal, Alpha or alpha.
-start
Restart numbering at given number.
-prefix
Text prefix for numbering.

Example:

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

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

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

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

# Numbering for the Index
$pdf->pageLabel(40, {
    -style => 'Roman'
    -start => 1,
    -prefix => 'Index '
});
$pdf->finishobjects(@objects)
Force objects to be written to file if possible.

Example:

$pdf = PDF::Builder->new(-file => 'our/new.pdf');
...
$pdf->finishobjects($page, $gfx, $txt);
...
$pdf->save();
$pdf->update()
Saves a previously opened document.

Example:

$pdf = PDF::Builder->open('our/to/be/updated.pdf');
...
$pdf->update();
$pdf->saveas($file)
Save the document to $file and remove the object structure from memory.

Caution: Although the object $pdf will still exist, it is no longer usable for any purpose after invoking this method! You will receive error messages about "can't call method new_obj on an undefined value".

Example:

$pdf = PDF::Builder->new();
...
$pdf->saveas('our/new.pdf');
$pdf->save()
Save the document to an already-defined file (or filename) and remove the object structure from memory.

Caution: Although the object $pdf will still exist, it is no longer usable for any purpose after invoking this method! You will receive error messages about "can't call method new_obj on an undefined value".

Example:

$pdf = PDF::Builder->new(-file => 'file_to_output');
...
$pdf->save();
$string = $pdf->stringify()
Return the document as a string and remove the object structure from memory.

Caution: Although the object $pdf will still exist, it is no longer usable for any purpose after invoking this method! You will receive error messages about "can't call method new_obj on an undefined value".

Example:

$pdf = PDF::Builder->new();
...
print $pdf->stringify();
$pdf->end()
Remove the object structure from memory. PDF::Builder 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.

$page = $pdf->page()
$page = $pdf->page($page_number)
Returns a new page object. By default, the page is added to the end of the document. If you give an existing page number, the new page will be inserted in that position, pushing existing pages back by 1 (e.g., page(5) would insert an empty page 5, with the old page 5 now page 6, etc.

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.

Example:

$pdf = PDF::Builder->new();

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

# Add a new first page.  $page becomes page 2.
$another_page = $pdf->page(1);
$page = $pdf->openpage($page_number)
Returns the PDF::Builder::Page object of page $page_number. This is similar to "$page = $pdf->page()", except that $page is not a new, empty page; but contains the contents of that existing page.

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

Example:

$pdf  = PDF::Builder->open('our/99page.pdf');
$page = $pdf->openpage(1);   # returns the first page
$page = $pdf->openpage(99);  # returns the last page
$page = $pdf->openpage(-1);  # returns the last page
$page = $pdf->openpage(999); # returns undef
$xoform = $pdf->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.

Example:

$pdf = PDF::Builder->new();
$old = PDF::Builder->open('our/old.pdf');
$page = $pdf->page();
$gfx = $page->gfx();

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

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

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

Note: You can only import a page from an existing PDF file.

$page = $pdf->import_page($source_pdf)
$page = $pdf->import_page($source_pdf, $source_page_number)
$page = $pdf->import_page($source_pdf, $source_page_number, $target_page_number)
$page = $pdf->import_page($source_pdf, $source_page_number, $target_page_object)
Imports a page from $source_pdf and adds it to the specified position in $pdf.

If the $source_page_number is omitted, 0, or -1; the last page of the source is imported. If the $target_page_number is omitted, 0, or -1; the imported page will be placed as the new last page of the target ($pdf). Otherwise, as with the "page()" method, the page will be inserted before an existing page of that number.

Note: 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.

Example:

$pdf = PDF::Builder->new();
$old = PDF::Builder->open('our/old.pdf');

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

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

Note: You can only import a page from an existing PDF file.

$count = $pdf->pages()
Returns the number of pages in the document.
$pdf->userunit($value)
Sets the global UserUnit, defining the scale factor to multiply any size or coordinate by. For example, "userunit(72)" results in a User Unit of 72 points, or 1 inch.

See "User Units" in PDF::Builder::Docs for more information.

$pdf->mediabox($name)
$pdf->mediabox($name, -orient => 'orientation')
$pdf->mediabox($w,$h)
$pdf->mediabox($llx,$lly, $urx,$ury)
($llx,$lly, $urx,$ury) = $pdf->mediabox()
Sets (or gets) the global MediaBox, defining the width and height (or by corner coordinates, or by standard name) of the output page itself, such as the physical paper size.

See "Media Box" in PDF::Builder::Docs for more information. The method always returns the current bounds (after any set operation).

$pdf->cropbox($name)
$pdf->cropbox($name, -orient => 'orientation')
$pdf->cropbox($w,$h)
$pdf->cropbox($llx,$lly, $urx,$ury)
($llx,$lly, $urx,$ury) = $pdf->cropbox()
Sets (or gets) the global CropBox. This will define the media size to which the output will later be clipped.

See "Crop Box" in PDF::Builder::Docs for more information. The method always returns the current bounds (after any set operation).

$pdf->bleedbox($name)
$pdf->bleedbox($name, -orient => 'orientation')
$pdf->bleedbox($w,$h)
$pdf->bleedbox($llx,$lly, $urx,$ury)
($llx,$lly, $urx,$ury) = $pdf->bleedbox()
Sets (or gets) the global BleedBox. This is typically used for hard copy printing where you want ink to go to the edge of the cut paper.

See "Bleed Box" in PDF::Builder::Docs for more information. The method always returns the current bounds (after any set operation).

$pdf->trimbox($name)
$pdf->trimbox($name, -orient => 'orientation')
$pdf->trimbox($w,$h)
$pdf->trimbox($llx,$lly, $urx,$ury)
($llx,$lly, $urx,$ury) = $pdf->trimbox()
Sets (or gets) the global TrimBox. This is supposed to be the actual dimensions of the finished page (after trimming of the paper).

See "Trim Box" in PDF::Builder::Docs for more information. The method always returns the current bounds (after any set operation).

$pdf->artbox($name)
$pdf->artbox($name, -orient => 'orientation')
$pdf->artbox($w,$h)
$pdf->artbox($llx,$lly, $urx,$ury)
($llx,$lly, $urx,$ury) = $pdf->artbox()
Sets (or gets) the global ArtBox. This is supposed to define "the extent of the page's meaningful content".

See "Art Box" in PDF::Builder::Docs for more information. The method always returns the current bounds (after any set operation).

@directories = PDF::Builder::addFontDirs($dir1, $dir2, ...)
Adds one or more directories to the search path for finding font files.

Returns the list of searched directories.

$font = $pdf->corefont($fontname, %options)
$font = $pdf->corefont($fontname)
Returns a new Adobe core font object. For details, see "Core Fonts" in PDF::Builder::Docs.

See also PDF::Builder::Resource::Font::CoreFont.

$font = $pdf->psfont($ps_file, %options)
$font = $pdf->psfont($ps_file)
Returns a new Adobe Type1 ("PostScript") font object. For details, see "PS Fonts" in PDF::Builder::Docs.

See also PDF::Builder::Resource::Font::Postscript.

$font = $pdf->ttfont($ttf_file, %options)
$font = $pdf->ttfont($ttf_file)
Returns a new TrueType (or OpenType) font object. For details, see "TrueType Fonts" in PDF::Builder::Docs.
$font = $pdf->cjkfont($cjkname, %options)
$font = $pdf->cjkfont($cjkname)
Returns a new CJK font object. These are TrueType-like fonts for East Asian languages (Chinese, Japanese, Korean). For details, see "CJK Fonts" in PDF::Builder::Docs.

See also PDF::Builder::Resource::CIDFont::CJKFont

$font = $pdf->synfont($basefont, %options)
$font = $pdf->synfont($basefont)
Returns a new synthetic font object. These are modifications to a core (or PS/T1 or TTF/OTF) font, where the font may be replaced by a Type1 or Type3 PostScript font. This does not appear to work with CJK fonts (created with "cjkfont" method). For details, see "Synthetic Fonts" in PDF::Builder::Docs.

See also PDF::Builder::Resource::Font::SynFont

$font = $pdf->bdfont($bdf_file, @options)
$font = $pdf->bdfont($bdf_file)
Returns a new BDF (bitmapped distribution format) font object, based on the specified Adobe BDF file.

See also PDF::Builder::Resource::Font::BdFont

$font = $pdf->unifont(@fontspecs, %options)
$font = $pdf->unifont(@fontspecs)
Returns a new uni-font object, based on the specified fonts and options.

BEWARE: This is not a true PDF-object, but a virtual/abstract font definition!

See also PDF::Builder::Resource::UniFont.

Valid %options are:

-encode
Changes the encoding of the font from its default.

$jpeg = $pdf->image_jpeg($file)
Imports and returns a new JPEG image object. $file may be either a filename or a filehandle.

See PDF::Builder::Resource::XObject::Image::JPEG for additional information and "examples/Content.pl" for some examples of placing an image on a page.

$tiff = $pdf->image_tiff($file, %opts)
$tiff = $pdf->image_tiff($file)
Imports and returns a new TIFF image object. $file may be either a filename or a filehandle. For details, see "TIFF Images" in PDF::Builder::Docs.

See PDF::Builder::Resource::XObject::Image::TIFF and PDF::Builder::Resource::XObject::Image::TIFF_GT for additional information and "examples/Content.pl" for some examples of placing an image on a page (JPEG, but the principle is the same). There is an optional TIFF library described, that gives more capability than the default one.

$rc = $pdf->LA_GT()
Returns 1 if the library name (package) Graphics::TIFF is installed, and 0 otherwise. For this optional library, this call can be used to know if it is safe to use certain functions. For example:

if ($pdf->LA_GT() {
    # is installed and usable
} else {
    # not available. you will be running the old, pure PERL code
}
$pnm = $pdf->image_pnm($file)
Imports and returns a new PNM image object. $file may be either a filename or a filehandle.

See "examples/Content.pl" for some examples of placing an image on a page (JPEG, but the principle is the same).

$png = $pdf->image_png($file, %options)
$png = $pdf->image_png($file)
Imports and returns a new PNG image object. $file may be either a filename or a filehandle. For details, see "PNG Images" in PDF::Builder::Docs.

See PDF::Builder::Resource::XObject::Image::PNG and PDF::Builder::Resource::XObject::Image::PNG_IPL for additional information and "examples/Content.pl" for some examples of placing an image on a page (JPEG, but the principle is the same). There is an optional PNG library (PNG_IPL) described, that gives more capability than the default one.

$rc = $pdf->LA_IPL()
Returns 1 if the library name (package) Image::PNG::Libpng is installed, and 0 otherwise. For this optional library, this call can be used to know if it is safe to use certain functions. For example:

if ($pdf->LA_IPL() {
    # is installed and usable
} else {
    # not available. don't use 16bps or interlaced PNG image files
}
$gif = $pdf->image_gif($file)
Imports and returns a new GIF image object. $file may be either a filename or a filehandle.

See PDF::Builder::Resource::XObject::Image::GIF for additional information and "examples/Content.pl" for some examples of placing an image on a page (JPEG, but the principle is the same).

$gdf = $pdf->image_gd($gd_object, %options)
$gdf = $pdf->image_gd($gd_object)
Imports and returns a new image object from Image::GD.

Valid %options are:

-lossless => 1
Use lossless compression.

See PDF::Builder::Resource::XObject::Image::GD for additional information and "examples/Content.pl" for some examples of placing an image on a page (JPEG, but the principle is the same).

$cs = $pdf->colorspace_act($file)
Returns a new colorspace object based on an Adobe Color Table file.

See PDF::Builder::Resource::ColorSpace::Indexed::ACTFile for a reference to the file format's specification.

$cs = $pdf->colorspace_web()
Returns a new colorspace-object based on the "web-safe" color palette.
$cs = $pdf->colorspace_hue()
Returns a new colorspace-object based on the hue color palette.

See PDF::Builder::Resource::ColorSpace::Indexed::Hue for an explanation.

$cs = $pdf->colorspace_separation($tint, $color)
Returns a new separation colorspace object based on the parameters.

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

$color 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.

$cs = $pdf->colorspace_devicen(\@tintCSx, $samples)
$cs = $pdf->colorspace_devicen(\@tintCSx)
Returns a new DeviceN colorspace object based on the parameters.

Example:

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

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

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

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

These are glue routines to the actual barcode rendering routines found elsewhere.
$bc = $pdf->xo_codabar(%options)
$bc = $pdf->xo_code128(%options)
$bc = $pdf->xo_2of5int(%options)
$bc = $pdf->xo_3of9(%options)
$bc = $pdf->xo_ean13(%options)
Creates the specified barcode object as a form XObject.

$xo = $pdf->xo_form()
Returns a new form XObject.
$egs = $pdf->egstate()
Returns a new extended graphics state object.
$obj = $pdf->pattern(%options)
$obj = $pdf->pattern()
Returns a new pattern object.
$obj = $pdf->shading(%options)
$obj = $pdf->shading()
Returns a new shading object.
$otls = $pdf->outlines()
Returns a new or existing outlines object.
$ndest = $pdf->named_destination()
Returns a new or existing named destination object.
2021-05-02 perl v5.32.1