PDF::Builder(3)

πŸ’– PDF::Builder β€” the manual page πŸ’–

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

okay bestie, sit down, hydrate, because we're about to make PDFs with Perl and honestly? it's giving main character energy. πŸ¦‹


✨ NAME ✨

PDF::Builder β€” Facilitates the creation and modification of PDF files πŸ’…

like, it makes PDFs. and also edits PDFs. that's the whole vibe. periodt.


✨ SYNOPSIS ✨

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->open_page($page_number);

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

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

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

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

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

look at that. a whole PDF, born in like twelve lines. iconic. πŸ‘‘


🌸 SOME SPECIAL NOTES 🌸

πŸ“– SOFTWARE DEVELOPMENT KIT

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

🧚 OPTIONAL LIBRARIES

PDF::Builder can make use of some optional libraries β€” they're not required for a successful installation, but they lowkey improve speed and capabilities. See "Optional Libraries" in PDF::Builder::Docs for the deets.

πŸ”€ STRINGS (CHARACTER TEXT)

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

🎨 RENDERING ORDER

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

πŸ“„ PDF VERSIONS SUPPORTED

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 the details.

πŸͺ SUPPORTED PERL VERSIONS (BACKWARDS COMPATIBILITY GOALS)

PDF::Builder intends to support all major Perl versions released in the past six years, plus one, so it keeps working for the life of most long-term-stable (LTS) server distributions. See "Supported Perl Versions" in PDF::Builder::Docs for more info, including the expected cutoff dates for Perl versions.

πŸ’€ KNOWN ISSUES

This module does not work with Perl's -l command-line switch. not even a little. πŸ’€

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

πŸ“œ HISTORY

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

✍️ AUTHOR

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

It was maintained by Steve Simms, who is still contributing new code to it (which often ends up in PDF::Builder).

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

πŸ†˜ SUPPORT

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

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

A formatted copy of the documentation (POD) may be found online, for your convenience, at https://www.catskilltech.com/Documentation/PDF/Builder.html.

Copies of most of the output of examples/ sample programs may be found online at https://www.catskilltech.com/Examples/PDF/Builder.html.

Bug reports are on https://github.com/PhilterPaper/Perl-PDF-Builder/issues?q=is%3Aissue+sort%3Aupdated-desc (with the "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. That's not what a PR is for, and it's 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. no cap. 🚫

βš–οΈ LICENSE

This software is Copyright (c) 2017-2025 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.


🌈 GENERAL PURPOSE METHODS 🌈

πŸ†• new

$pdf = PDF::Builder->new(%opts)

Creates a new PDF object. baby's first PDF 🍼

Options

  • file β€” If you'll be saving it as a file and you already know the filename, you can hand over the 'file' option to minimize possible memory requirements later on (the file is opened immediately for writing, instead of waiting until the "save"). The "file" can also be a filehandle. convenient!!
  • compress β€” The 'compress' option specifies stream compression: default is 'flate', 'none' (or 0) is no compression. No other compression methods are currently supported. that's the whole menu bestie.
  • 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, either because a higher PDF level file was read in, or because a higher level feature was requested. A value of 0 suppresses the warning message.
  • diaglevel β€” The 'diaglevel' option specifies 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->to_string();

$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();

πŸ“ default_page_size

@rectangle = $pdf->default_page_size($size); # Set

@rectangle = $pdf->default_page_size() # Get

Sets the default physical size for pages in the PDF. If called without arguments (Get), it returns an array of the coordinates of the rectangle describing the default physical page size (the Media Box). Setting the size also returns the resulting media size. slay ✨

This is basically an alternate method of defining the mediabox() call, added for compatibility with PDF::API2.

See "Page Sizes" in PDF::Builder::Page for possible values.

πŸ’‘ Heads up: this method is only at the PDF (document) level. It is not implemented at the page level. If you want to set or get the page-level override of the media size, use the mediabox() method instead.

πŸ“ default_page_boundaries

%boundaries = $pdf->default_page_boundaries('media' =>
     [xmin, ymin, xmax, ymax]);  # Set the media box

%boundaries = $pdf->default_page_boundaries(); # Get (all five)
@media_rect = @{ $boundaries{'media'} }; # show 'media' box

Sets default prepress page boundaries ('boxes') for pages in the PDF. If called without arguments, it returns the coordinates of the rectangles describing each of the supported page boundaries, as a hash of array refs. Each will be US Letter size, unless it has been explicitly changed. Setting the values will also return the hash.

See the equivalent "page_boundaries" method in PDF::Builder::Page for details.


πŸ“₯ INPUT/OUTPUT METHODS πŸ“€

πŸ“‚ open

$pdf = PDF::Builder->open($pdf_file, %opts)

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

πŸ“¨ from_string, open_scalar, openScalar

$pdf = PDF::Builder->from_string($pdf_string, %opts)

Opens a PDF contained in a string. See new() for other options.

  • diags => 1 β€” Display warnings when a 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 croak $@;
undef $/;  # Read the whole file at once
$pdf_string = <$fh>;

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

Alternate name: "open_scalar"

"from_string" was formerly known as "open_scalar" (and even before that, as "openScalar"), and this older name is still valid as an alternative to "from_string". It is possible that "open_scalar" will be deprecated and then removed some time in the future, so it may be advisable to use "from_string" in new work. 🫢

🧡 to_string, stringify

$string = $pdf->to_string()

Returns the document as a string and removes 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->to_string();

Alternate name: "stringify"

"to_string" was formerly known as "stringify", and this older name is still valid as an alternative to "to_string". It is possible that "stringify" will be deprecated and then removed some time in the future, so it may be advisable to use "to_string" in new work. ✨


🧚 finishobjects 🧚

$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();

Note: this method is now considered obsolete, and may be deprecated. It allows for objects to be written to disk in advance of finally saving and closing the file. Otherwise, it's no different than just calling save() when all changes have been made. There's no memory advantage since "ship_out" doesn't remove objects from memory. πŸ¦‹

πŸ¦‹ update πŸ¦‹

$pdf->update()

Saves a previously opened document.

Example:

$pdf = PDF::Builder->open('our/to/be/updated.pdf');
...
$pdf->update();

Note: it is considered better to simply save() the file, rather than calling update(). They end up doing the same thing, anyway. This method may be deprecated in the future. πŸ’€

🌸 saveas 🌸

$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');

πŸ’Ύ save πŸ’Ύ

$pdf->save()

$pdf->save(filename)

Save the document to an already-defined file (or filename) and remove the object structure from memory. Optionally, a new filename may be given. πŸŽ€

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

Note: now that save() can take a filename as an argument, it effectively is interchangeable with saveas(). This is strictly for compatibility with recent changes to PDF::API2. Unlike PDF::API2, we are not deprecating the saveas() method, because in user interfaces, "save" normally means that the current filename is known and is to be used, while "saveas" normally means that (whether or not there is a current filename) a new filename is to be used. ✨

πŸ”’ close, release, end πŸ”’

$pdf->close();

Close an open file (if relevant) and 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. πŸ’™

Alternate names: "release" and "end"

πŸ‘‹ end πŸ‘‹

$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 to_string a PDF. You should only need to call it explicitly if you are reading PDF files and not writing them. πŸ“

This (and release) are older and now deprecated names formerly used in PDF::API2 and PDF::Builder. You should try to avoid having to explicitly call them. ⚠️


πŸ’– METADATA METHODS πŸ’–

🏷️ title 🏷️

$title = $pdf->title();

$pdf = $pdf->title($title);

Get/set/clear the document's title. ✨

✍️ author ✍️

$author = $pdf->author();

$pdf = $pdf->author($author);

Get/set/clear the name of the person who created the document. πŸ’œ

πŸ“ subject πŸ“

$subject = $pdf->subject();

$pdf = $pdf->subject($subject);

Get/set/clear the subject of the document. 🌸

πŸ”‘ keywords πŸ”‘

$keywords = $pdf->keywords();

$pdf = $pdf->keywords($keywords);

Get/set/clear a space-separated string of keywords associated with the document. πŸ¦‹

🎨 creator 🎨

$creator = $pdf->creator();

$pdf = $pdf->creator($creator);

Get/set/clear the name of the product that created the document prior to its conversion to PDF. πŸ’Ž

🏭 producer 🏭

$producer = $pdf->producer();

$pdf = $pdf->producer($producer);

Get/set/clear the name of the product that converted the original document to PDF.

PDF::Builder fills in this field when creating a PDF. ⭐

πŸ“… created πŸ“…

$date = $pdf->created();

$pdf = $pdf->created($date);

Get/set/clear the document's creation date.

The date format is "D:YYYYMMDDHHmmSSOHH'mm", where "D:" is a static prefix identifying the string as a PDF date. The date may be truncated at any point after the year. "O" is one of "+", "-", or "Z", with the following "HH'mm" representing an offset from UTC.

See comments in the internal function _is_date() for more information on the inconsistency of PDF standards on exactly what the date format should be! 😭

When setting the date, "D:" will be prepended automatically if omitted. πŸ’…

πŸ”„ modified πŸ”„

$date = $pdf->modified();

$pdf = $pdf->modified($date);

Get/set/clear the document's modification date. The date format is as described in "created" above.

See comments in the internal function _is_date() for more information on the inconsistency of PDF standards on exactly what the date format should be! 😭

πŸ—‚οΈ info_metadata πŸ—‚οΈ

%info = $pdf->info_metadata(); # Get all keys and values

$value = $pdf->info_metadata($key); # Get the value of one key

$pdf = $pdf->info_metadata($key, $value); # Set the value of one key

Get/set/clear a key in the document's information dictionary. The standard keys (title, author, etc.) have their own accessors, so this is primarily intended for interacting with custom metadata.

Pass "undef" as the value in order to remove the key from the dictionary. ✨

See comments in the internal function _is_date() for more information on the inconsistency of PDF standards on exactly what the date format should be! This applies to CreationDate and ModDate keys. ⚠️

πŸ“‹ info πŸ“‹

%infohash = $pdf->info()

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

Note: this method is still available, for compatibility purposes. It is better to use individual accessors or "info_metadata" instead. πŸ’™

🏷️ infoMetaAttributes 🏷️

@metadata_attributes = $pdf->infoMetaAttributes()

@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";

Note: this method is still available for compatibility purposes, but the use of "info_metadata" instead is encouraged. 🌸

πŸ“„ xml_metadata πŸ“„

$xml = $pdf->xml_metadata();

$pdf = $pdf->xml_metadata($xml);

Gets/sets the document's XML metadata stream. πŸ¦‹

πŸ“¦ xmpMetadata πŸ“¦

$xml = $pdf->xmpMetadata()  # Get

$xml = $pdf->xmpMetadata($xml)  # Set (also returns $xml value)

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.

This method is considered obsolete. Use "xml_metadata" instead. ⚠️

βš™οΈ default βš™οΈ

$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).
CAUTION: Perl::Critic (tools/1_pc.pl) has started flagging the name "default" as a reserved keyword in higher Perl versions. Use with caution, and be aware that this name may have to be changed in the future. πŸ’€

πŸ”’ version πŸ”’

$version = $pdf->pdf_version() # Get

$version = $pdf->pdf_version($version) # Set (also returns newly set version)

Gets/sets the PDF version (e.g., 1.5). 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. ⚠️

See PDF::Builder::Basic::PDF::File for additional information on the "version" method. πŸ“š

πŸ” is_encrypted, isEncrypted πŸ”

$bool = $pdf->is_encrypted()

Checks if the previously opened PDF is encrypted.

Alternate name: "isEncrypted"

This is the older name; it is kept for compatibility with PDF::API2. πŸ’š

✨ INTERACTIVE FEATURE METHODS ✨


outline, outlines

$otls = $pdf->outline()

Creates (if it's not already there) and hands you back the document's 'outline' tree πŸ’– β€” which is also known as its 'bookmarks', or the 'table of contents', depending on which PDF reader you're looking at it in.

If you wanna poke at or change that outline tree, go see PDF::Builder::Outlines.

Alternate name: outlines

This one's the older name; it's just hanging around for compatibility. πŸ’…


page_layout

$layout = $pdf->page_layout();

$pdf = $pdf->page_layout($layout);

Gets/sets the page layout that should be used when the PDF gets opened. πŸ‘‘

$layout is one of these:

single_page (or undef)

Display one page at a time.

one_column

Display the pages in one column (a.k.a. continuous).

two_column_left

Display the pages in two columns, with odd-numbered pages on the left.

two_column_right

Display the pages in two columns, with odd-numbered pages on the right.

two_page_left

Display two pages at a time, with odd-numbered pages on the left.

two_page_right

Display two pages at a time, with odd-numbered pages on the right.

This got split out from preferences() for compatibility with PDF::API2. And fr fr, it can both set (assign) and get (query) the settings. 🫢


page_mode

$mode = $pdf->page_mode(); # Get

$pdf = $pdf->page_mode($mode); # Set

Gets/sets the page mode, which describes how the PDF should be displayed when opened. πŸ¦‹

$mode is one of these:

none (or undef)

Neither outlines nor thumbnails should be displayed.

outlines

Show the document outline.

thumbnails

Show the page thumbnails.

full_screen

Open in full-screen mode, with no menu bar, window controls, or any other window visible. Main character energy, literally zero UI. 😌

optional_content

Show the optional content group panel.

attachments

Show the attachments panel.

This got split out from preferences() for compatibility with PDF::API2. And yes bestie, it can both set (assign) and get (query) the settings too. ✨


viewer_preferences

%preferences = $pdf->viewer_preferences(); # Get

$pdf = $pdf->viewer_preferences(%preferences); # Set

Gets/sets PDF viewer preferences, as described in PDF::Builder::ViewerPreferences.

This got split out from preferences() for compatibility with PDF::API2. And it also can both set (assign) and get (query) the settings used. πŸ’œ


preferences

$pdf->preferences(%opts)

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 the details on all these option groups, and "Page Fit Options" in PDF::Builder::Docs for page positioning.

Note: the various preferences have been split out into their own methods. It is preferred that you use these specific methods. πŸ’…

🌸 PAGE METHODS 🌸


page

$page = $pdf->page()

$page = $pdf->page($page_number)

Returns a new page object. By default, the page gets added to the end of the document. But if you hand it an existing page number, the new page will be inserted right in that position, pushing the existing pages back by 1 (so like, page(5) would insert an empty page 5, and the old page 5 is now page 6, etc.).

If $page_number is -1, the new page is inserted as the second-to-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);

open_page, openpage

$page = $pdf->open_page($page_number)

Returns the PDF::Builder::Page object of page $page_number. This is similar to $page = $pdf->page(), except that $page isn't a new, empty page β€” it's got the contents of that existing page in it. πŸ”₯

If $page_number is 0, -1, or unspecified, it will return the last page in the document. And if the page you asked for is out of range, the $page you get back will be undefined. πŸ™ˆ

Example:

$pdf  = PDF::Builder->open('our/99page.pdf');
$page = $pdf->open_page(1);   # returns the first page
$page = $pdf->open_page(99);  # returns the last page
$page = $pdf->open_page(-1);  # returns the last page
$page = $pdf->open_page(999); # returns undef
$page = $pdf->open_page(0);   # returns the last page
$page = $pdf->open_page();    # returns the last page

Alternate name: openpage

This is the older name; it is kept for compatibility until after June 2023 (deprecated, as previously announced). ⚠️


import_page, importpage

$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 position you specified in $pdf. πŸ“₯

If $source_page_number is omitted, 0, or -1; the last page of the source gets imported. If $target_page_number is omitted, 0, or -1; the imported page gets placed as the new last page of the target ($pdf). Otherwise, same energy as the page() method β€” the page gets 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:

my $pdf = PDF::Builder->new();
my $source = PDF::Builder->open('source.pdf');

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

$pdf->saveas('sample.pdf');
Note: You can only import a page from an existing PDF file. No cap. 🚫

Alternate name: importpage

This name is still valid in PDF::API2, so it's included here for compatibility.


embed_page, importPageIntoForm

$xoform = $pdf->embed_page($source_pdf, $source_page_number)

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

This is useful if you wanna transpose the imported page somewhat differently onto a page (e.g. two-up, four-up, etc.). So many options bestie.

If $source_page_number is 0 or -1, it will return the last page in the document. The default value for the $source_page_number is 0 (return last page).

Example:

# take page 2 of source.pdf and add to empty doc sample.pdf at half size
# note that sample.pdf could be an existing document!
#
my $pdf = PDF::Builder->new();                      # so far, empty document
my $source = PDF::Builder->open('source.pdf');        # content to copy over
my $page = $pdf->page();                      # place to be actually updated

# Import Page 2 from the source PDF
my $xo = $pdf->embed_page($source, 2);

# Add it to the new PDF's first page at 1/2 scale
my ($x, $y) = (0, 0);
$page->object($xo, $x, $y, 0.5);

$pdf->save('sample.pdf');
Note: You can only import a page from an existing PDF file. πŸ’…

Alternate name: importPageIntoForm

This is the older name; it is kept for compatibility.


page_count, pages

$count = $pdf->page_count()

Returns the number of pages in the document. πŸ”’

Alternate name: pages

This is the old name; it is kept for compatibility.


page_labels, pageLabel

$pdf->page_labels($page_number, %opts)

Sets the page label numbering format, for the PDF Reader's page-selection slider thumb (not the outline/bookmarks, okay? just the thumb). As of right now, there's no method to automatically synchronize a page's label with the outline/bookmarks, or to somewhere on the printed page. Depending on which PDF Reader you're using, this formatted page label may show up in the reader control area as the current page number. πŸŽ€

CAUTIONS:

  1. The given page index started at 0 for the old method (pageLabel()), which is the internal PDF array index, while for the new method (page_labels()) it starts with 1, the visible page number! Don't get confused. 😭
  2. Options for the old method (pageLabel) were a hashref, while for the new method (page_labels) it's a hash. This permits pageLabel() to accept multiple page number schemes in one call, rather than one per call as per page_labels().
  3. Many PDF readers do not support page labels; they simply (at most) label the sliding thumb with the physical page number. Adobe Acrobat Reader (free version) appears to have a bug in some versions, where if the only page label is 'decimal' (the default), it labels the thumb as though no page labels were defined ("Page m of n"). You can get around this problem by using an explicit start option value, e.g., 'start' => 1. However, for your convenience, the start option now defaults to 1. πŸ’€
# Generate a 30-page PDF
my $pdf = PDF::Builder->new();
$pdf->page() for 1..30;

# Number pages i to v, 1 to 20, and A-1 to A-5, respectively
$pdf->page_labels(1, 'style' => 'roman');
$pdf->page_labels(6, 'style' => 'decimal');
$pdf->page_labels(26, 'style' => 'decimal', 'prefix' => 'A-');

or...

$pdf->pageLabel(0,  { style => 'roman' },
                5,  { style => 'decimal' },
                25, { style => 'decimal', prefix => 'A-' });

$pdf->save('sample.pdf');

Supported Options:

  • style β€” Roman (I,II,III,...), roman (i,ii,iii,...), decimal (1,2,3,...), Alpha (A,B,C,...), alpha (a,b,c,...), or nocounter. This is the styling of the counter part of the label (unless nocounter, in which case there's no counter output at all). Note that arabic is permitted as a synonym for decimal. πŸ’…
  • start β€” (Re)start numbering the counter at the given page number (this is a decimal integer, not the styled counter). By default it starts at 1, and resets to 1 at each call to page_labels()! You need to explicitly give start if you want to continue counting at the current page number when you call page_labels(), whether or not you're changing the format. 😀

Also note that the counter starts at physical page 1, while the page $index number in the page_labels() call (as well as the PDF PageLabels dictionary) starts at logical page (index) 0. πŸŒ€

πŸ’– prefix

Text that goes before the number, bestie β€” like an Appendix letter B-. If style is nocounter, then literally just this text shows up, nothing else. Otherwise a styled counter gets glued onto the end of it. And if you straight-up omit style, remember it defaults to a decimal number, which will be appended to your prefix. (so your prefix is never alone unless you say nocounter, got it? πŸ‘‘

Per the Adobe/ISO PDF spec, a prefix of Content is special β€” any /S counter gets ignored and only that text is used. But apparently that's ignored in practice (so just use a style of nocounter if you want to suppress the counter). πŸ’€

Dotted inserted page numbers

Wanna slide a range of pages in, like 3 pages wedged between existing pages 37 and 38? Easy. Use a prefix of '37.' and decimal numbering starting (start) at 1 or wherever you like. That gives you pages 37.1, 37.2, 37.3. πŸŽ€ And if you want leading 0's on the numbers β€” for when you later realize you need more pages squeezed in, like page 37.05 between 37 and 37.1 β€” use a prefix of '37.0' and set start at 5.

Just keep in mind: only the (rightmost) counter β€” the one that starts at the start value β€” gets incremented (and formatted) by the PDF Reader. Everything else (the prefix) is a constant string. Worst case, you end up defining a page label for every single page. πŸ™ˆ

Example:

# Start with lowercase Roman Numerals at the 1st page, starting with i (1)
$pdf->page_labels(1,
    'style' => 'roman',
);

or, if you're rolling with the old name:

$pdf->pageLabel(0,
    { 'style' => 'roman' },
);
# Switch to Arabic (decimal) at the 5th page, starting with 1
$pdf->page_labels(5,
    'style' => 'decimal',
);

or:

$pdf->pageLabel(4,
    { 'style' => 'decimal' },
);
# invalid style at the 25th page, should just continue
# with decimal at the current counter
$pdf->page_labels(25,
    'style' => 'raman_noodles',  # fail over to decimal
       # note that older versions of PDF::API2 may see the 'r' and
       #   treat it as 'roman'
    'start' => 25,  # necessary, otherwise would restart at 1
);
# No page label at the 31st and 32nd pages. Note that this could be
# confusing to the person viewing the PDF, but may be appropriate if
# the page itself has no numbering.
$pdf->page_labels(31,
    'style' => 'nocounter',
);
# Numbering for Appendix A at the 33rd page, A-1, A-2,...
$pdf->page_labels(33,
    'start' => 1,  # unnecessary
    'prefix' => 'A-'
);
# Numbering for Appendix B at the 37th page, B-1, B-2,...
$pdf->page_labels(37,
    'prefix' => 'B-'
);
# Numbering for the Index at the 41st page, Index I, Index II,...
$pdf->page_labels(41,
    'style' => 'Roman',
    'start' => 1,  # unnecessary
    'prefix' => 'Index '  # note trailing space
);
# Unnumbered 'Index' at the 45th page, Index, Index,...
$pdf->page_labels(45,
    'style' => 'nocounter',
    'prefix' => 'Index '
);

Alternate name: pageLabel 🌈

This old method name is kept around for compatibility with old user code. But heads up, bestie: with pageLabel you have to make the options list an anonymous hash by wrapping { } around the whole list, even if it's only got one item in it. Also remember that the page number (index) for pageLabel starts at 0 (same as the PDF page index) instead of 1 (like page_labels does). And finally, pageLabel() still lets you define multiple page numbering schemes in a single call. 🫢


🌸 userunit

$pdf->userunit($value)

Sets the global UserUnit β€” the scale factor everything else gets multiplied by when it comes to sizes or coordinates. So like, userunit(72) gives you a User Unit of 72 points, which is 1 inch. πŸ“

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


🌸 mediabox

$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 β€” that's the width and height (or corner coordinates, or a standard name) of the output page itself, i.e. the physical paper size. πŸ“„

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


🌸 cropbox

$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 defines the media size that the output will later be clipped to. βœ‚οΈ

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


🌸 bleedbox

$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 one's for hard copy printing where you want the ink to run all the way to the edge of the cut paper. πŸ–¨οΈ

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


🌸 trimbox

$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 β€” like, after the paper's been trimmed. βœ‚οΈβœ¨

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


🌸 artbox

$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". What counts as "meaningful" is up to the author of the page β€” but it'd usually leave out "decorative" graphics and such, and possibly titles, headers, footers, and page numbers. πŸ’…

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

πŸ’– FONT METHODS πŸ’–

🌸 Embedding of Fonts 🌸

⚠️ CAUTION, bestie, this one matters: some font routines (currently only ttfont()) will automatically embed font definitions, all on their own, for the purpose of improving portability of PDF files. But here's the thing β€” font copyright and licensing terms vary by font provider, and some of them straight-up prohibit embedding of their fonts, either entirely, or they'll only allow the subset of glyphs actually used in the document. So you need to be aware of the terms, and use the "embed" and "nosubset" flags as appropriate. And ngl? The PDF::Builder font routines currently have no means to automatically detect any embedding limitations for a given font, and they cannot default their behavior accordingly! 😭 So that part is on you, fr fr.

corefont

$font = $pdf->corefont($fontname, %opts)

Returns a new Adobe core font object. For all the deets, including the supported %opts, go look at PDF::Builder::Resource::Font::CoreFont. Note that this is an Adobe-standard corefont name, and not a file name. Big difference, don't mix them up πŸ’…

See also "Core Fonts" in PDF::Builder::Docs for additional information, including Notes and Limitations.

psfont

$font = $pdf->psfont($ps_file, %opts)

Returns a new Adobe Type1 ("PostScript", "T1") font object. For all the deets, including the supported %opts, see PDF::Builder::Resource::Font::Postscript.

See also "PS Fonts" in PDF::Builder::Docs for additional information, including Notes and Limitations.

ttfont

$font = $pdf->ttfont($ttf_file, %opts)

Returns a new TrueType (or OpenType) font object. For all the deets, including the supported %opts, see PDF::Builder::Resource::CIDFont::TrueType.

See also "TrueType Fonts" in PDF::Builder::Docs for additional information, including Notes and Limitations.

bdfont

$font = $pdf->bdfont($bdf_file, @opts)

Returns a new BDF (bitmapped distribution format) font object, based on the Adobe BDF file you specified. Okay so real talk β€” these are very low resolution fonts, like they look like they came straight off a dot-matrix printer πŸ“ , and they should only be used for decorative or novelty purposes. It's giving retro, it's giving ✨aesthetic✨, but it is not giving readable body text.

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

cjkfont

$font = $pdf->cjkfont($cjkname, %opts)

Returns a new CJK font object. These are TrueType-like fonts for East Asian languages (Chinese, Japanese, Korean). For all the deets, including the supported %opts, see PDF::Builder::Resource::CIDFont::CJKFont, as well as "CJK Fonts" in PDF::Builder::Docs.

NOTE: "cjkfont" is quite old and is not well supported. We recommend that you try using "ttfont" (or another font routine, if it's not TTF/OTF) with the appropriate CJK font file instead. Most of those appear to be .ttf or .otf format anyway. PDFs created using "cjkfont" may not be fully portable, and support for "cjkfont" may be dropped in a future release. πŸ™ˆ We would genuinely appreciate hearing from you if you are successfully using "cjkfont", and are unable to use "ttfont" instead β€” like, please tell us, bestie.

Among other things, "cjkfont" selections are limited, because they require CMAP files; they may or may not subset correctly; and they can not be used as the base for synthetic fonts. It's giving limitations, ngl.

font

$font = $pdf->font($name, %opts)

A convenience function to add a font to the PDF without having to specify the format. Returns the font object, to be used by PDF::Builder::Content. So chill, it just figures it out for you 🫢

The font $name is either the name of one of the standard 14 fonts ("STANDARD FONTS" in PDF::Builder::Resource::Font::CoreFont), such as "Helvetica", a "Font::TTF::Font" object, or the path to a font file (including an extension/filetype). There are 15 additional core fonts on a Windows system. Note that the exact name of a core font needs to be given. The file extension (if a path is given) determines what type of font file it is.

my $pdf = PDF::Builder->new();
my $font1 = $pdf->font('Helvetica-Bold');
my $font2 = $pdf->font('/path/to/ComicSans.ttf');
my $page = $pdf->page();
my $content = $page->text();

$content->position(1 * 72, 9 * 72);
$content->font($font1, 24);
$content->text('Hello, World!');

$content->position(0, -36);
$content->font($font2, 12);
$content->text('This is some sample text.');

$pdf->saveas('sample.pdf');

The path can be omitted if the font file is in the current directory or one of the directories returned by "font_path". Iconic, honestly.

Core, TrueType (ttf/otf), Adobe PostScript Type 1 (pfa/pfb/t1), and Adobe Glyph Bitmap Distribution Format (bdf) fonts are supported. ✨


The following options (%opts) are available:

  • format β€” the font format is normally detected automatically based on the file's extension (if one is given, as in non-core fonts). If you're using a font with an atypical extension, you can set "format" to one of "truetype" (TrueType or OpenType), "type1" (PostScript Type 1), or "bitmap" (Adobe Bitmap). There is no "format" entry for Core fonts, because the name must be an exact match. Periodt.
  • (other options) β€” the %opts entries get passed on to the appropriate font format routine (corefont(), ttfont(), etc.), so they can totally be used here. These include 'encode', 'pdfname', 'pfmfile', 'dokern', etc. See the appropriate font routine for a full list of the supported options.

standard_fonts

@names = $pdf->standard_fonts($flag)

Returns the names of the 14 standard (built-in) "core" fonts, if $flag is omitted or "false" (0). See PDF::API2::Resource::Font::CoreFont for details. Note that these do not include the 14 additional Windows "core" fonts extension, unless $flag is given with a value of "true" (1).

is_standard_font

$boolean = PDF::Builder->is_standard_font($name);

$boolean = PDF::Builder->is_standard_font($name, $flag);

Returns true if $name is an exact, case-sensitive match for one of the standard font names. Case-sensitive, bestie, so don't come at it with lowercase and expect a yes πŸ’…

Note that these do not include the 14 additional Windows "core" fonts extension, unless $flag is given with a value of "true" (1), in which case, $name will also be checked against the additional font names.

font_path

@directories = PDF::Builder->font_path()

Return the list of directories that will be searched (in order) in addition to the current directory when you add a font to a PDF without including the full path to the font file.

add_to_font_path, addFontDirs

@directories = PDF::Builder::add_to_font_path('/my/fonts', '/path/to/fonts', ...)

Adds one or more directories to the list of paths to be searched for font files.

Returns the font search path.

Alternate name: "addFontDirs"

Prior to recent changes to PDF::API2, this method was addFontDirs(). This method is still available, but may be deprecated some time in the future. So like... heads up. ⏳

set_font_path

@directories = PDF::Builder->set_font_path('/my/fonts', '/path/to/fonts');

Replace the existing font search path. This should only be necessary if you need to remove a directory from the path for some reason, or if you need to reorder the list. Basically: only touch this if you actually have to.

Returns the font search path.

synfont, synthetic_font

$font = $pdf->synfont($basefont, %opts)

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 the "cjkfont" method). For details, see "Synthetic Fonts" in PDF::Builder::Docs.

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

Alternate name: "synthetic_font"

Prior to recent PDF::API2 changes, the routine to create modified fonts was "synfont". PDF::API2 has renamed it to "synthetic_font", which the author does not like, but to maintain compatibility, "synthetic_font" is available as an alias.

There are also some minor option differences (incompatibilities) discussed in "SynFont", including the value of 'bold' between the two entry points. πŸ‘€

unifont

$font = $pdf->unifont(@fontspecs, %opts)

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! Like, it's giving main character energy but it's not a real PDF thing, okay?

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


πŸ‘‘ Font Manager methods πŸ‘‘

The Font Manager is automatically initialized. No setup needed, she just shows up. πŸ’…

font_settings

@list = $pdf->font_settings()  # Get

$pdf->font_settings(%info)  # Set

Change one or more default settings. See PDF::Builder::FontManager/font_settings for details.

add_font_path

$rc = $pdf->add_font_path("a directory path", %opts)

Add a search path for Font Manager font entries. See PDF::Builder::FontManager/add_font_path for details.

add_font

$rc = $pdf->add_font(%info)

Add a font (face) definition to the Font Manager list. See PDF::Builder::FontManager/add_font for details.

get_font

@current = $pdf->get_font()  # Get

$font = $pdf->get_font(%info)  # Set

Retrieve a ready-to-use font, or find out what the current one is. See PDF::Builder::FontManager/get_font for details.

get_external_font

$rc = $pdf->get_external_font()

See if there is already a predefined (opened) font that the user wants to use. See PDF::Builder::FontManager/get_external_font for details.

dump_font_tables

$pdf->dump_font_tables()

Dump all known font information to STDOUT. See PDF::Builder::FontManager/dump_font_tables for details. Just... everything, straight to your terminal 🫠

✨ IMAGE METHODS ✨

bestie this is THE section, this is where we make pictures actually show up on the page πŸŽ€ importing images is lowkey the most fun part of the whole module and i'm obsessed


image

$object = $pdf->image($file, %opts);

okay so this one is the ✨convenience queen✨ β€” it sniffs out what kind of image you handed it, imports a file of that type, and hands you back an object you can drop right into a page's content πŸ¦‹

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

my $image = $pdf->image('/path/to/image.jpg');
$page->object($image, 100, 100);

$pdf->save('sample.pdf');

$file can be a file name, a filehandle, or a PDF::Builder::Resource::XObject::Image::GD object. flexible icon behavior fr πŸ’…

CAUTION, bestie, do NOT mix these up: this image (the $pdf-> one) is not the same as the image method living in the graphics (gfx) class ($gfx->), which is the one that actually places a read-in or decoded image onto the page! two different girls, two different jobs 😭

for the deets on putting images on a page after they've been imported, go peek at "image" in PDF::Builder::Content and "object" in PDF::Builder::Content.

so how does it know what format you've got? usually it just vibes off the file's extension β€” .gif, .png, .tif/.tiff, .jpg/.jpeg, .pnm/.pbm/.pgm/.ppm ✨ and if you hand it a filehandle instead, it'll detect GIF, JPEG, PNM, and PNG by reading the file's header. sadly though, at this time the other formats (TIFF and GD) cannot be auto-detected. (and like, TIFF kind of could be, except image_tiff() can't take a filehandle as input anyway when you're using the libtiff library β€” which is highly recommended, jsyk 🫢)

if your file has a weirdo extension, or your filehandle is holding a different kind of image than expected, just set the "format" option to one of the supported types: "gif", "jpeg", "png", "pnm", or "tiff". problem solved, no cap πŸ’–

Note: PNG images that include an alpha (transparency) channel go through a relatively slow process of splitting the image into separate RGB and alpha components, as is required by images in PDFs. if you're having performance issues, install Image::PNG::Libpng to speed up this process by an order of magnitude β€” either module will be used automatically if it's available. see the "image_png" method for details. 🧚
Note: TIFF image processing is very slow if you're using the pure Perl decoder. we highly recommend using the Graphics::TIFF library to improve performance. see the "image_tiff" method for details. πŸ”₯

image_jpeg

$jpeg = $pdf->image_jpeg($file, %opts)

imports and returns a shiny new JPEG image object πŸ’œ $file can be either a filename or a filehandle.

see PDF::Builder::Resource::XObject::Image::JPEG for extra info, and "examples/Content.pl" for some examples of placing an image on a page. 🌸


image_tiff

$tiff = $pdf->image_tiff($file, %opts)

imports and returns a brand new TIFF image object πŸ‘‘ $file can 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 extra info, and "examples/Content.pl" for some examples of placing an image on a page (those are JPEG, but the principle is the same bestie, don't stress). there's an optional TIFF library (TIFF_GT) described that gives you more capability than the default one. see the TIFF_GT documentation for further information on using this library β€” especially when you're passing a filehandle for the file. πŸ’…

LA_GT

$rc = $pdf->LA_GT()

returns 1 if the library name (package) Graphics::TIFF is installed, and 0 otherwise. since this library is optional, this call is how you find out if it's 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
}

image_pnm

$pnm = $pdf->image_pnm($file, %opts)

imports and returns a new PNM image object 🌈 $file can be either a filename or a filehandle.

see PDF::Builder::Resource::XObject::Image::PNM for extra info, and "examples/Content.pl" for some examples of placing an image on a page (JPEG again, but the principle is the same). πŸ¦‹


image_png

$png = $pdf->image_png($file, %opts)

imports and returns a new PNG image object ✨ $file can 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 extra info, and "examples/Content.pl" for some examples of placing an image on a page (yep, JPEG, same principle). πŸ’–

there's an optional PNG library (PNG_IPL) described that gives you more capability than the default one. see the PNG_IPL documentation for further information on using this library β€” particularly when passing a filehandle for the file. πŸŽ€

LA_IPL

$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 tells you if it's 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
}

image_gif

$gif = $pdf->image_gif($file, %opts)

imports and returns a new GIF image object 🌸 $file can be either a filename or a filehandle.

see PDF::Builder::Resource::XObject::Image::GIF for extra info, and "examples/Content.pl" for some examples of placing an image on a page (JPEG, but you already know the principle by now πŸ’…).


image_svg

$pnm = $pdf->image_svg($file, %opts)

imports and returns a new SVG image object 🧚 $file can be a filename, a string, or a filehandle.

see PDF::Builder::Resource::XObject::Image::SVG for extra info, and "examples/Content.pl" for some examples of placing an image on a page (JPEG, same principle). note that object() is preferably used rather than image(). if "image" determines that the image object is a processed SVG array, it simply passes it on to "object". πŸ’œ

CAUTIONS, bestie, read these fr fr: 1. if you're using image(), the final two (optional) parameters are not width and height β€” they're instead the horizontal scale and vertical scale. 2. results are unpredictable if you let the "x" and "y" positions default to the Lower Left corner at "(0,0)", because of the different scaling. it is best to explicitly give the "x" and "y" positions. 3. be aware that due to different scaling, some resulting images may be much larger than expected β€” account for this when setting any "scale" factor. 😭

LA_SVG

$rc = $pdf->LA_SVG()

returns 1 if the library name (package) SVGPDF is installed, and 0 otherwise. for this optional library, this call is how you check if it's safe to use certain functions. for example:

if ($pdf->LA_SVG() {
    # is installed and usable
} else {
    # not available. can't use image_svg or any other SVG function
}

image_gd

$gdf = $pdf->image_gd($gd_object, %opts)

imports and returns a new image object from Image::GD 🌟

see PDF::Builder::Resource::XObject::Image::GD for extra info, and "examples/Content.pl" for some examples of placing an image on a page (JPEG, but the principle is the same, you already knew that tho 🫢).

🎨 COLORSPACE METHODS 🎨

Bestie. This is the section where we stop playing and start controlling color like an absolute boss. πŸ’…


colorspace

$colorspace = $pdf->colorspace($type, @arguments)

So here's the tea: you can add colorspaces to a PDF for two reasons, and both are valid. β˜•

  • To specifically control the output color on a particular device β€” think spot colors, device colors.
  • To save space by limiting the available colors down to a defined palette β€” think web-safe palette, ACT file.

Once they've been added to the PDF, you can use them in place of regular hex codes or named colors. It's giving "leveled up". ✨

my $pdf = PDF::Builder->new();
my $page = $pdf->page();
my $content = $page->graphics();

# Add colorspaces for a spot color and the web-safe color palette
my $spot = $pdf->colorspace('spot', 'PANTONE Red 032 C', '#EF3340');
my $web = $pdf->colorspace('web');

# Fill using the spot color with 100% coverage
$content->fill_color($spot, 1.0);

# Stroke using the first color of the web-safe palette
$content->stroke_color($web, 0);

# Add a rectangle to the page
$content->rectangle(100, 100, 200, 200);
$content->paint();

$pdf->save('sample.pdf');

The following types of colorspaces are supported, and yes we're going through all of them πŸ‘‘

spot

Spot colors are the ones that tell a device β€” usually a printer πŸ–¨οΈ β€” to use or emulate a particular ink color ($tint) for parts of the document. So specific. So intentional.

An $alt_color is provided for devices (e.g. PDF viewers) that don't know how to produce the named color. It can either be an approximation of the color in RGB, CMYK, or HSV formats, or a wildly different color (e.g. 100% magenta, %0F00) to make it clear if the spot color isn't being used as expected. Honestly? Chaotic genius. πŸ’€

my $spot = $pdf->colorspace('spot', $tint, $alt_color);

web

The web-safe color palette is a historical collection of colors that was used when many display devices only supported 256 colors. Ancient lore, bestie. πŸ¦‹

my $web = $pdf->colorspace('web');

act

An Adobe Color Table (ACT) file provides a custom palette of colors that can be referenced by PDF graphics and text drawing commands. Your own palette, your own rules. πŸŽ€

my $act = $pdf->colorspace('act', $filename);

device

A device-specific colorspace allows for precise color output on a given device (typically a printing press), bypassing the normal color interpretation performed by raster image processors (RIPs). It's giving "we go straight to the source, no middleman". πŸ”₯

my $devicen = $pdf->colorspace('device', @colorspaces);

Device colorspaces are also needed if you want to blend spot colors. Yes, needed. Can't skip this step, bestie:

my $pdf = PDF::Builder->new();
my $page = $pdf->page();
my $content = $page->graphics();

# Create a two-color device colorspace
my $yellow = $pdf->colorspace('spot', 'Yellow', '%00F0');
my $spot = $pdf->colorspace('spot', 'PANTONE Red 032 C', '#EF3340');
my $device = $pdf->colorspace('device', $yellow, $spot);

# Fill using a blend of 25% yellow and 75% spot color
$content->fill_color($device, 0.25, 0.75);

# Stroke using 100% spot color
$content->stroke_color($device, 0, 1);

# Add a rectangle to the page
$content->rectangle(100, 100, 200, 200);
$content->paint();

$pdf->save('sample.pdf');

colorspace_act

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

colorspace_web

$cs = $pdf->colorspace_web()

Returns a new colorspace-object based on the "web-safe" color palette. Retro but make it useful. πŸ’–

colorspace_hue

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

colorspace_separation

$cs = $pdf->colorspace_separation($tint, $color)

Returns a new separation colorspace object based on the parameters you handed it. 🫢

$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. Automatic. Iconic. No notes. ✨

colorspace_devicen

$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. πŸ‘‘


πŸ“Š BARCODE METHODS πŸ“Š

These are glue routines to the actual barcode rendering routines found elsewhere. Glue routines! They hold it together, bestie. 🩹

xo_* Bar Code routines

$bc = $pdf->xo_codabar(%opts)

$bc = $pdf->xo_code128(%opts)

$bc = $pdf->xo_2of5int(%opts)

$bc = $pdf->xo_3of9(%opts)

$bc = $pdf->xo_ean13(%opts)

Creates the specified barcode object as a form XObject. Scan away, it's literally scannable. πŸ“ˆ


🌸 OTHER METHODS 🌸

xo_form

$xo = $pdf->xo_form()

Returns a new form XObject. Fresh out the box. πŸ“¦

egstate

$egs = $pdf->egstate()

Returns a new extended graphics state object, as described in PDF::Builder::Resource::ExtGState.

pattern

$obj = $pdf->pattern(%opts)

Returns a new pattern object. πŸŽ€

shading

$obj = $pdf->shading(%opts)

Returns a new shading object. Gradient hours. πŸŒ…

named_destination

$ndest = $pdf->named_destination($cat, $name, $obj)

Returns a new named destination object. $cat is the category, and is normally the string 'Dests' (it's a PDF keyword). The $name is the unique (within an entire PDF document) name, such as "foo" in the example below. Unique within the entire document β€” no duplicates, that's the rule. πŸ’…

See PDF::Builder::NamedDestination for more information.

Example:

my $dest = PDF::Builder::NamedDestination->new($pdf);
#$dest->goto($page, 'xyz' => [undef, undef, undef]);  old style
$dest->goto($page, 'xyz', (undef, undef, undef));
$pdf->named_destination('Dests', 'foo', $dest);

init_state()

Initialize 'state' variable that carries information across multiple document passes for column() call. See PDF::Builder::Content::Column_docs for documentation.

pass_start_state()

Update 'state' variable that carries information across multiple document passes for column() call, at the beginning of each pass. See PDF::Builder::Content::Column_docs for documentation. πŸ”


And that's a wrap on the whole PDF::Builder(3) page, bestie!! We did it. Every method, every signature, every single one. πŸ₯³

This masterpiece was generated by perl v5.42.0 and dated 2026-01-17 β€” the PDF::Builder(3) page, section 3 of your manual, living its best life. Go forth and build PDFs, you absolute legend. πŸ’–βœ¨πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from