PDF::Builder::Docs(3)

๐Ÿ’– PDF::Builder::Docs ๐Ÿ’–

okay bestie, welcome to the PDF::Builder::Docs(3) manpage โ€” it's the User Contributed Perl Documentation edition, and it's giving extra docs for the Builder module โœจ. no cap, this is where the real tea is.


๐Ÿ“› NAME ๐Ÿ“›

PDF::Builder::Docs โ€” Additional documentation for Builder module. like, the bonus lore, fr fr.


โœจ SOME SPECIAL NOTES โœจ

๐Ÿ› ๏ธ Software Development Kit ๐Ÿ› ๏ธ

so there are four levels of involvement with PDF::Builder. depending on what you wanna do, different kinds of installs are recommended. let's break it down, bestie:

  1. You're just installing PDF::Builder as a prerequisite for running some other package. all you gotta do is install the CPAN package for PDF::Builder, and it will load the .pm files into your Perl library. if the other package prereqs PDF::Builder, its installer may download and install PDF::Builder automatically. ๐Ÿซถ

lowkey important: PDF::Builder has a number of optional prerequisites. it will happily install and run without them, but advanced functionality (possibly including that needed by another package) will not be available unless you manually install the desired packages. see "Optional Libraries" or the README file for the list of optional packages. iykyk.

  1. You wanna write a Perl program that uses PDF::Builder functions. in addition to installing PDF::Builder from CPAN, you'll want documentation on it. obtain a copy of the product from GitHub (https://github.com/PhilterPaper/Perl-PDF-Builder) or as a gzipped tar file from CPAN. this includes a utility to build (from POD) a library of HTML documents, as well as examples (examples/ directory) and contributed sample programs (contrib/ directory). slay. ๐Ÿ’…
  2. You wanna modify PDF::Builder files. in addition to the CPAN and GitHub distributions, you may choose to keep a local Git repository for tracking your changes. depending on whether or not your PDF::Builder copy is being used for production purposes, you may want to do your editing and testing in the Perl library installation (live) or in a different place. the "t" tests (t/ directory) and examples provide good regression tests to ensure that you haven't broken anything. if you do your editing on the live code, don't forget when done to copy the changes back into the master version you keep! ๐Ÿ˜ญ
  3. You wanna contribute to the development of PDF::Builder. you will need a local Git repository (and a GitHub account), so that when you've got it all done, you can issue a "Pull Request" to bring it to our attention. we can't guarantee that your work will be incorporated into the project, but at least we will look at it. from time to time, a new CPAN version will be issued. ๐Ÿ‘‘

if you want to make substantial changes for public use, and can't come to a meeting of minds with us, you can even start your own GitHub project and register a new CPAN project (that's what we did, forking PDF::API2). please don't just assume that we don't want your changes โ€” at least propose what you want to do in writing, so we can consider it. we're always looking for people to help out and expand PDF::Builder. fr fr. ๐ŸŒˆ


๐Ÿ“ฆ Optional Libraries ๐Ÿ“ฆ

PDF::Builder can make use of some optional libraries, which are not required for a successful installation. if you want improved speed and capabilities for certain functions, you may want to install and use these libraries. PDF::Builder's README file lists the minimum versions needed, and INFO/Prereq_fixes lists known updates needed for some. bestie, here's the lineup:

  • Perl::Critic โ€” Needed if running tools/1_pc.pl to check the library content. like, the vibe check for your code.
  • Graphics::TIFF โ€” PDF::Builder inherited a rather slow, buggy, and limited TIFF image library from PDF::API2. if Graphics::TIFF (available on CPAN, uses libtiff.a) is installed, PDF::Builder will use that instead, unless you specify that it is to use the old, pure Perl library. the only time you might want to consider this is when you need to pass an open filehandle to image_tiff instead of a file name. see resolved bug reports RT 84665 and RT 118047, as well as image_tiff, for more information. no cap, the old one is giving struggle. ๐Ÿ’€
  • Image::PNG::Libpng โ€” PDF::Builder inherited a rather slow and buggy pure Perl PNG image library from PDF::API2. if Image::PNG::Libpng (available on CPAN, uses libpng.a) is installed, PDF::Builder will use that instead, unless you specify that it is to use the old, pure Perl library. using the new library will give you improved speed, the ability to use 16 bit samples, and the ability to read interlaced PNG files. see resolved bug report RT 124349, as well as image_png, for more information. glow up, fr. โœจ
  • HarfBuzz::Shaper โ€” This library enables PDF::Builder to handle complex scripts (Arabic, Devanagari, etc.) as well as non-LTR writing systems. it is also useful for Latin and other simple scripts, for ligatures and improved kerning. HarfBuzz::Shaper is based on a set of HarfBuzz libraries, which it will attempt to build if they are not found. see textHS for more information. iconic for multilingual besties. ๐ŸŒ
  • Text::Markdown โ€” This library is used if you want to format "Markdown" style code in PDF::Builder, via the column() method. it translates a certain dialect of Markdown into HTML, which is then further processed. main character energy for your docs.
  • HTML::TreeBuilder โ€” This library is used to format HTML input into a data structure which PDF::Builder can interpret, via the column() method. note that if Markdown input is used, it will also need HTML::TreeBuilder to handle the HTML the Markdown is translated to. the way that these two team up? obsessed. ๐Ÿซถ
  • Pod::Simple::XHTML โ€” This library is used if you wish to generate the HTML documentation from the POD and PM source, using docs/buildDoc.pl. note that the full set of documentation can also be found online at https://www.catskilltech.com/FreeSW/product/PDF-Builder/title/PDF%3A%3ABuilder/freeSW_full under the "Documentation" link. this online documentation is updated at every CPAN release, but not necessarily when the GitHub repository is updated. so like, don't @ me if it's stale. ๐Ÿ™ˆ
  • SVGPDF โ€” This library is used to convert SVG image files into PDF primitives, so SVG images may be included in a PDF. slay those vectors. ๐Ÿ’…

note that the installation process will not attempt to install these libraries automatically. if you don't wish to use one or more of them, you are free to not install the optional librarie(s). if you may want to make use of one or more, consider installing them before installing PDF::Builder, so that any t-tests and/or examples that make use of these libraries may be run during installation and checkout of PDF::Builder. remember, you can always install an optional library later, if you want to make use of it. no pressure, bestie. ๐ŸŽ€


๐Ÿ”ค Strings (Character Text) ๐Ÿ”ค

Perl, and hence PDF::Builder, use strings that support the full range of Unicode characters. when importing strings into a Perl program, for example by reading text from a file, you must be aware of what their character encoding is. single-byte encodings (default is 'latin1'), represented as bytes of value 0x00 through 0xFF (0..255), will produce different results if you do something that depends on the encoding, such as sorting, searching, or comparing any two non-ASCII characters. this also applies to any characters (text) hard coded into the Perl program. it's giving encoding chaos if you're not careful. ๐Ÿ˜ญ

you can always decode the text from external encoding (ASCII, UTF-8, Latin-3, etc.) into the Perl (internal) UTF-8 multibyte encoding. this uses one to four bytes to represent each character. see pragma utf8 and module Encode for details about decoding text. note that only TrueType fonts (ttfont) can make direct use of UTF-8-encoded text. other font types (core, T1, etc.) can only use single-byte encoded text. if your text is ASCII, Latin-1, or CP-1252, you can just leave the Perl strings as the default single-byte encoding. easy peasy. โœจ

then, there is the matter of encoding the output to match up with available font character sets. you're not actually translating the text on output, but are telling the output system (and Reader) what encoding the output byte stream represents, and what character glyphs they should generate. it's like, meta, but make it fonts. ๐Ÿ’…

if you confine your text to plain ASCII (0x00 .. 0x7F byte values) or even Latin-1 or CP-1252 (0x00 .. 0xFF byte values), you can use default (non-UTF-8) Perl strings and use the default output encoding (WinAnsiEncoding), which is more-or-less Windows CP-1252 (a superset in turn, of ISO-8859-1 Latin-1). if your text uses any other characters, you will need to be aware of what encoding your text strings are (in the Perl string and for declaring output glyph generation). see "Core Fonts", "PS Fonts" and "TrueType Fonts" in "FONT METHODS" for additional information. periodt.


๐Ÿช Supported Perl Versions ๐Ÿช

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. it's giving legacy support realness. ๐Ÿ‘‘

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. math is math. ๐Ÿงฎ

the intent is to avoid expending unnecessary effort in supporting very old (obsolete) versions of Perl. so like, we're not gonna waste energy on ancient vibes. ๐Ÿ’€

Anticipated Support Cutoff Dates

note that these are not hard and fast dates. in particular, we develop on Strawberry Perl, which sometimes falls a little behind the official Perl release! also, due to user requests to allow new releases of PDF::Builder to run on earlier versions of Perl, we will try to stretch the lifetime of earlier Perl versions. eventually, some older Perl versions will have to be dropped if and when we start making use of newer Perl operators and constructs. nevertheless, it is still not a good idea to continue to use very old Perl versions that are beyond their support cutoff dates โ€” they become vulnerable to security attacks, and bugs do not get fixed. so like, upgrade, bestie. ๐Ÿซถ

  • 5.28 current minimum supported version. out of support, so use at your own risk. โš ๏ธ
  • 5.30 future minimum supported version, until next PDF::Builder release after 20 June, 2026.
  • 5.32 future minimum supported version, until next PDF::Builder release after 20 May, 2027.
  • 5.34 not released under Strawberry Perl, expected to be skipped. ๐Ÿ™ˆ
  • 5.36 future minimum supported version, until next PDF::Builder release after 28 May, 2028. this is currently our primary development version. ๐Ÿ‘‘
  • 5.38 future minimum supported version, until next PDF::Builder release after 02 Jul, 2029.
  • 5.40 future minimum supported version, until next PDF::Builder release after 09 June, 2030. this is currently the maximum tested version. ๐ŸŒŸ
  • 5.42 future minimum supported version, until next PDF::Builder release after 03 July, 2031.

So if you're stuck running this module on a server with a truly fossilized Perl (no shade, legacy infra is real), bestie, you've got options: look into either plenv or Perlbrew to run a newer Perl without needing admin privileges. No root, no drama. ๐Ÿ’…

And honestly? Any feature in PDF::Builder should keep working unchanged for the life of most long-term-stable (LTS) server distros, whose lifetime is usually about six (6) years. To be clear: that is not a statement of warranty โ€” it just means we intend to try to keep any particular release of PDF::Builder working for a period of years. It helps a lot if you periodically update your Perl installation to something released in the recent past. ๐Ÿซถ


๐ŸŒธ Some Internal Details ๐ŸŒธ

Okay so some of the following may be a bit scary or confusing to beginners, so fr fr, don't be afraid to skip over it until you're ready for it... No gatekeeping here, come back when you're curious. โœจ

Perl (and PDF::Builder) internally use strings which are either single-byte (ISO-8859-1/Latin-1) or multibyte UTF-8 encoded โ€” there's an internal flag marking the string as UTF-8 or not. So if you work strictly in ASCII or Latin-1 or CP-1252 (each a superset of the previous one, cute little stack ๐Ÿฅž), you should be totally OK not doing anything special about your string encoding. Just vibe with the default Perl single byte strings (internally marked as not UTF-8) and the default output encoding (WinAnsiEncoding). Slay.

But โ€” if you're pulling input from a variety of sources, you should consider decoding (converting) your text to UTF-8, because that gives you an internally consistent representation (and your Perl code itself should be saved in UTF-8, in case you want any hard coded non-ASCII characters). In any string, non-ASCII characters (0x80 or higher) would be converted to the Perl UTF-8 internal representation, via $string = Encode::decode(MY_ENCODING, $input);. Here MY_ENCODING would be a string like 'latin1', 'cp-1252', 'utf8', etc. Similar capabilities are available for declaring a file to be in a certain encoding. ๐Ÿ‘‘

Heads up bestie: if you use UTF-8 encoding for your text, only TrueType font output (ttfont) can handle it directly. Corefont and Type1 output will require that the text be converted back into a single-byte encoding (using Encode::encode), which may need to be declared with encode (for corefont or psfont). And if you have any characters not found in the selected single-byte encoding (but which are found in the font itself), you'll need automap to break up the font glyphs into 256 character planes, map such characters to 0x00 .. 0xFF in the appropriate plane, and switch between font planes as necessary. ๐Ÿ˜ญ It's giving "why is encoding like this".

Core and Type1 fonts (output) use the byte values in the string (single-byte encoding only!) and provide a byte-to-glyph mapping record for each plane. TrueType outputs a group of four hexadecimal digits representing the CId (character ID) of each character. And no, the CId does not correspond to either the single-byte or UTF-8 internal representations of the characters. It's its own thing. ๐Ÿ’€

The bottom line, periodt: you need to know what the internal representation of your text is, so that the output routines can tell the PDF reader about it (via the PDF file). The text will not be translated upon output โ€” but the PDF reader needs to know what encoding is in use, so it knows what glyph to associate with each byte (or byte sequence). ๐Ÿฆ‹

Also, some operating systems and Perl flavors are reputed to be strict about encoding names. For example, latin1 (an alias) may be rejected as invalid, while iso-8859-1 (a canonical value) will work. Rude, but okay. ๐Ÿ™ˆ

By the way, it's recommended that you be using at least Perl 5.10 if you're going to be using any non-ASCII characters. Perl 5.8 may be a little unpredictable in handling such text. Just saying. โœจ


๐ŸŽจ Rendering Order ๐ŸŽจ

For better or worse, for compatibility purposes, PDF::Builder continues the same rendering model as used by PDF::API2 (and possibly its predecessors). Here's the tea: all graphics for one graphics object go into one record, and all text output for one text object goes into another record. Which one gets output first is whichever is declared first.

Which can lead to unexpected results, where items are rendered in (apparently) the wrong order. ๐Ÿ˜ญ Like, text and graphics items are not necessarily output (rendered) in the same order as they were created in code. Two items in the same object (e.g., $text) will be rendered in the same order as they were coded โ€” but items from different objects may not be rendered in the expected order.

The following example (source code and annotated PDF excerpts) will hopefully illustrate the issue, bestie. Let's look:

use strict;
use warnings;
use PDF::Builder;

# demonstrate text and graphics object order
#
my $fname = "objorder";

my $paper_size = "Letter";

# see the text and graphics stream contents
my $pdf = PDF::Builder->new(compress => 'none');
$pdf->mediabox($paper_size);
my $page = $pdf->page();
# adjust path for your operating system
my $fontTR = $pdf->ttfont('C:\\Windows\\Fonts\\timesbd.ttf');
   # or 'C:/Windows/Fonts/timesbd.ttf' will also work on Windows

For this first group, you might expect the "under" line to be output, then the filled circle (disc) partly covering it, then the "over" line covering the disc, and finally a filled rectangle (bar) over both lines. ๐Ÿ™ƒ

What actually happened is that the $grfx graphics object was declared first, so everything in that object (the disc and bar) is output first, and the text object $text (both lines) comes afterwards. Result: the text lines are on top of the graphics drawings. Not the plot twist anyone asked for. ๐Ÿ’€

# ----------------------------
# 1. text, orange ball over, text over, bar over

my $grfx1 = $page->gfx();
my $text1 = $page->text();
$text1->font($fontTR, 20);  # 20 pt Times Roman bold

$text1->fillcolor('black');
$grfx1->strokecolor('blue');
$grfx1->fillcolor('orange');

$text1->translate(50,700);
$text1->text_left("This text should be under everything.");

$grfx1->circle(100,690, 30);
$grfx1->fillstroke();

$text1->translate(50,670);
$text1->text_left("This text should be over the ball and under the bar.");

$grfx1->rect(160,660, 20,70);
$grfx1->fillstroke();

% ---------------- group 1: define graphics object first, then text
11 0 obj << /Length 690 >> stream   % obj 11 is graphics for (1)
 0 0 1 RG    % stroke blue
1 0.647059 0 rg   % fill orange
130 690 m ... c h B   % draw and fill circle
160 660 20 70 re B   % draw and fill bar
endstream endobj

12 0 obj << /Length 438 >> stream   % obj 12 is text for (1)
  BT
/TiCBA 20 Tf   % Times Roman Bold 20pt
0 0 0 rg   % fill black
1 0 0 1 50 700 Tm   % position text
<0037 ... 0011> Tj   % "under" line
1 0 0 1 50 670 Tm   % position text
<0037 ... 0011> Tj   % "over" line
  ET
endstream endobj

The second group is the same as the first, with the only difference being that the text object was declared first, and then the graphics object. The result: the two text lines are rendered first, and then the disc and bar are drawn over them. Order really said "main character energy only for whoever goes first". ๐Ÿ‘‘

# ----------------------------
# 2. (1) again, with graphics and text order reversed

my $text2 = $page->text();
my $grfx2 = $page->gfx();
$text2->font($fontTR, 20);  # 20 pt Times Roman bold

$text2->fillcolor('black');
$grfx2->strokecolor('blue');
$grfx2->fillcolor('orange');

$text2->translate(50,600);
$text2->text_left("This text should be under everything.");

$grfx2->circle(100,590, 30);
$grfx2->fillstroke();

$text2->translate(50,570);
$text2->text_left("This text should be over the ball and under the bar.");

$grfx2->rect(160,560, 20,70);
$grfx2->fillstroke();

% ---------------- group 2: define text object first, then graphics
13 0 obj << /Length 438 >> stream    % obj 13 is text for (2)
  BT
/TiCBA 20 Tf   % Times Roman Bold 20pt
0 0 0 rg   % fill black
1 0 0 1 50 600 Tm   % position text
<0037 ... 0011> Tj   % "under" line
1 0 0 1 50 570 Tm   % position text
<0037 ... 0011> Tj   % "over" line
  ET
endstream endobj

14 0 obj << /Length 690 >> stream   % obj 14 is graphics for (2)
 0 0 1 RG   % stroke blue
1 0.647059 0 rg   % fill orange
130 590 m ... h B   % draw and fill circle
160 560 20 70 re B   % draw and fill bar
endstream endobj

The third group defines two text and two graphics objects, in the order that they are expected in. So: the "under" text line is output first, then the orange disc graphics is output, partly covering the text. Then the "over" text line is now output โ€” it's actually over the disc, but it's orange ๐Ÿ˜ญ because the previous object stream (the first graphics object) left the fill color (also used for text) as orange, since we didn't explicitly set the fill color before outputting the second text line.

And this is not "inheritance" so much as it is: whatever the graphics (drawing) state (used for both "graphics" and "text") is left in at the end of one object, that's the state at the beginning of the next object. ๐Ÿซ  If you wish to control this, consider surrounding the graphics or text calls with save() and restore() calls to save and restore (push and pop) the graphics state to what it was at the save(). Finally, the bar is drawn over everything. โœจ

# ----------------------------
# 3. (2) again, with two graphics and two text objects

my $text3 = $page->text();
my $grfx3 = $page->gfx();
$text3->font($fontTR, 20);  # 20 pt Times Roman bold
my $text4 = $page->text();
my $grfx4 = $page->gfx();
$text4->font($fontTR, 20);  # 20 pt Times Roman bold

$text3->fillcolor('black');
$grfx3->strokecolor('blue');
$grfx3->fillcolor('orange');
# $text4->fillcolor('yellow');
# $grfx4->strokecolor('red');
# $grfx4->fillcolor('purple');

$text3->translate(50,500);
$text3->text_left("This text should be under everything.");

$grfx3->circle(100,490, 30);
$grfx3->fillstroke();

$text4->translate(50,470);
$text4->text_left("This text should be over the ball and under the bar.");

$grfx4->rect(160,460, 20,70);
$grfx4->fillstroke();

% ---------------- group 3: define text1, graphics1, text2, graphics2
15 0 obj << /Length 206 >> stream   % obj 15 is text1 for (3)
  BT
/TiCBA 20 Tf   % Times Roman Bold 20pt
0 0 0 rg  % fill black
1 0 0 1 50 500 Tm   % position text
<0037 ... 0011> Tj   % "under" line
  ET
endstream endobj

16 0 obj << /Length 671 >> stream   % obj 16 is graphics1 for (3) circle
 0 0 1 RG   % stroke blue
1 0.647059 0 rg   % fill orange
130 490 m ... h B   % draw and fill circle
endstream endobj
        17 0 obj << /Length 257 >> stream   % obj 17 is text2 for (3)
          BT
        /TiCBA 20 Tf   % Times Roman Bold 20pt
        1 0 0 1 50 470 Tm   % position text
        <0037 ... 0011> Tj   % "over" line
          ET
        endstream endobj

        18 0 obj << /Length 20 >> stream   % obj 18 is graphics for (3) bar
         160 460 20 70 re B   % draw and fill bar
        endstream endobj

Group four is literally group three's twin ๐Ÿซถ except we also set the fill color for the text in that second line. And the way that makes it SO obvious that the "over" line (yellow bestie ๐Ÿ’›) got written after the orange disc, and still before the bar. Order really said "I'm the main character" and meant it.

        # ----------------------------
        # 4. (3) again, a new set of colors for second group

        my $text3 = $page->text();
        my $grfx3 = $page->gfx();
        $text3->font($fontTR, 20);  # 20 pt Times Roman bold
        my $text4 = $page->text();
        my $grfx4 = $page->gfx();
        $text4->font($fontTR, 20);  # 20 pt Times Roman bold

        $text3->fillcolor('black');
        $grfx3->strokecolor('blue');
        $grfx3->fillcolor('orange');
        $text4->fillcolor('yellow');
        $grfx4->strokecolor('red');
        $grfx4->fillcolor('purple');

        $text3->translate(50,400);
        $text3->text_left("This text should be under everything.");

        $grfx3->circle(100,390, 30);
        $grfx3->fillstroke();

        $text4->translate(50,370);
        $text4->text_left("This text should be over the ball and under the bar.");

        $grfx4->rect(160,360, 20,70);
        $grfx4->fillstroke();

        % ---------------- group 4: define text1, graphics1, text2, graphics2 with colors for 2
        19 0 obj << /Length 206 >> stream   % obj 19 is text1 for (4)
          BT
        /TiCBA 20 Tf   % Times Roman Bold 20pt
        0 0 0 rg  % fill black
        1 0 0 1 50 400 Tm   % position text
        <0037 ... 0011> Tj   % "under" line
          ET
        endstream endobj

        20 0 obj << /Length 671 >> stream   % obj 20 is graphics1 for (4) circle
         0 0 1 RG   % stroke blue
        1 0.647059 0 rg   % fill orange
        130 390 m ... h B   % draw and fill circle
        endstream endobj

        21 0 obj << /Length 266 >> stream   % obj 21 is text2 for (4)
          BT
        /TiCBA 20 Tf   % Times Roman Bold 20pt
        1 1 0 rg   % fill yellow
        1 0 0 1 50 370 Tm   % position text
        <0037 ... 0011> Tj   % "over" line
          ET
        endstream endobj

        22 0 obj << /Length 52 >> stream   % obj 22 is graphics for (4) bar
         1 0 0 RG   % stroke red
        0.498039 0 0.498039 rg   % fill purple
        160 360 20 70 re B   % draw and fill rectangle (bar)
        endstream endobj

        # ----------------------------
        $pdf->saveas("$fname.pdf");

So here's the tea โ˜• on why text and graphics are split like this: because of the split, only some text methods exist on a graphics object, and only some graphics methods exist on a text object. There's a LOT of overlap ngl, but they're not the same, periodt. Honestly there's no real reason the code couldn't have been written (in PDF::API2, or earlier) as outputting to one single object, which would keep everything in exactly the same order as the method calls. The glow-up there? Less object and stream overhead in the PDF file ๐Ÿ”ฅ. The only downside is that an object might overflow more easily and need splitting into multiple objects โ€” but fr fr, that should be rare.

You should always be able to manually split an object by just ending output to the first object and picking up with output to the second one, as long as it was created immediately after the first. The graphics state at the end of object one should be the initial state at the start of object two. BUT โ€” caution time, bestie ๐Ÿ™ˆ โ€” with text objects the PDF spec says the Text matrices are not carried over from one object to the next (BT resets them), so you might need to reset some settings yourself.

        $grfx1 = $page->gfx();
        $grfx2 = $page->gfx();
        # write a huge amount of stuff to $grfx1
        # write a huge amount of stuff to $grfx2, picking up where $grfx1 left off

๐ŸŒˆ Rendering with a shared (mixed) object ๐ŸŒˆ

Okay so now that you get the rendering order and how the order of object declarations affects it, you can fully control how text and graphics get drawn, however you want. Chef's kiss ๐Ÿ‘‘. There's genuinely no need to add another "both" type object that handles all graphics and text objects โ€” that would probably be a major code bloat for very little benefit. That said, it could be considered in the future if there's a demonstrated need, like serious PDF file size bloat from the extra object overhead when you're interleaving text and graphics output.

Right now there's no general facility for mixed-use objects, but there IS a limited example: the current implementation of underline, line-through, and overline text (within column() markup). Those get done <em>inside</em> the text object by temporarily exiting (ET) to graphics mode to draw the lines, then hopping back (BT) to text mode ๐Ÿฆ‹. Why? So baseline coordinate adjustments could be made easily. And since BT resets some text settings, you have to do this with care!

A bunch of PDF-producing products out there mix their text and graphics into a single object. As long as PDF::Builder isn't expecting to pick apart a "text" or "graphics" stream from an existing PDF file in order to look inside it, this shouldn't cause any problems. HOWEVER โ€” if you add a new text-only or graphics-only object to an existing PDF via PDF::Builder, you need to be aware of the rendering order. Presumably the new object(s) come after the original one, but like, know what's going on. A text, graphics, or mixed object is all the same to a PDF reader โ€” it only cares about who has the lower object number (to be rendered first). It's giving "first come, first drawn" ๐Ÿ’….

๐Ÿ’€ Graphics state left by existing PDFs ๐Ÿ’€

There was a problem reported recently (ticket 231) that suggested the expected rendering order of output wasn't being respected. Plot twist: what it actually was โ€” a utility ("Canva") used to generate a template PDF was writing graphics commands to a single stream (a mixed graphics and text stream, rather than separate streams, but that's not important here). And apparently it was leaving the PDF it created with a graphics state of transparent "fill" mode ๐Ÿ˜ญ. So any further text (plus filled graphics draws) added by the user in PDF::Builder (open PDF, open_page, add graphics and text in new streams) was still being drawn, but got rendered invisible! Remember, text is by default (render mode 0) drawn only with fill, not outlined. The fix was to first use the egstate() call to set transparency back to 0 (off), making "fill" opaque again โœจ. See examples/060_transparency for a code sample, or ticket 231.

๐ŸŽ€ Notes on Reader support of features ๐ŸŽ€

PDF Readers are complex pieces of software, written by different groups at different times. So yeah, they differ in how they support features and handle non-standard (i.e., not quite meeting standards) content ๐Ÿ™ƒ! Most Readers out there support all or most features up through PDF 1.7, and some support PDF 2.x features. Note that PDF::Builder supports PDF 1.4 for the most part, with a few PDF 1.5 features added. Most any Reader out there should (in theory) support any PDF produced with PDF::Builder.

There's no official reference implementation of a Reader, although Adobe's Acrobat Reader (AAR, a free download) is so prevalent that it's almost a de facto standard. At least, we try to get PDF::Builder and its tests and examples to run on AAR. Sometimes it's hard, like, for example, the handling of save (q) and restore (Q) operators (commands) within a text stream. The PDF standard sort of suggests these apply only to the Graphics Stream, and possibly shouldn't appear in a Text Stream. Most Readers appear to just ignore q and Q within a text stream, and AAR usually seems to too, but certain combinations of stream size and compression seem to trigger a warning in AAR upon load! This particular case is now a moot point, since save() and restore() have been reverted to being no-ops (with a single warning message given if found) in a Text Stream.

We've been advised that certain stream operators may not be strictly allowed within certain parts of a stream (particularly certain graphics state operators after path construction has started). No Reader seems to give problems with this right now, but users should be aware that the ordering of their PDF::Builder calls may need to be updated at some point, so the PDFs work on all Readers. If necessary, we'll add code to enforce this (or at least warn of potential problems). Please feel free to report if you find such restrictions are necessary ๐Ÿซถ.

Also note that not all filters (including compression methods) may be supported on all Readers. For example, at this time, AAR (and a number of other Readers) apparently do not support CCITT Group 4 Fax compression (for some TIFF images). This remains under investigation ๐Ÿ”.

โญ PDF Versions Supported โญ

When you create a PDF file using the functions in PDF::Builder, the output is marked as PDF 1.4. That does NOT mean all PDF functionality up through 1.4 is supported! There are almost surely features missing as far back as the PDF 1.0 standard ๐Ÿ˜ญ.

The big problem is when a PDF of version 1.5 or higher gets imported or opened in PDF::Builder. If it contains content that's actually unsupported by this software, there's a chance something will break ๐Ÿ’€. This doesn't guarantee that a PDF marked as "1.7" will go down in flames when read by PDF::Builder, or that a PDF written back out will break in a Reader โ€” but the possibility is there. Much PDF writer software simply marks its output as the highest version of PDF at the time (usually 1.7), even if there's no content beyond, say, 1.2. There is some handling of PDF 1.5 items in PDF::Builder, such as cross reference streams, but support beyond 1.4 is very limited. All we can say is: be careful when handling PDFs whose version is above 1.4, and test thoroughly, because they may break at some point.

PDF::Builder includes a simple version control mechanism, where the initial PDF version to be output (default 1.4) can be set by the programmer โœจ. Input PDFs greater than 1.4 (current output level) will receive a warning (can be suppressed) that the output level will be raised to that level. The use of PDF features greater than the current output level will likewise trigger a warning that the output level is to be raised to the necessary level. If that's not what you want, you should avoid using those PDF features which are higher than the desired PDF output level. Vibe check your version numbers, bestie ๐Ÿ’….

History ๐Ÿซถ

So like, PDF::API2 was originally written by Alfred Reibenschuh, derived from Martin Hosken's Text::PDF via the Text::PDF::API wrapper. Then in 2009, Otto Hirr started the PDF::API3 fork, but it literally never went anywhere ๐Ÿ’€. In 2011, PDF::API2 maintenance was taken over by Steve Simms. In 2017, PDF::Builder was forked by Phil M. Perry, who wanted a more aggressive schedule of new features and bug fixes than Simms was providing โ€” although some of Simms's work has been ported from PDF::API2. No cap.

According to Alfred Reibenschuh's 2005 presentation <yellow>pdfapi2_for_fun_and_profit_APW2005.pdf</yellow> (on http://pdfapi2.sourceforge.net, an unmaintained site), the history of PDF::API2 (the predecessor to PDF::Builder) goes as such:

  • First Code implemented based on PDFlib-0.6 (AFPL)
  • Changed to Text::PDF with a total rewrite as Text::PDF::API (procedural)
  • Unmaintainable Code triggered rewrite into new Namespace PDF::API2 (object-oriented, LGPL)
  • Object-Structure streamlined in 0.4x

At Simms's request, the name of the new offering was changed from PDF::API4 to PDF::Builder, to reduce the chance of confusion due to parallel development. Perry's intent is to keep all internal methods as upwardly compatible with PDF::API2 as possible, although it is likely that there will be some drift (incompatibilities) over time. At least initially, any program written based on PDF::API2 should be convertible to PDF::Builder simply by changing "API2" anywhere it occurs to "Builder". See the INFO/KNOWN_INCOMP known incompatibilities file for further information.

Thanks... ๐Ÿ’–

Many users have helped out by reporting bugs and requesting enhancements. A special shout out goes to those who have contributed code and tests, or coordinated their package development with the needs of PDF::Builder: Ben Bullock, Cary Gravel, Gregor Herrmann, Petr Pisar, Jeffrey Ratcliffe, Steve Simms (via PDF::API2 fixes), and Johan Vromans. Drop me a line if I've overlooked your contribution! ๐Ÿฅบ


DETAILED NOTES ON METHODS ๐Ÿง โœจ

Note: older versions of this package named various (hash element) options with leading dashes (hyphens) in the name, e.g., '-encode'. The use of a dash is now optional, and options are documented with names not using dashes. While the use of dashed option names is deprecated and discouraged, they will remain legal for some time to come. At some point in the future, it is possible that support for dashed names will be withdrawn, so it would be good practice to start using undashed names in new and revised code.

After saving a file... ๐Ÿ›‘

Note that a PDF object such as $pdf cannot continue to be used after saving an output PDF file or string with $pdf->save(), saveas(), or stringify(). There is some cleanup and other operations done internally which make the object unusable for further operations. You will likely receive an error message about can't call method new_obj on an undefined value if you try to keep using a PDF object.

IntegrityCheck ๐Ÿ”

The PDF::Builder methods that open an existing PDF file, pass it by the integrity checker method, "$self->IntegrityCheck(level, content)". This method serves two purposes: 1) to find any "/Version" settings that override the PDF version found in the PDF heading, and 2) perform some basic validations on the contents of the PDF.

The "level" parameter accepts the following values:

  • 0 โ€” Do not output any diagnostic messages; just return any version override.
  • 1 โ€” Output error-level (serious) diagnostic messages, as well as returning any version override.

Errors include, in no place was the /Root object specified, or if it was, the indicated object was not found. An object claims another object as its child (/Kids list), but another object has already claimed that child. An object claims a child, but that child does not list a Parent, or the child lists a different Parent.

  • 2 โ€” Output error- (serious) and warning- (less serious) level diagnostic messages, as well as returning any version override. This is the default.
  • 3 โ€” Output error- (serious), warning- (less serious), and note- (informational) level diagnostic messages, as well as returning any version override.

Notes include, in no place was the (optional) /Info object specified, or if it was, the indicated object was not found. An object was referenced, but no entry for it was found among the objects. (This may be OK if the object is not defined, or is on the free list, as the reference will then be ignored.) An object is defined, but it appears that no other object is referencing it.

  • 4 โ€” Output error-, warning-, and note-level diagnostic messages, as well as returning any version override. Also dump the diagnostic data structure.
  • 5 โ€” Output error-, warning-, and note-level diagnostic messages, as well as returning any version override. Also dump the diagnostic data structure and the $self data structure (generally useful only if you have already read in the PDF file).

The version is a string (e.g., '1.5') if found, otherwise "undef" (undefined value) is returned.

For controlling the "automatic" call to IntegrityCheck (via opens), the level may be given with the option (flag) "diaglevel => n", where "n" is between 0 and 5.

Preferences - set user display preferences ๐ŸŽ€

$pdf->preferences(%options)

Controls viewing preferences for the PDF.

Page Mode Options ๐ŸŒธ

  • fullscreen โ€” Full-screen mode, with no menu bar, window controls, or any other window visible.
  • thumbs โ€” Thumbnail images visible.
  • outlines โ€” Document outline visible.

Page Layout Options ๐Ÿฆ‹

  • singlepage โ€” Display one page at a time.
  • onecolumn โ€” Display the pages in one column.
  • twocolumnleft โ€” Display the pages in two columns, with odd-numbered pages on the left.
  • twocolumnright โ€” Display the pages in two columns, with odd-numbered pages on the right.

Viewer Options ๐Ÿ‘‘

  • hidetoolbar โ€” Specifying whether to hide tool bars.
  • hidemenubar โ€” Specifying whether to hide menu bars.
  • hidewindowui โ€” Specifying whether to hide user interface elements.
  • fitwindow โ€” Specifying whether to resize the document's window to the size of the displayed page.
  • centerwindow โ€” Specifying whether to position the document's window in the center of the screen.
  • displaytitle โ€” Specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary.
  • afterfullscreenthumbs โ€” Thumbnail images visible after Full-screen mode.
  • afterfullscreenoutlines โ€” Document outline visible after Full-screen mode.
  • printscalingnone โ€” Set the default print setting for page scaling to none.
  • simplex โ€” Print single-sided by default.
  • duplexflipshortedge โ€” Print duplex by default and flip on the short edge of the sheet.
  • duplexfliplongedge โ€” Print duplex by default and flip on the long edge of the sheet.

Page Fit Options ๐Ÿ”โœจ

These options are used for the "firstpage" layout, as well as for Annotations, Named Destinations and Outlines. For Annotations and Named Destinations, the first form given is for the fit as a hash element (option), while the second is as given as a list (before any options).

  • 'fit' => 1, 'fit' โ€” 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. Bottom line: the entire page is shown, as large as possible.
  • 'fith' => $top, 'fith', $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. Bottom line: like 'fit', but scrolled vertically to put desired y coordinate at the very top edge.
  • 'fitv' => $left, 'fitv', $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. Bottom line: like 'fit', but scrolled horizontally to put desired x coordinate at the very left edge.
  • 'fitr' => [ $left, $bottom, $right, $top ], 'fitr', $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. Bottom line: defines a viewport into the page by giving its corners. Cf. 'xyz', but all 4 corners of the viewport rectangle are given.
  • 'fitb' => 1, 'fitb' โ€” 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. Similar to 'fit'.
  • 'fitbh' => $top, 'fitbh', $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. Like 'fitb', but scrolled vertically so that $top is at the top edge of the display.
  • 'fitbv' => $left, 'fitbv', $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. Like 'fitb', but scrolled horizontally so that $left is at the left edge of the display.
  • 'xyz' => [ $left, $top, $zoom ] / 'xyz', $left, $top, $zoom โ€” show the page in $page, put the coords [$left, $top] at the top-left corner of the viewport, and blow the page content up by $zoom. And here's the cute part: if any of $left, $top, or $zoom is undef, that parameter just keeps its current value โ€” no reset, no drama. So if you're already vibing at a certain spot and zoom level, your next page lands at the same x,y and the same zoom when all three are undef. Cf. 'fitr', but that one gives you both corners; this one gives you just one corner plus the magnification. ๐Ÿ’…

โœจ Initial Page Options โœจ

  • firstpage => [ $page, %options ] โ€” tells the reader which page to open on. You pass the page (either a page number or a page object), plus one of the location options listed up above in "Page Fit Options". Pick one, bestie, not all of them. ๐ŸŽ€

๐Ÿ’– Example ๐Ÿ’–

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

๐ŸŒธ info Example ๐ŸŒธ

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

๐Ÿฆ‹ XMP XML example ๐Ÿฆ‹

$xml = $pdf->xmpMetadata();
print "PDFs Metadata reads: $xml\n";
$xml=<<EOT;
<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>
<?adobe-xap-filters esc="CRLF"?>
<x:xmpmeta
  xmlns:x='adobe:ns:meta/'
  x:xmptk='XMP toolkit 2.9.1-14, framework 1.6'>
    <rdf:RDF
      xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
      xmlns:iX='http://ns.adobe.com/iX/1.0/'>
        <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'></rdf:Description>
        <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'></rdf:Description>
        <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'/></rdf:Description>
        <rdf:Description
          rdf:about='uuid:b8659d3a-369e-11d9-b951-000393c97fd8'
          xmlns:dc='http://purl.org/dc/elements/1.1/'
          dc:format='application/pdf'>
            <dc:description>
              <rdf:Alt>
                <rdf:li xml:lang='x-default'>Adobe Portable Document Format (PDF)</rdf:li>
              </rdf:Alt>
            </dc:description>
            <dc:creator>
              <rdf:Seq>
                <rdf:li>Adobe Systems Incorporated</rdf:li>
              </rdf:Seq>
            </dc:creator>
            <dc:title>
              <rdf:Alt>
                <rdf:li xml:lang='x-default'>PDF Reference, version 1.6</rdf:li>
              </rdf:Alt>
            </dc:title>
        </rdf:Description>
    </rdf:RDF>
</x:xmpmeta>
<?xpacket end='w'?>
EOT

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

๐Ÿ’… "BOX" METHODS ๐Ÿ’…

okay so general note first, bestie, and it's an important one: be careful if you set a page-level Media Box (or any other "box") that's different from the global box setting. Like, define the whole chain of boxes on the page, or you're gonna get surprises. Example of the chaos: you set a global Media Box (paper size) and a global Crop Box, and then you set a new page-level Media Box but don't set a new page-level Crop Box โ€” the cropping that comes out of that may be straight up odd. Those combos are not well defined. You have been warned. ๐Ÿซถ

All dimensions in boxes default to the default User Unit, which is points (1/72 inch). Heads up though: the PDF spec caps sizes and coordinates at 14400 User Units (that's 200 inches, given the default User Unit of one point), and Adobe products (so far) follow that limit for Acrobat and Distiller. Worth knowing: other PDF writers and readers may just ignore the 14400 unit limit, with or without a specified User Unit. So PDF::Builder does not enforce any limits on coordinates โ€” it's your responsibility to think about what readers and other PDF tools might be used with the PDF you produce! ๐Ÿ‘‘ Also, earlier Acrobat readers had coordinate limits as small as 3240 User Units (45 inches), and a minimum media size of 72 or 3 User Units.


๐Ÿงš User Units (userunit) ๐Ÿงš

$pdf->userunit($number)

The default User Unit in the PDF coordinate system is one point (1/72 inch). Think of it like a scale factor that lets you make bigger documents (or even smaller ones, no judgement). This method can be used (for PDF 1.6 and higher) to set the User Unit to some number of points. For example, userunit(72) sets the scale multiplier to 72.0 points per User Unit, which is 1 inch per User Unit. Any number greater than zero is acceptable, though some readers and tools may not handle User Units of less than 1.0 very well. ๐Ÿ˜ฌ

Not every reader respects the User Unit when you give one, or handles it the exact same way. Adobe Distiller, for one, does not use it. How User Units get handled may vary from reader to reader. Adobe Acrobat, at this writing, respects User Unit in version 7.0 and up, but limits it to 75000 (which gives a maximum document size of 15 million inches, or 236.7 miles, or 381 km). Other readers and PDF tools may allow a larger (or smaller) limit.

Your Mileage May Vary: some readers ignore a global User Unit setting and don't have pages inherit it (PDF::Builder duplicates it on each page to simulate inheritance). Some readers may throw spurious warnings about truncated content when a Media Box is changed while User Units are in use. Some readers do strange things with Crop Boxes when a User Unit is in effect. ๐Ÿ’€

Depending on which reader you're on, the effect of a larger User Unit (greater than 1) may mean lower resolution (chunkier or coarser appearance) in the rendered document. If you're printing something the size of a highway billboard, this may not matter to you, but you should be aware of the possibility (even with fractional coordinates). Conversely, a User Unit of less than 1.0 (if permitted) reduces the allowable size of your document, but may result in greater resolution.

A global (PDF level) User Unit setting is inherited by each page (that's an action by PDF::Builder, not necessarily something the reader does automatically), or it can be overridden by calling userunit in the page. Do not give more than one global userunit setting, because only the last one will be used. Setting a page's User Unit (if $page-> instead) is permitted, overriding the global setting for that page. But many sources recommend against doing this, since results may not be as expected (once again, depending on the quirks of the reader). ๐Ÿ™ˆ

Remember to call userunit before calling anything having to do with page or box sizes, or coordinates. Especially when you're setting 'named' box sizes, the methods need to know the current User Unit so that named page sizes (in points) can be scaled down to the current User Unit. โญ


๐ŸŽ€ Media Box (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 the global Media Box (or the page's Media Box, if $page-> instead). This defines the width and height of the output page itself โ€” the actual physical paper size โ€” either by corner coordinates, or by a standard name. This is normally the largest of the "boxes". If any subsidiary box (one inside it) exceeds the media box, the portion of the material or boxes outside of the Media Box gets ignored. Basically, the Media Box is The One Box to Rule Them All, and it's the overall limit for the other boxes (some docs refer to the Media Box as "clipping" other boxes). On top of that, the Media Box defines the overall coordinate system for text and graphics operations. ๐Ÿ‘‘

If you give no arguments, you get the current Media Box (global or page) coordinates returned instead. The former get_mediabox (page only) function was deprecated and has been removed. Also, when you set the Media Box, the resulting coordinates get returned. That means you can specify the page size by a name (alias) and get the dimensions back, all in one call. Obsessed. โœจ

Note that many printers can't print all the way to the physical edge of the paper, so plan to leave some blank margin, even outside of any crop marks and bleeds. Printers and on-screen readers are free to discard any content found outside the Media Box, and printers may discard some material just inside the Media Box too. ๐Ÿ˜ญ

A global Media Box is required by the PDF spec. If you don't explicitly give one, PDF::Builder will set the global Media Box to US Letter size (8.5in x 11in). That's the media size used for all pages if you don't specify a mediabox call on a page. In other words, a global (PDF level) mediabox setting is inherited by each page, or can be overridden by setting mediabox in the page. Do not give more than one global mediabox setting, because only the last one will be used. ๐Ÿ’–

okay so continuing from where we were ๐Ÿ’– โ€” if you hand it a single string name (like 'A4'), you can optionally tack on an orientation to spin the page 90 degrees into Landscape mode: "orient => 'L'" or "orient => 'l'". and bestie, orient is the only option it recognizes, and a string that starts with an 'L' or 'l' (for Landscape) is the only value that does anything โ€” literally anything else gets treated as Portrait mode, no cap. The y axis still runs from 0 at the bottom of the page up to what used to be the page width (which is now, surprise, the height) at the top, and same energy for the x axis: 0 at left to the (former) height at the right. So basically the coordinate system is identical to before, except the height and width have swapped. it's giving "same vibe, different dimensions" โœจ

And listen โ€” the lower left corner does not have to be 0,0. It can be literally any values you want, even negative ones (as long as the resulting media's sides are at least one point long, bestie, we need some page there). mediabox sets the coordinate system (origin included) of the graphics and text that'll get drawn, plus all the subsequent "boxes". You can even hand it any two opposite corners (like upper left and lower right, go off ๐Ÿ‘‘). The coordinate system gets rearranged (by the Reader) so it still lands on the conventional minimum x and y in the lower left โ€” i.e., you can't make y increase from top to bottom, sorry not sorry!

Example time, my love:

$pdf = PDF::Builder->new();
$pdf->mediabox('A4'); # A4 size (595 Pt wide by 842 Pt high)
...
$pdf->saveas('our/new.pdf');

$pdf = PDF::Builder->new();
$pdf->mediabox(595, 842); # A4 size, with implicit 0,0 LL corner
...
$pdf->saveas('our/new.pdf');

$pdf = PDF::Builder->new;
$pdf->mediabox(0, 0, 595, 842); # A4 size, with explicit 0,0 LL corner
...
$pdf->saveas('our/new.pdf');

Go peek at the PDF::Builder::Resource::PaperSizes source code for the full list of supported names (aliases) and their dimensions in points. You're totally free to add extra paper sizes to that file if you want โ€” super handy if you keep reaching for a standard page size in rotated (Landscape) mode. Also check out the "getPaperSizes" call in PDF::Builder::Util. These names (aliases) work in the other "box" calls too, though they're only useful if the "box" is the same size as the full media (Media Box) and you don't mind them starting at 0,0. ๐ŸŽ€


Crop Box (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 the global Crop Box (or the page's Crop Box, if you use "$page->" instead). This defines the media size that your output will later get clipped to. Heads up though โ€” this does not itself output any crop marks to guide cutting of the paper, bestie, it's just the invisible boundary. PDF Readers should treat this as the visible portion of the page, and anything outside it may get clipped (aka invisible, gone, ghosted ๐Ÿ‘ป). By default it's equal to the Media Box, but you can define it smaller, in the coordinate system that the Media Box set up. A global setting gets inherited by each page, but you can override it per-page. slay ๐Ÿ’…

A Reader or Printer might choose to discard any clipped (invisible) part of the page and show only the area inside the Crop Box. Like, if your page Media Box is A4 (0,0 to 595,842 Points) and your Crop Box is (100,100 to 495,742), a reader like Adobe Acrobat Reader may show you a page 395 by 642 Points in size (i.e., just the visible area). Other Readers may show you the full media size (Media Box) with a 100 Point wide blank area (in this example) around the visible content. different readers, different vibes, iykyk ๐Ÿฆ‹

If you give no arguments, you get the current Crop Box (global or page) coordinates back instead. The old "get_cropbox" (page only) function was deprecated and has been removed, rip ๐Ÿชฆ. If no Crop Box has been defined, the Media Box coordinates (which always exist) get returned instead. And bonus: when you set the Crop Box, the resulting coordinates come back to you too. That means you can specify the crop box by a name (alias) and get the dimensions back, all in one call. iconic. ๐ŸŒŸ

Do not confuse the Crop Box with the "Trim Box", which shows where printed paper is actually expected to get cut. Some PDF Readers may shrink the visible "paper" background down to the size of the crop box; others may just yeet any content outside it. Either way, you'd lose any trim or crop marks, printer instructions, color alignment dots, or other content outside the Crop Box. A good use of the Crop Box is limiting printing to the area where a printer can reliably put down ink, leaving white the edge areas where paper-handling mechanisms prevent ink or toner from being applied. That keeps you from accidentally dropping valuable content where a printer will refuse to print, while still letting you include a bleed area and space for printer's marks and instructions. Needless to say, if your printer can't print to the very edge of the paper, you'll need to trim (cut) the printed sheets to get true bleeds. โœ‚๏ธ

A global (PDF level) cropbox setting is inherited by each page, or can be overridden by setting cropbox in the page. As with "mediabox", only one crop box may be set at this (PDF) level. As with "mediabox", a named media size may have an orientation (l or L) for Landscape mode. And here's the tea ๐Ÿ“: the PDF level global Crop Box will be used even if the page gets its own Media Box. That is, the page's Crop Box inherits the global Crop Box, not the page Media Box, even if the page has its own media size! So if you set the page's own Media Box, you should consider also explicitly setting the page Crop Box (and the other boxes too). don't get caught slipping ๐Ÿซถ


Bleed Box (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 the global Bleed Box (or the page's Bleed Box, if "$page->" instead). This one is typically used when printing on paper, when you want ink or color (like thumb tabs, cute ๐Ÿ‘€) printed a bit beyond the final paper size, so the cut paper properly bleeds (the cut goes through the ink) instead of accidentally leaving some white paper visible outside. Allow enough "bleed" over the expected trim line to account for minor variations in paper handling, folding, and cutting โ€” all that so you avoid showing white paper at the edge. The Bleed Box is where printing could actually extend to; the Trim Box is normally within it, where the paper would actually be cut. Default value equals the Crop Box, but it's often a bit smaller. The space between the Bleed Box and the Crop Box is available for printer instructions, color alignment dots, etc., while crop marks (trim guides) are at least partly within the bleed area (and should be printed after content is printed). ๐Ÿ’–

If you give no arguments, the current Bleed Box (global or page) coordinates are returned instead. The former "get_bleedbox" (page only) function was deprecated and has been removed ๐Ÿชฆ. If no Bleed Box has been defined, the Crop Box coordinates (if defined) get returned, otherwise the Media Box coordinates (which always exist) get returned. And same as before: when you set the Bleed Box, the resulting coordinates come back. So you can specify the bleed box by a name (alias) and get the dimensions back, all in one call. ๐Ÿ’…

A global (PDF level) bleedbox setting is inherited by each page, or can be overridden by setting bleedbox in the page. As with "mediabox", only one bleed box may be set at this (PDF) level. As with "mediabox", a named media size may have an orientation (l or L) for Landscape mode. And again โ€” the PDF level global Bleed Box will be used even if the page gets its own Crop Box. That is, the page's Bleed Box inherits the global Bleed Box, not the page Crop Box, even if the page has its own media size! So if you set the page's own Media Box or Crop Box, you should consider also explicitly setting the page Bleed Box (and the other boxes). ๐ŸŒˆ


Trim Box (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 the global Trim Box (or the page's Trim Box, if "$page->" instead). This is supposed to be the actual dimensions of the finished page (after the paper gets trimmed). In some production environments, it's useful to have printer's instructions, cut marks, and so on sitting outside of the trim box. The default value equals the Crop Box, but it's often a bit smaller than any Bleed Box, to allow that desired "bleed" effect. โœจ

If you give no arguments, the current Trim Box (global or page) coordinates are returned instead. The former "get_trimbox" (page only) function was deprecated and has been removed ๐Ÿชฆ. If no Trim Box has been defined, the Crop Box coordinates (if defined) get returned, otherwise the Media Box coordinates (which always exist) get returned. And yep, when you set the Trim Box, the resulting coordinates are returned too. That lets you specify the trim box by a name (alias) and get the dimensions back, all in one call. ๐Ÿ˜ญ (happy tears, it's just so convenient)

A global (PDF level) trimbox setting is inherited by each page, or can be overridden by setting trimbox in the page. As with "mediabox", only one trim box may be set at this (PDF) level. As with "mediabox", a named media size may have an orientation (l or L) for Landscape mode. And once more for the people in the back ๐Ÿ“ฃ: the PDF level global Trim Box will be used even if the page gets its own Crop Box. That is, the page's Trim Box inherits the global Trim Box, not the page Crop Box, even if the page has its own media size! If you set the page's own Media Box or Crop Box, you should consider also explicitly setting the page Trim Box (and the other boxes). ๐Ÿงš


Art Box (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 the global <strong>Art Box</strong> โ€” or the page's own Art Box if you say $page-> instead. Think of it as "the extent of the page's meaningful content (including [margins])". It's the box that might exclude stuff like Headlines or headings, you know? Any binding or punched-holes margin would typically live outside of the Art Box, and so would page numbers and running headers and footers. Default value = whatever the Crop Box is, though normally it wouldn't be any bigger than the Trim Box. The Art Box is often used for defining "important" content (like, excluding advertisements ๐Ÿซฃ) that may or may not get brought over to another page (N-up printing, for example).

If you pass no arguments at all, you get the current Art Box coordinates (global or page) back instead. Heads up: the old get_artbox (page only) function was deprecated and has been removed. If an Art Box hasn't been defined, the Crop Box coordinates get returned (if they exist), and if those don't exist, the Media Box coordinates get returned โ€” which always exist, so you're never left empty-handed. ๐Ÿ’– And when you're setting the Art Box, the resulting coordinates come back to you too. That means you can name your art box by an alias and get the dimensions back, all in one call. Iconic, honestly.

A global (PDF level) artbox setting gets inherited by every page, or a page can override it by setting artbox on itself. Just like mediabox, only one art box may be set at this (PDF) level. Also just like mediabox, a named media size may have an orientation (l or L) for Landscape mode. โš ๏ธ Important though: the PDF level global Art Box gets used even if the page has its own Crop Box. Like, the page's Art Box inherits the global Art Box, not the page Crop Box, even if the page has its own media size! So if you set the page's own Media Box or Crop Box, you should consider explicitly setting the page Art Box too (and the other boxes while you're at it).

๐ŸŒธ Suggested Box Usage ๐ŸŒธ

Peep examples/Boxes.pl for an example of using boxes.

How you define your boxes (or just let them default) is totally up to you, and it depends on what you're actually doing โ€” duplex printing US Letter or A4 on your laser printer? Spiral bound on the bind margin? Engaging a professional printer? For that last one, discuss in advance with the print firm what capabilities (and limitations) they have and what info they need from a PDF file. For instance, they may not want a Crop Box defined at all, and may call for very specific box sizes. For large press runs, they may print multiple pages (N-up) duplexed on large web roll "signatures", which then get intricately folded and guillotined (trimmed) and bound together into books or magazines. You'd usually just supply a PDF with all the pages; they'd handle the signature layout (which includes offsets and 180 degree rotations).

(As an aside โ€” do not count on a commercial printer having any particular font available, so be sure to ask. Usually they'll want you to embed all fonts used, but ask first, and double-check before handing over the print job! TTF/OTF fonts (ttfont()) are embedded by default, but other fonts (core, ps, bdf, cjk) are not! A printer may have a core font collection, but they are free to substitute a "workalike" font for any given core font, and the results may not match what you saw on your PC! ๐Ÿ˜ญ)

So, assuming you're using a single sheet (US Letter or A4) laser or inkjet printer โ€” are you planning to trim each sheet down to a smaller final size? If so, you can do true bleeds by defining a Trim Box and a slightly larger Bleed Box. You'd print bleeds (all the way to the finished edge) out to the Bleed Box, but nothing is enforced about the Bleed Box. At the other end of the spectrum, you'd define the Media Box to be the physical paper size being printed on. Most printers reserve a little space on the sides (and possibly top and bottom) for paper handling, so it's often good to define your Crop Box as the printable area. Remember that the Media Box sets the coordinate system used, so you still need to avoid going outside the Crop Box with content (most readers and printers will not show any ink outside of the Crop Box). Whether or not you define a Crop Box, you're going to almost always end up with white paper on at least the sides.

For small in-house jobs, you probably won't need color alignment dots and other such professional instructions and information between the Bleed Box and the Crop Box โ€” but crop marks for trimming (if used) should go just outside the Trim Box (partly or wholly within the Bleed Box), and be drawn after all content. If you're not trimming the paper, don't try to do any bleed effects (including solid background color pages/covers), because you'll usually have a white edge around the sheet anyway (printers leave a clean, dry route for the feed rollers). And don't count on a PDF document never being physically printed and only ever displayed (where you can do things like bleed all the way to the media edge). Finally, for single sheet printing, an Art Box is probably unnecessary โ€” but if you're combining pages into N-up prints, or doing other manipulations, it may be useful.

๐Ÿฆ‹ Box Inheritance ๐Ÿฆ‹

What Media, Crop, Bleed, Trim, and Art Boxes a page gets can be a little complicated. Note that usually, only the Media and Crop Boxes will have a clear visual effect. The visual effect of the other boxes (if any) may be very subtle.

  1. First, everything is set at the global (PDF) level. The Media Box is always defined, and defaults to US Letter (8.5 inches wide by 11 inches high). The global Crop Box inherits the Media Box, unless explicitly defined. The Bleed, Trim, and Art Boxes inherit the Crop Box, unless explicitly defined. A global box should only be defined once, because the last one defined is the one that will be written to the PDF!
  2. Second, a page inherits the global boxes, for its initial settings. You may call any of the box set methods (cropbox, trimbox, etc.) to explicitly set (override) any box for this page. Note that setting a new Media Box for the page does not reset the page's Crop Box โ€” it still uses whatever it inherited from the global Crop Box. You'd need to explicitly set the page's Crop Box if you want a different setting. Likewise, the page's Bleed, Trim, and Art Boxes will not be reset by a new page Crop Box โ€” they'll still inherit from the global (PDF) settings.
  3. Third, the page Media Box (the one actually used for output pages) clips or limits all the other boxes to extend no larger than its size. For example, if the Media Box is US Letter, and you set a Crop Box of A4 size, the smaller of the two heights (11 inches) would be effective, and the smaller of the two widths (8.26 inches, 595 Points) would be effective. The given dimensions of a box are returned on query (get), not the effective dimensions clipped by the Media Box.

๐ŸŽ€ Outlines (Bookmarks) ๐ŸŽ€

Okay bestie, you can absolutely create outlines (a.k.a. bookmarks) in a PDF document. And you are not limited to entire pages as targets โ€” you can adjust the destination dest() to bring up a specific part of a page. Slay.

โœจ Simple Single-Level set of Outline โœจ

Inserts three outlines (at the same level) in a simple list of 12 pages (055_outlines example):

my $doc = PDF::Builder-> open($infile);

$doc-> outlines
    -> outline
        -> dest( $doc-> openpage( 1 ))
        -> title( '1st page (i)' );

$doc-> outlines
    -> outline
        -> dest( $doc-> openpage( 4 ))
        -> title( '4th page (1)' );

$doc-> outlines
    -> outline
        -> dest( $doc-> openpage( 11 ))
        -> title( '11th page (7)' );

dest() by default is a link to an entire page (given as the ordinal page number, not the document's formatted page number). The title() is what you see in the Outline or Bookmark section of your PDF Reader.

๐Ÿ’… A Multi-level example Outline ๐Ÿ’…

It is also possible to define nested (multiple level) outlines. For the same set of pages as above, we'll add two pages nested under page i and three pages nested under page 1. Note that it's common practice to make the top level sections (e.g., preface, body, end matter) and put all the real pages under them, but you still need to have each section "heading" map to a real page. So preface might point to page i, and have outlines to i, ii, and iii nested below it.

my $doc = PDF::Builder-> open($infile);
my $root =  # Outlines object (root of whole thing)
    $doc-> outlines();

my $top0 =  # Outline object at top level, initially collapsed (closed)
$root -> outline($root)
        -> is_open(0)
        -> dest( $doc-> openpage( 1 ))
        -> title( '1st page (i)' );

my $top1 =  # Outline object at top level
$root -> outline($root)
        -> dest( $doc-> openpage( 4 ))
        -> title( '4th page (1)' );

my $top2 =  # Outline object at top level. no children
$root -> outline($root)
        -> dest( $doc-> openpage( 11 ))
        -> title( '11th page (7)' );

# add lower level bookmarks here. there's no reason that they couldn't be
# mixed in with the higher levels above, provided that they come after
# their parent is defined.

# two pages under the first top-level page (i)
$top0 -> outline($top0)
          -> dest( $doc-> openpage( 2 ))
          -> title( '2nd page (ii)' );

$top0 -> outline($top0)
          -> dest( $doc-> openpage( 3 ))
          -> title( '3rd page (iii)' );

# three pages under the second top-level page (1). the third is
# inserted after the first and before the second.
my $first =
$top1 -> outline($top1)
          -> dest( $doc-> openpage( 5 ))
          -> title( '5th page (2)' );

$top1 -> outline($top1)
          -> dest( $doc-> openpage( 6 ))
          -> title( '6th page (3)' );

$first -> insert_after()
          -> dest( $doc-> openpage( 7 ))
          -> title( '7th page (4)' );

It's possible to define a single outline (link) as closed, in which case all the outlines nested under it will be hidden (with a "closed" twistor). Try to avoid going more than two levels deep (one level of nesting), because the Outlines/Bookmarks column is usually pretty narrow.


๐ŸŒˆ FONT METHODS ๐ŸŒˆ

๐Ÿ’œ Core Fonts ๐Ÿ’œ

These are the "built-in" fonts, in the sense that any PDF Reader is guaranteed to supply and support them. The metrics for the supported fonts are shipped with PDF::Builder โ€” but not the fonts themselves. ๐Ÿ’€

Core fonts are single byte encodings ONLY, bestie. Like, that's the whole vibe. The default encoding for core fonts is WinAnsiEncoding (which is roughly the CP-1252/Windows-1252 superset of ISO-8859-1/Latin-1, iykyk). Wanna change it? Peep the "encode" option down below. ๐Ÿ’…

So there are some 14 core fonts โ€” regular, italic, bold, and bold-italic variants โ€” for Times [serif], Helvetica [sans serif], and Courier [fixed pitch]; plus two symbol fonts, Symbol and Zapf Dingbats. These are supposed to be available on any PDF Reader, although ngl, other fonts with very similar metrics get substituted all the time. ๐Ÿ™ˆ

Windows machines have an extra 14 "core" fonts (15 if you count Bank Gothic ๐Ÿ˜ญ): Georgia [serif], Verdana [sans serif], and Trebuchet [sans serif] in 4 variants each, along with Webdings and Wingdings. These are usually available on a Windows platform (but not guaranteed, fr fr!). They're usually not installed by default on Linux, Mac, and other non-Windows platforms, so use caution if you're specifying these fonts. ๐Ÿซถ

PDF::Builder does supply the metrics for the Windows core fonts (as well as the standard ones), so it should be possible to use PDF::Builder to generate documents (PDF files) containing these fonts, even if your platform may not be able to display them. For instance, Font Manager will load the Windows core fonts on all platforms. It is up to the user to take care in selecting fonts, if they plan to be able to view documents using those fonts! On the other hand, the 020_corefonts example will not attempt to create listings of Windows core fonts unless it is run on a Windows platform. โœจ

๐ŸŒˆ Examples ๐ŸŒˆ

$font1 = $pdf->corefont('Times-Roman', encode => 'latin2');
$font2 = $pdf->corefont('Times-Bold');
$font3 = $pdf->corefont('Helvetica');
$font4 = $pdf->corefont('ZapfDingbats');

Core fonts can also be requested via the font() method ๐Ÿ‘‘

$font5 = $pdf->font('Courier-Oblique');

as well as being built into FontManager ๐Ÿ’–

$font6 = $pdf->get_font('face'=>'Times', 'italic'=>1, 'bold'=>0);

๐Ÿ’€ Notes and Limitations ๐Ÿ’€

  • You cannot use UTF-8 or other multibyte encodings with core fonts, only single byte encodings (256 characters maximum). A PDF Reader simply does not know what to do with a multibyte character, and likely will render it as a sequence of single characters (producing gibberish ๐Ÿ˜ญ). Although most single-byte encodings, at least for European languages, are supported, it is possible that you might encounter an encoding that includes a character not found in a given font file, or vice-versa (the font includes characters that the encoding does not give you access to). It's giving mismatch energy.
  • Do not confuse Unicode character points (such as given with an HTML entity) with single byte values or multibyte characters. The only way to access a character defined for a given encoding is with a single byte value in the range 0 to 255. For example, if you can't directly type a "Euro" symbol, it is "\x80" in many encodings โ€” you would use that instead of the Unicode "\x{20AC}" code point or "x\{E282AC}" UTF-8 byte string. It's a matter of giving a single byte value that the PDF Reader can look up in its font definition to get the desired glyph. If the "Euro" symbol is not found in the encoding you're using, well, you're out of luck. ๐Ÿ™ˆ
  • Be aware of what a given platform (operating system) and editor is using for its code page when it creates a file with your text to be turned into a PDF! If you typed a "Euro" but it's, say, a UTF-8 byte string in the file, you probably won't get a "Euro" in your PDF. Classic trap, bestie.
  • Note that core fonts use fixed lists of expected glyphs, along with metrics such as their widths. This may not exactly match up with whatever local font file is used by the PDF Reader. It's usually pretty close, but many cases have been found where the list of glyphs is different between the core fonts and various local font files, so be aware of this. There is no guarantee that all glyphs (code points) found in one single-byte encoding will be found in another, nor that font metrics are available for all glyphs covered by a given singe-byte encoding. If you are writing in English, or even in most Western European languages, this is usually not a problem with core fonts, but for other languages and alphabets, it might be. ๐ŸŒธ
  • Also be aware that a PDF Reader is free to substitute another font which is similar (but not necessarily identical) to the requested core font. For example, Windows machines often substitute Arial for the requested Helvetica. The metrics (widths) are the same, but the glyphs are a little different. Not me getting a whole different font than I ordered ๐Ÿ’€
  • Core fonts are supposed to be available on all PDF Readers, so they are not embeddable in the PDF (as TTF fonts are). This is not believed to be a problem for archival (PDF/A) documents, but may become one at some point, so you should be aware. ๐Ÿ‘‘

See "font automap" in PDF::Builder::Resource::Font method for information on accessing more than 256 glyphs in a font, using planes, although there is no guarantee that future changes to font files will permit consistent results. ๐Ÿฆ‹

๐Ÿงš Should you use TTF instead? ๐Ÿงš

If you need to reliably access certain characters not found in common encodings, please consider using TrueType (TTF) or OpenType (OTF) fonts via the ttfont() method. Note that you will be responsible for specifying the exact path and full file name of the TTF file, and making sure the font file is available on the PDF Writer, and possibly on the Reader (if not embedded). โœจ

This would enable you to use UTF-8 text, with extended glyph usability, as well as permitting the font itself to be embedded in the PDF, ensuring that you get exactly the glyphs you want, without any substitutions. Kerning and ligature support (via HarfBuzz::Shaper) may be more available for TTF fonts. There are tools, such as FontForge, which can do a fairly good (though, not perfect) job of converting a Type1 font library (if that's what your core fonts are, internally) to OTF. ๐ŸŽ€

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


๐Ÿฆ‹ PS Fonts ๐Ÿฆ‹

PostScript fonts are also known as "Type 1" fonts. These are not "built-in" fonts, and both the PDF Writer and any PDF Reader would need to provide the desired font files. PostScript fonts used to be very commonly used, but have fallen out of favor. RIP to a legend, lowkey.

PS (Type 1) fonts are not shipped with PDF::Builder, but are expected to be found on the machine with the PDF reader. Most PDF readers do not install PS fonts, and it is up to the user of the PDF reader to install the needed fonts. Unlike TrueType fonts, PS (T1) fonts are not embedded in the PDF, and must be supplied on the Reader end. ๐Ÿ˜ญ

PS fonts are limited to single byte encodings. The default encoding for the PS fonts is WinAnsiEncoding (roughly the CP-1252/Windows-1252 superset of ISO-8859-1/Latin-1). See the "encode" option below to change this encoding. ๐Ÿ’…

One characteristic of PS font usage is that two files are used for each font: a glyph file (".pfa" for ASCII format, ".pfb" for binary format, or ".t1" for an extended format), and a metrics file (".afm" for an ASCII format, or ".pfm" for binary format). A binary glyph file may be used with an ASCII metrics file, and vice-versa, if desired or needed. The ASCII and binary files have the same content, just in different formats. โœจ

Caution: the file name given for the glyph file (first argument to "psfont") must have a file extension of .pfa, .pfb, or .t1; as the extension will be checked to see how to parse the file. Don't skip the extension, bestie, it's literally how it knows what to do!

๐Ÿ”ฅ WARNING: End of Adobe Support ๐Ÿ”ฅ

Adobe has announced an end to support for Type 1 (Postscript/T1) fonts in its products. The announcement wordings are a bit vague, sometimes referring to "all products" and other times just to "authoring software". Presumably, Adobe PDF Readers (as well as Readers supplied by other parties) will continue to display PDFs with Type 1 fonts for quite some time, although this is by no means absolutely certain. Note that this does NOT mean that PDF::Builder or other Third Party authoring tools may not continue to support Type 1 fonts. This termination by Adobe of support of a now old and obsolete font format does not affect the use of PDF::Builder for authoring PDFs, nor is it binding on other non-Adobe readers and authoring tools. However, using Adobe products for editing of PDFs with Type 1 fonts, and possibly of displaying them, may no longer be possible. At any rate, users may want to consider starting to move away from Type 1 font usage and switch to TTF/OTF or even core fonts, although it is unknown how long Type 1 Reader support will continue. Not me watching a whole font format sunset in real time ๐Ÿ’€

๐ŸŒธ Examples ๐ŸŒธ

$font1 = $pdf->psfont('Times-Book.pfa', afmfile => 'Times-Book.afm');
$font2 = $pdf->psfont('/fonts/Synest-FB.pfb', pfmfile => '/fonts/Synest-FB.pfm');

PS fonts can also be requested via the font() method ๐Ÿ‘‘

$font3 = $pdf->font('/fonts/Times-Book.t1', afmfile => '/fonts/Times-Book.afm');

as well as being capable of being loaded into FontManager ๐Ÿ’–

$font4 = $pdf->get_font('face'=>'Times-Book', 'italic'=>0, 'bold'=>0);

๐Ÿ“ Notes and Limitations ๐Ÿ“

  • You cannot use UTF-8 or other multibyte encodings with PS fonts, only single byte encodings (256 characters maximum). A PDF Reader (or Writer!) simply does not know what to do with a multibyte character, and likely will render it as a sequence of single characters (producing gibberish ๐Ÿ˜ญ). Although most single-byte encodings, at least for European languages, are supported, it is possible that you might encounter an encoding that includes a character not found in a given font file, or vice-versa (the font includes characters that the encoding does not give you access to).
  • Do not confuse Unicode character points (such as given with an HTML entity) with single byte values or multibyte characters. The only way to access a character defined for a given encoding is with a single byte value in the range 0 to 255. For example, if you can't directly type a "Euro" symbol, it is "\x80" in many encodings โ€” you would use that instead of the Unicode "\x{20AC}" code point or "x\{E282AC}" UTF-8 byte string. It's a matter of giving a single byte value that the PDF Reader can look up in its font definition to get the desired glyph. If the "Euro" symbol is not found in the encoding you're using, well, you're out of luck. ๐Ÿ™ˆ
  • Be aware of what a given platform (operating system) and editor is using for its code page when it creates a file with your text to be turned into a PDF! If you typed a "Euro" but it's, say, a UTF-8 byte string in the file, you probably won't get a "Euro" in your PDF. Same trap as before, and it WILL get you if you're not paying attention.

...and fr fr, if you need more than 256 glyphs out of a font, go read up on "font automap" in the PDF::Builder::Resource::Font method โ€” that's your gateway to using planes to reach the extras. ๐Ÿ’… Lowkey gotta warn you tho: there is no guarantee that future changes to font files will permit consistent results. It's giving "works today, pray for tomorrow." ๐Ÿ™ˆ

Should you use TTF instead?

Okay bestie, real talk: if you need to reliably get at certain characters that just aren't in the common encodings, please consider using TrueType (TTF) or OpenType (OTF) fonts through the ttfont() method instead. Periodt. โœจ

But heads up โ€” the tradeoff is on you, not the module:

  • you're responsible for specifying the exact path and full file name of the TTF file ๐Ÿซถ
  • you gotta make sure the font file is actually available on the PDF Writer, and possibly on the Reader too (that's the case if it's not embedded) ๐Ÿ˜ญ

What this buys you: you can use UTF-8 text with extended glyph usability, and you can let the font itself be embedded right into the PDF โ€” which means you get exactly the glyphs you want, no substitutions, no failures, no "sorry this file isn't on your reader" drama. ๐ŸŒธ Kerning and ligature support (via HarfBuzz::Shaper) may also be more available for TTF fonts. And if you're sitting on a Type1 font library, there are tools like FontForge that can do a fairly good (though, not perfect) job converting it to OTF. ๐Ÿ‘‘

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


TrueType Fonts

TrueType (TTF) fonts and their close cousins, OpenType (OTF) fonts, are widely used โ€” you've definitely seen them. They ship with tons of operating systems, but plot twist: they are not "built-in" to PDF. So both the PDF Writer and any PDF Reader (if the font isn't embedded) would need to have the desired font files on hand. ๐Ÿ’€

TTF and OTF fonts are not shipped with PDF::Builder. They're just expected to be found on the machine running the PDF Writer (and, if needed, the Reader). Most PDF readers do not install TTF/OTF fonts, and it's up to the user of the PDF reader to install whatever's needed (when it wasn't embedded). Good news tho: the default behavior is to embed the font subset โ€” like, only the glyphs you actually used โ€” into the PDF file. So there's basically no chance of the reader not having the right font. Slay. ๐ŸŽ€

TTF and OTF fonts aren't stuck in single byte encodings either โ€” they can use multibyte encodings such as UTF-8. The default encoding for these fonts is WinAnsiEncoding (roughly the CP-1252/Windows-1252 superset of ISO-8859-1/Latin-1). Want something else? Check the "encode" option below to change it. ๐Ÿฆ‹

Examples

    $font1 = $pdf->ttfont('Times.ttf');
    $font2 = $pdf->ttfont('Georgia.otf');

TTF/OTF fonts can also be requested via the font() method

    $font3 = $pdf->font('/fonts/Sanskrit.ttf');

as well as being capable of being loaded into FontManager

    $font4 = $pdf->get_font('face'=>'BrushScript', 'italic'=>0, 'bold'=>0);

Notes and Limitations

  • CAUTION: There's a "gotcha" with TrueType fonts that you genuinely need to be aware of. PDF::Builder outputs to the text stream a list of glyph IDs as four-digit hex codes, rather than the list of character byte codes that other font types use. The intent is to allow more than the standard Unicode points (alternate glyphs for ligatures and other uses โœจ). But do not count on this as encryption to hide your content โ€” the PDF Reader will just display it anyway! Even though it does make it hard to find specific text in a PDF using a text editor. ๐Ÿ’€
  • The Tw operator, if you use it ("$text->wordspace(n)") to adjust inter-word spacing, will be ignored by most, if not all, PDF Readers (including Adobe products ๐Ÿ‘€). Why? Because that operator is looking for actual ASCII spaces (x20 bytes) in the stream to apply the width change to. Note that only ASCII spaces are affected (not other spaces), and not at all for TrueType and OpenType fonts โ€” because they have 4-digit glyph IDs, not x20 bytes! ๐Ÿ™ˆ

PDF::Builder has been updated to attempt to respect the Tw operator when using TTF/OTF fonts. If the "Tw" amount is non-zero, it will split up sentences on ASCII spaces (x20) and individually place words on the page. This necessarily bloats the PDF file size, but it's the only way to adjust word spacing via the wordspace() method. And again โ€” only ASCII spaces (x20) are affected (to match the behavior of the Tw operator for other font types). Other spaces (xA0 required/non-breaking space, thin space, etc.) are not handled. ๐Ÿ˜ญ

  • Warning: BaseEncoding is not set by default for TrueType fonts, so text in the PDF isn't searchable (by the PDF reader) unless a ToUnicode CMap is included. A ToUnicode CMap is included by default (unicodemap set to 1) by PDF::Builder, but it allows it to be disabled (for performance and file size reasons ๐Ÿ’…) by setting unicodemap to 0. Doing that will produce non-searchable text, which, besides being annoying to users, may prevent screen readers and other aids to disabled users from working correctly! Not iconic. Not cute. Don't do it casually. ๐Ÿซถ
  • Do not confuse Unicode character points (like the ones you'd give with an HTML entity) with single byte values or multibyte characters. The only way to access a character defined for a given encoding is with a single code value in the allowable range. For example, if you can't directly type a "Euro" symbol, it's "\x80" in many encodings โ€” you'd use that for a single-byte encoding, or for UTF-8, the Unicode "\x{20AC}" code point. You would never give the UTF-8 byte string "x\{E282AC}". It needs to be understandable in the context of the current encoding, so that the 4-digit glyph code can be output. ๐Ÿงš
  • Be aware of what a given platform (operating system) and editor is using for its code page when it creates a file with your text to be turned into a PDF! If you typed a "Euro" but it's, say, a UTF-8 byte string in the file, and you are using a single-byte encoding, you probably won't get a "Euro" in your PDF. ๐Ÿ˜ฌ

Where is the font I just added?

Okay this is the part nobody warns you about. ๐Ÿ™ˆ Sometimes you get lucky and you can specify the exact directory the ".ttf" or ".otf" file lives in, which makes it so easy to specify the path to the font file (for uses such as ttfont(), font(), or Font Manager calls). Other times, the operating system plays hide and seek with you and you burn hours tracking down where the file went. ๐Ÿ’€

Linux distributions tend to have their own favorite hiding places for font files, but at least they tend to be consistent! Windows, on the other hand, often decides it knows better than you, and will put files in an unexpected place, under an unexpected name. Main character energy, but make it annoying. ๐Ÿ˜ค

So โ€” to find out where your TTF or OTF file ended up: if you don't see an obvious entry in /Windows/Fonts (even if you drag-and-dropped the font file right there), you need to look in /Users/XXXX/AppData/Local/Microsoft/Windows/Fonts, depending on what user name you were signed on as when you installed the font. And even then, you may not be done, because the name may have been changed to something unrecognizable. You may need to look at Windows' mapping of font name to filename. ๐Ÿ•ต๏ธ

In the command shell (command line), or whatever equivalent you like to use, enter "regedit" to bring up the registry editor. For the top level, choose (click on) either "HKEY_LOCAL_MACHINE" (for global font settings, in /Windows/Fonts) or "HKEY_CURRENT_USER" (for fonts installed by whoever is currently signed on, in /Users/XXXX/AppData...). From there, both have the same path: "SOFTWARE > Microsoft > Windows NT > CurrentVersion > Fonts". This should bring up a listing of all the installed fonts (full name, e.g. "Papyrus Regular") and their actual filename ("PAPYRUS.TTF"). ๐Ÿ’–

For instance โ€” and this is a real one โ€” I just installed (drag and drop into /Windows/Fonts) a blackletter "Gothic" font named English Towne Medium. It ended up in my /Users/XXXX... directory as "EnglishTowne.ttf". ๐ŸŒธ

You don't need to change anything in the registry, just look. You do have the capability to change things, including hiding/showing the font, if you care to get into those things.

See also PDF::Builder::Resource::CIDFont::TrueType.


CJK Fonts

Examples:

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

Warning: Unlike ttfont(), the font file is not embedded in the output PDF file. This is evidently behavior left over from the early days of CJK fonts, where the "Cmap" and "Data" were always external files rather than internal tables. ๐Ÿ˜ญ

If you need a CJK-using PDF file to embed the font, for portability, you can create a PDF using "cjkfont", and then use an external utility (e.g., "pdfcairo") to embed the font in the PDF. It may also be possible to use ttfont() instead, to produce the PDF โ€” provided you can deduce the correct font file name from examining the PDF file. Like, on my Windows system, the "Ming" font would be:

    $font = $pdf->ttfont("C:/Program Files/Adobe/Acrobat DC/Resource/CIDFont/AdobeMingStd-Light.otf")

Of course, the font file used would have to be ".ttf" or ".otf". It may act a little differently than "cjkfont" (due a a different Cmap), but you should be able to embed the font file into the PDF. โœจ

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

Due to the lack of ongoing support for CJK fonts, and the apparent "arrested development" of PDF support for them at an early stage of life, we strongly recommend that you attempt to directly use TTF or OTF fonts for Far-Eastern (CJK) text support (via ttfont()) before resorting to cjkfont() usage! ๐Ÿ‘‘ Also, CJK fonts appear to be unusable as input for synthetic fonts, and normally aren't embedded in the PDF file (which means the font file has to be installed on the Reader). ๐Ÿ’€


Synthetic Fonts

Warning: BaseEncoding is not set by default for these fonts, so text in the PDF isn't searchable (by the PDF reader) unless a ToUnicode CMap is included. A ToUnicode CMap is included by default (unicodemap set to 1) by PDF::Builder, but it allows it to be disabled (for performance and file size reasons) by setting unicodemap to 0. This will produce non-searchable text, which, besides being annoying to users, may prevent screen readers and other aids to disabled users from working correctly! ๐Ÿซถ

Examples:

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

Note that CJK fonts (created with the "cjkfont" method) do not work properly with "synfont". This is due to a different internal structure of the CJK fonts, as compared to corefont, ttfont, and psfont base fonts. If you require a synthesized (modified) CJK font, you might try finding the TTF or OTF original, use "ttfont" to create the base font, and run "synfont" against that, in the manner described for embedding "CJK Fonts". ๐ŸŒˆ

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

๐Ÿ’– IMAGE METHODS ๐Ÿ’–

okay bestie, this is the extra tea on the โœจenhancedโœจ libraries you can use for TIFF and PNG images. For the GD, GIF, JPEG, and PNM formats, go look at their own specific info listings. Also, peep examples/Content.pl โ€” it shows you how to slap an image onto a page and how to use it inside a Form. ๐Ÿ–ผ๏ธ


๐ŸŒ€ Why is my image flipped or rotated??

Not me getting this question every single week ๐Ÿ˜ญ Here's the thing โ€” it's actually super common with JPEG photos in a PDF: your image shows up rotated and/or mirrored (flipped). Same energy can hit TIFF images too. What's going down is that the camera stores the image exactly as it came off the CCD sensor, no matter which way the camera was actually pointing, and it does not rotate it to the correct orientation! It does stash a separate "orientation" flag suggesting how the image might be corrected, but not all image processing obeys that flag. (PDF::Builder does not.) So likeโ€ฆ if you take a "portrait" (tall) photo of a tree with the phone held vertically, then use it in a PDF, the tree may look like somebody cut it down ๐ŸŒณ๐Ÿ’€ (it appears in landscape mode).

I found some code that should let the image_jpeg or image routine auto-rotate to (supposedly) the correct orientation by hunting for the Exif metadata "Orientation" tag in the file. But bestie, three problems pop up:

  1. If a photo has been edited, and rotated or flipped in the process, there is no guarantee that the Orientation tag has been corrected.
  2. More than one Orientation tag may exist (e.g., in the binary APP1/Exif header, and in XML data), and they may not agree with each other โ€” soโ€ฆ which one are we even supposed to use?? ๐Ÿ™ˆ
  3. The code would need to uncompress the raster data, swap and/or transpose rows and/or columns, and recompress the raster data for inclusion into the PDF. That is costly and error-prone. And in any case, the user would need to be able to override any auto-rotate function.

So for now, PDF::Builder is just gonna leave it up to you, the library user, to handle rotating and/or flipping an image that displays incorrectly. It's possible we'll consider adding some sort of query or warning that the image appears to not be "normally" oriented (Orientation value 1 or "Top-left"), according to the Orientation flag. In the meantime you can either (re-)save the photo in an editor like PhotoShop or GIMP, or use PDF::Builder code like this (for images rotated 180 degrees):

$pW = 612; $pH = 792;  # page dimensions (US Letter)
my $img = $pdf->image_jpeg("AliceLake.jpeg");
# raw size WxH 4032x3024, scaled down to 504x378
$sW = 4032/8; $sH = 3024/8;
# intent is to center on US Letter sized page (LL at 54,207)
# Orientation flag on this image is 3 (rotated 180 degrees).
# if naively displayed (just $gfx->image call), it will be upside down

$gfx->save();

## method 0: simple display, is rotated 180 degrees!
#$gfx->image($img, ($pW-$sW)/2,($pH-$sH)/2, $sW,$sH);

## method 1: translate, then rotate
#$gfx->translate($pW,$pH);             # to new origin (media UR corner)
#$gfx->rotate(180);                    # rotate around new origin
#$gfx->image($img, ($pW-$sW)/2,($pH-$sH)/2, $sW,$sH);
                                       # image's UR corner, not LL

# method 2: rotate, then translate
$gfx->rotate(180);                     # rotate around current origin
$gfx->translate(-$sW,-$sH);            # translate in rotated coordinates
$gfx->image($img, -($pW-$sW)/2,-($pH-$sH)/2, $sW,$sH);
                                       # image's UR corner, not LL

## method 3: flip (mirror) twice
#$scale = 1;  # not rescaling here
#$size_page = $pH/$scale;
#$invScale = 1.0/$scale;
#$gfx->add("-$invScale 0 0 -$invScale 0 $size_page cm");
#$gfx->image($img, -($pW-$sW)/2-$sW,($pH-$sH)/2, $sW,$sH);

$gfx->restore();

If your image is also mirrored (flipped about an axis), a simple rotation will not be enough, bestie. You could do something with a reversal of the coordinate system, like in "method 3" above (see "Advanced Methods" in PDF::Builder::Content). To mirror only left/right, the second $invScale would be positive; to mirror only top/bottom, the first one would be positive. And if all else fails, you could just save a mirrored copy in a photo editor. ๐ŸŽจ 90 or 270 degree rotations will require a rotate call, possibly with cm usage to reverse mirroring. Oh and incidentally โ€” do not confuse this issue with the coordinate flipping performed by some Chrome browsers when printing a page to PDF. Different drama, same chaos.

๐Ÿ’ก Heads up: TIFF images may have the exact same rotation/mirroring problems as JPEG. Which is not surprising at all, because the Exif format was literally lifted from TIFF for use in JPEG. The cure will be similar to JPEG's.

๐ŸŒธ TIFF Images ๐ŸŒธ

Quick note bestie: the Graphics::TIFF support library does not currently permit a filehandle for $file.

PDF::Builder will use the Graphics::TIFF support library for TIFF functions, if it's available, unless you explicitly tell it not to. Your code can test whether Graphics::TIFF is available by examining $tiff->usesLib() or $pdf->LA_GT().

Note that the first query is only available once the $tiff object has been created. Which may or may not be too late for your purposes. ๐Ÿ˜ฌ

  • = -1 โ€” Graphics::TIFF is installed, but your code has specified nouseGT, to not use it. The old, pure Perl, code (buggy! ๐Ÿ›) will be used instead, as if Graphics::TIFF was not installed.
  • = 0 โ€” Graphics::TIFF is not installed. Not all systems are able to successfully install this package, as it requires libtiff.a.
  • = 1 โ€” Graphics::TIFF is installed and is being used. ๐ŸŽ‰

Options:

  • nouseGT => 1 โ€” Do not use the Graphics::TIFF library, even if it's available. Normally you would want to use this library, but there may be cases where you don't, such as when you want to use a file handle instead of a name.
  • silent => 1 โ€” Do not give the message that Graphics::TIFF is not installed. This message will be given only once, but you may want to suppress it, such as during t-tests.

๐Ÿฆ‹ PNG Images ๐Ÿฆ‹

PDF::Builder will use the Image::PNG::Libpng support library for PNG functions, if it's available, unless you explicitly tell it not to. Your code can test whether Image::PNG::Libpng is available by examining $png->usesLib() or $pdf->LA_IPL().

Note that the first query is only available once the $png object has been created. Again โ€” maybe too late for your purposes, maybe not. You decide. ๐Ÿ™ƒ

  • = -1 โ€” Image::PNG::Libpng is installed, but your code has specified nouseIPL, to not use it. The old, pure Perl, code (slower and less capable ๐Ÿ˜ญ) will be used instead, as if Image::PNG::Libpng was not installed.
  • = 0 โ€” Image::PNG::Libpng is not installed. Not all systems are able to successfully install this package, as it requires libpng.a.
  • = 1 โ€” Image::PNG::Libpng is installed and is being used. โœจ

Options:

  • nouseIPL => 1 โ€” Do not use the Image::PNG::Libpng library, even if it's available. Normally you would want to use this library, when available, but there may be cases where you don't.
  • silent => 1 โ€” Do not give the message that Image::PNG::Libpng is not installed. This message will be given only once, but you may want to suppress it, such as during t-tests.
  • notrans => 1 โ€” No transparency โ€” ignore tRNS chunk if provided, ignore Alpha channel if provided.

๐Ÿ‘‘ USING SHAPER (HarfBuzz::Shaper library) ๐Ÿ‘‘

# if HarfBuzz::Shaper is not installed, either bail out, or try to
# use regular TTF calls instead
my $rc;
$rc = eval {
    require HarfBuzz::Shaper;
    1;
};
if (!defined $rc) { $rc = 0; }
if ($rc == 0) {
    # bail out in some manner
} else {
    # can use Shaper
}

my $fontfile = '/WINDOWS/Fonts/times.ttf'; # used by both Shaper and textHS
my $fontsize = 15;                         # used by both Shaper and textHS
my $font = $pdf->ttfont($fontfile);
$text->font($font, $fontsize);

my $hb = HarfBuzz::Shaper->new(); # only need to set up once
my %settings; # for textHS(), not Shaper
$settings{'dump'} = 1; # see the diagnostics
$settings{'script'} = 'Latn';
$settings('dir'} = 'L';  # LTR
$settings{'features'} = ();  # required

# -- set language (override automatic setting)
#$settings{'language'} = 'en';
#$hb->set_language( 'en_US' );
# -- turn OFF ligatures
#push @{ $settings{'features'} }, 'liga';
#$hb->add_features( 'liga' );
# -- turn OFF kerning
#push @{ $settings{'features'} }, 'kern';
#$hb->add_features( 'kern' );
$hb->set_font($fontfile);
$hb->set_size($fontsize);
$hb->set_text("Let's eat waffles in the field for brunch.");
  # expect ffl and fi ligatures, and perhaps some kerning

my $info = $hb->shaper();
$text->textHS($info, \%settings); # strikethru, underline allowed

The package HarfBuzz::Shaper may be optionally installed in order to use the text-shaping capabilities of the HarfBuzz library. These include kerning and ligatures in Western scripts (such as the Latin alphabet). More complex scripts can be handled too, like the Arabic family and Indic scripts, where multiple forms of a character may be automatically selected, characters may be reordered, and other modifications made. The examples/HarfBuzz.pl script gives some examples of what may be done. ๐Ÿงš

โš ๏ธ Keep in mind that HarfBuzz works only with TrueType (.ttf) and OpenType (.otf) font files. It will not work with PostScript (Type1), core, bitmapped, or CJK fonts. Not all .ttf fonts have the instructions necessary to guide HarfBuzz, but most proper .otf fonts do. In other words, there are no guarantees that a particular font file will work with Shaper!

The basic idea is to break up text into "chunks" which are of the same script (alphabet), language, direction, font face, font size, and variant (italic, bold, etc.). These could range from a single character to paragraph-length strings of text. These are fed to HarfBuzz::Shaper, along with flags, the font file to be used, and other supporting information, to create an array of output glyphs. Each element is a hash describing the glyph to be output, including its name (if available), its glyph ID (number) in the selected font, its x and y displacement (usually 0), and its "advance" x and y values, all in points. For horizontal languages (LTR and RTL), the y advance is normally 0 and the x advance is the font's character width, less any kerning amount. ๐Ÿ’…

Shaper's gonna do its lil detective work and figure out the script + text direction from the Unicode range, plus take a pretty solid guess at the language you're using. You can override the language if you want, but rn the script and text direction are locked in โ€” no override, bestie, sorry. ๐Ÿ’…

Super important note: the number of glyphs (array elements) is not always equal to the number of Unicode points (characters) in the chunk's text string! ๐Ÿ˜ญ Sometimes one character gets decomposed into several pieces (multiple glyphs), sometimes multiple characters get squished into a single ligature glyph, and characters can get reordered (esp. in Indic and Southeast Asian languages). Also, for Right-to-Left (bidirectional) scripts like the Hebrew and Arabic families, the text comes out in Left-to-Right order โ€” literally reversed from the input. ๐ŸŒˆ

With due care, you can manipulate a Shaper array in code. The elements are more or less independent of each other, so you can modify, rearrange, insert, or delete them. You might nudge a glyph's position using the 'dx' and 'dy' hash elements. The 'ax' value should be left alone so the wrong kerning doesn't get calculated โ€” but you might need to adjust the "advance x" value with one of these:

  • axs โ€” a value to be substituted for 'ax' (in points) โœจ
  • axsp โ€” a substituted value (percentage) of the original 'ax' ๐Ÿ’ซ
  • axr โ€” reduces 'ax' by the value (points). If it's negative, it increases 'ax' ๐ŸŽ€
  • axrp โ€” reduces 'ax' by the given percentage. Again, negative increases 'ax' ๐Ÿฆ‹
Caution: a given character's glyph ID is not necessarily the same between any two fonts! Fr fr. Like, an ASCII space (U+0020) might be "<0001>" in one font and "<0003>" in another (even one that's closely related!). And a U+00A0 required blank (non-breaking space) may be output as a regular ASCII space U+0020. So take care if you need to find a particular glyph in the array, especially if the number of elements don't match. ๐Ÿ‘€ Consider making a text string of "marker" characters (space, nbsp, hyphen, soft hyphen, etc.) and processing it through HarfBuzz::Shaper to get the corresponding glyph numbers. You may have to count spaces, say, to see where you could break a glyph array to fit a line.

The advancewidthHS() method takes the same inputs as textHS() does. Like advancewidth(), it returns the chunk length in points. Unlike advancewidth(), you cannot override the glyph array's font, font size, etc. ๐Ÿ™…โ€โ™€๏ธ

Once you've got your (possibly modified) array of glyphs, you feed it to the textHS() method to render it to the page. Remember this method handles only a single line of text โ€” it does not do line splitting or fitting, so that's on you to do manually rn. ๐Ÿ˜ฎโ€๐Ÿ’จ For Western scripts (e.g., Latin), that might not be too hard, but for other scripts that involve extensive modification of the raw characters, splitting words can get quite difficult โ€” though you still may be able to split at inter-word spaces. ๐Ÿ’–

A useful (but not exhaustive) set of functions is allowed by textHS(). Support includes direction setting (top-to-bottom and bottom-to-top directions, e.g., for Far Eastern languages in traditional orientation), plus explicit script names and language (depending on what support HarfBuzz itself gives). Not yet supported: stuff like discretionary ligatures and manual selection of glyphs (e.g., swashes and alternate forms). ๐Ÿ™ˆ

Currently, textHS() can only handle a single text string. We're looking at how fitting to a line length (splitting up an array) could be done, as well as how words might be split on hard and soft hyphens. At some point, full paragraph and page shaping could be possible. ๐Ÿ”ฎ


And that's a wrap on the whole page, bestie!! ๐ŸŽ€โœจ This was written against perl v5.42.0, dated 2026-01-17, and it's the PDF::Builder::Docs(3) page โ€” ily, go make something gorgeous, and remember: every single detail stayed exactly where it was. periodt. ๐Ÿ’…๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from