PDF::B...n_docs(3pm)

๐Ÿ“ฆ
version 3.028 ยท 3 versions
, in ubuntu resolute, ubuntu stonking

๐Ÿ’– NAME ๐Ÿ’–

PDF::Builder::Content::Column_docs โ€” the column text formatting system, bestie ๐Ÿ’…. This page lives in the User Contributed Perl Documentation (that's the 3pm in the header, iykyk โœจ).


okay so this whole little crew of routines is a sub-library that supports complex columnar output with high level markup languages ๐Ÿ’–. Right now you can define exactly one rectangular layout on a page, and user-defined content fills it up. Anything that couldn't fit inside the column confines gets handed back to you in an internal array format, and you can pass it to the next column() call to finish the formatting ๐Ÿซถ.

Future plans, fr fr: non-rectangular columns being definable, plus flow from one column to another on a page, plus column balancing ๐ŸŒˆ. Other possible enhancements include support for non-Western writing systems (e.g., bidirectional text, using the HarfBuzz library), proper word-splitting and paragraph shaping (possibly using the Knuth-Plass algorithm), and additional markup languages ๐Ÿ‘‘.


๐ŸŽ€ column ๐ŸŽ€

($rc, $next_y, $unused) = $text->column($page, $text, $grfx, $markup, $txt, %opts)

This method fills out a column of text on a page, returning any unused portion that could not be fit, and where it left off on the page ๐Ÿ’….

Tag names, CSS entries, markup type, etc. are case-sensitive (usually lower-case letters only). Like, you literally cannot give a <P> paragraph in HTML or a P selector in CSS styling. Not the vibe, it just won't work ๐Ÿ™ˆ.

  • $page is the page context. Currently, its only use is for page annotations for links ('md1' []() and 'html' <a>), so if you're not using those, you may pass anything such as undef for $page if you wish ๐Ÿ’–.
  • $text is the text context, so that various font and text-output operations may be performed. It is often, but not necessarily always, the same as the object containing the column method ๐Ÿ‘‘.
  • $grfx is the graphics (gfx) context. It may be a dummy (e.g., undef) if no graphics are to be drawn, but graphical items such as the column outline ('outline' option) and horizontal rule (<hr> in HTML markup) use it ๐Ÿ”ฅ. Currently, text-decoration underline (default for links, 'md1' []() and 'html' <a>) or line-through or overline use the text context, but may in the future require a valid graphics context ๐Ÿ˜ญ. Images (when implemented) will require a graphics context.
  • $markup is information on what sort of markup is being used to format and lay out the column's text:
    • 'pre' โ€” the input material has already been processed and is already in the desired form ๐ŸŽ€. $txt is an array reference to the list of hashes. This must be used when you are calling column() a second (or later) time to output material left over from the first call ๐Ÿ’ซ. It may also be used when the caller application has already processed the text into the appropriate format, and other markup isn't being used.
    • 'none' โ€” if none is specified, there is no markup in use. At most, a blank line or a new text array element specifies a new paragraph, and that's it ๐Ÿ“. $txt may be a single string, or an array (list) of strings.
      • The input txt is a list (anonymous array reference) of strings, each containing one or more paragraphs. A single string may also be given. An empty line between paragraphs may be used to separate the paragraphs. Paragraphs may not span array elements.
    • 'md1' โ€” this specifies a certain flavor of Markdown compatible with Text::Markdown. See the full description below ๐Ÿ‘€.
      • There are other flavors of Markdown, so other mdn flavors may be defined in the future, such as POD from Perl code ๐ŸŒธ.
    • 'html' โ€” this specifies that a large subset of HTML markup is used, along with some attributes and CSS โœจ.
      • Numeric entities (decimal &#nnn; and hexadecimal &#xnnn;) are supported, as well as named entities (&mdash; for example) ๐Ÿ’–.
      • The input txt is a list (anonymous array reference) of strings, each containing one or more paragraphs and other markup. A single string may also be given. Per normal HTML practice, paragraph tags should be used to mark paragraphs. Note that HTML::TreeBuilder is configured to automatically mark top body-level text with paragraph tags, in case you forget to do so, although it is probably better to do it yourself, to maintain more control over the processing ๐Ÿ‘‘. Separate array elements will first be glued together into a single string before processing, permitting paragraphs to span array elements if desired ๐Ÿฆ‹.
    • Other input formats โ€” there are other markup languages out there, such as HTML-like Pango, nroff-like man page, Markdown-like wikimedia, and Perl's POD, that might be supported in the future (provided there are supported Perl libraries for them) ๐Ÿคž. It is very unlikely that TeX or LaTeX will ever be supported, as they both already have excellent PDF output ๐Ÿ’€.
      • PDF::Builder currently only supports the markup languages described above. If you want to use something else (e.g., Perl's POD, or man format, or even MS Word or some other WYSIWYG format), you will need to find a converter utility to convert it to a supported flavor of Markdown or HTML. Many such converters already exist, so take a look (although you may well have to do some cleanup before column() accepts the resulting HTML as input) ๐ŸŽ€.
      • Perhaps in the future, PDF::Builder will directly support additional formats, but no promises ๐Ÿ™ˆ.
  • $txt is the input text: a string, an array reference to multiple strings, or an array reference to hashes. See $markup for details ๐ŸŒŸ.
  • %opts Options โ€” a number of these are, despite the name, mandatory. Yes bestie, the name is straight-up lying to you, iconic behavior ๐Ÿ’….
    • 'rect' => [x, y, width, height] โ€” this defines a column as a rectangular area of a given width and height (both in points) on the current page ๐Ÿ“. In the future, it is expected that more elaborate non-rectangular areas will be definable, but for now, a simple rectangle is all that is permitted. The column's upper left coordinate is "x, y" โœจ.
      • The top text baseline is assumed to be relative to the UL corner (based on the determined line height), and the column outline clips that baseline, as it does additional baselines down the page (interline spacing is "leading" multiplied by the largest "font_size" or image height needed on that line) ๐Ÿซถ.
      • Currently, 'rect' is required, as it is the only column shape supported ๐Ÿ‘‘.
    • 'relative' => [ x, y, scale(s) ] โ€” 'relative' defaults to [ 0, 0, 1, 1 ], and allows a column outline (currently only 'rect') to be either absolute or relative. "x" and "y" are added to each "x,y" coordinate pair, after scaling ๐Ÿ’ซ. Scaling values:
      • (none) โ€” the scaling defaults to 1 in both x and y dimensions (no change).
      • scale (one value) โ€” the scaling in both the x (width) and y (height) dimensions uses this value.
      • scale_x, scale_y (two values) โ€” there are two separate scaling factors for the x dimension (width) and y dimension (height).
      • This permits a generically-shaped outline to be defined, scaled (perhaps not preserving the aspect ratio) and placed anywhere on the page ๐ŸŒˆ. This could save you from having to define similarly-shaped columns from scratch multiple times. If you want to define a relative outline, the lower left corner (whether or not it contains a point, and whether or not it's the first one listed) would usually be 0, 0, to have scaling work as expected. In other words, your outline template should be in the lower left corner of the page ๐ŸŒธ.
    • 'start_y' => $start_y โ€” if omitted, it is assumed that you want to start at the top of the defined column (the maximum "y" value minus the maximum vertical extent of this line) ๐Ÿ”ฅ. If used, the normal value is the "next_y" returned from the previous column() call. It is the deepest extent reached by the previous line (plus leading), and is the top-most point of the new first line of this column() call.
      • Note that the "x" position will be determined by the column shape and size (the left-most point of the baseline), so there is no place to explicitly set an "x" position to start at ๐Ÿ™ˆ.
    • 'font_size' => $font_size โ€” this is the starting font size (in points) to be used. Over the course of the text, it may be modified by markup โœจ. The default is 12pt. It is in turn overridden by any CSS or HTML font size-settings ๐Ÿ’….
      • The starting font size may be set in a number of ways. It may be inherited from a previous $text->font(..., font-size) statement; it may be set via the "font_size" option (overriding any font method inheritance); it may default to 12pt (if neither explicit way is given). For HTML markup, it may of course be modified by the "font" tag or by CSS styling "font-size". For Markdown, it may be modified by CSS styling ๐ŸŽ€.
    • 'font_info' => $string โ€” this permits the user to specify the starting font used in column() (body font-family, font-style, font-weight, color) ๐Ÿ’œ. column() will pick up any font already loaded ($text->font($font, $size);, or using FontManager), and use that as the "current" font ๐Ÿ‘‘. If no font has been loaded, and no other instructions are given, the FontManager default (core Times-Roman) will be used ๐ŸŒŸ.
      • The "font_info" option for column() may be given to override either of the two above methods. You may specify a $string of '-fm-' to instruct column() to use the FontManager "default" font (Times face core font). Or, you may pick a font face known to FontManager (added by user code if not one of the 28 core fonts), and optionally give it style and weight: $string of 'face:style:weight:color'. The style defaults to 'normal' (non-italic), or 'normal' or '0' may be given. For italics, use 'italic' or '1'. The weight defaults to 'normal' (unbolded weight), or 'normal' or '0' may be given. For bold (heavy) text, use 'bold' or '1'. Finally, a color may be given ๐Ÿฆ‹.

๐Ÿงš bestie this is only part 1 of 7โ€ฆ brace yourself, the rest is coming ๐Ÿ’–

At the end of the day, the "style" option on column() is your override button โ€” you can hand it something like 'style'=>{ body { font-family:... } and it'll set the initial current font for you. ๐Ÿ’… But bestie, remember the golden rule: like everything font-related that column() touches, the 'face' (aka the family) has to already be known to FontManager, which means loading it explicitly with add_font() unless it's one of the 28 core fonts. And keep in mind the first 14 fonts are standard PDF, while the second 14 are normally shipped with Windows (but not always with other operating systems). ๐Ÿ™ˆ

  • 'marker_width' => $marker_width
  • 'marker_gap' => $marker_gap โ€” the width of the gutter sitting to the left of a list item, basically the VIP lounge where (on the item's first line) the marker lives. That marker holds the symbol (for bulleted/unordered lists) or the formatted number plus the "before" and "after" text (for numbered/ordered lists). Both get a single space (marker_gap = 1em) before the item text even starts. The number is a length, in points.

The default is 1 em (1 times the font_size you passed to column()), and ngl it does not get adjusted when font_size changes in the markup โ€” that's on purpose, so lists stay consistently indented. Usually that's totally fine for unordered (bulleted) lists and single-digit ordered (numbered) lists, though you might need to widen it for two- or three-digit numbered ones. โœจ And an explicit value you pass in also doesn't budge โ€” the gutter width for the marker stays the same across all lists (keeping them aligned, slay). If you're planning exceptionally long markers, like an ordered list of years in Roman numerals, e.g., (MCMXCIX), you may wanna make that gutter a bit wider.

You can also hand it a value for marker_gap โ€” that's the gap between the ($marker_width-wide) marker and the start of the list item's text. Default is $fs points (1 em), set by the font_size in the markup.

The list-style-position CSS property can be given as the standard 'outside' (the default) or 'inside', or โ€” as an extension to CSS โ€” to indent the left side of the second, third, etc. <li> lines somewhere between the 'inside' and 'outside' positions. And be sure to consider the "_marker-align" extended property, which can left, center, or right (default) align the marker inside the marker_gutter. ๐Ÿ‘‘

  • 'leading' => $leading โ€” the leading ratio used all throughout the column text. The position from $x, $y through $x + width is assumed to be the first text baseline. The next line down lands at $y - $leading*$font_size. If font_size changes for any reason over the course of the column, that baseline spacing (leading * font_size) changes right along with it. Default leading ratio is 1.125 (that's 12.5% added to the font).
  • 'para' => [ $indent, $top-margin ] โ€” when you kick off a new paragraph, these are the default indentation (in points) and the extra vertical spacing for a top margin on a paragraph. Otherwise the default is [ 1*$font_size, 0 ] (1em indent, 0 additional vertical space). Either one can be overridden by the appropriate CSS settings. And yes, you can define an outdent with a negative indentation value. These apply to all $markup types. ๐Ÿฆ‹
Heads up: at the top of a column, any top margin (not just for paragraphs) gets ignored. Periodt.
  • 'outline' => "color string" โ€” you may optionally ask for the column to be outlined in a given color, which is super handy for debugging fitting problems. Fair warning: this requires that the graphics context be provided to column().
  • 'color' => "color string" โ€” the color to draw the text (or rule or other graphic) in. Default is black (#000000).
  • 'style' => "CSS styling" โ€” you can define CSS (selectors and property lists) to override the built-in CSS defaults. These get applied for the whole column() call. You can use this, or style tags in 'html', but for 'none' or 'md1' you'll need this method to set styling. Peep the "font_info=>" option too if you wanna set initial font settings.

Note that โ€” unlike the "style=" attribute in HTML tags โ€” the "style=>" option is formatted like a <style> tag, meaning selector { property: value;... }. If you want to set global values, use the body selector. ๐Ÿ’–

  • 'substitute' => [ [ 'char or string', 'before', 'replace', 'after'],... ] โ€” when a certain Unicode code point (character) or string is found, insert the before text before the character, replace the character or string with the replace text, and insert the after text after the character. This can make it way easier to inject HTML code (font, color, etc.) into Markdown text, in case the settings and character you want can't be produced by your Markdown editor. This applies to both 'md1' and 'html' markup, and multiple substitutions can be defined via multiple array elements. If you want to leave the original character or string itself unchanged, just define the replace text to be the same as 'char or string'. 'before' and/or 'after' text may be empty strings if you don't want to insert some sort of markup there. ๐ŸŒธ

Example: to insert a red cross (X-out) and green tick (check) mark

'substitute' => [
  [ '%cross%', '<font face="ZapfDingbats" color="red">', '8', '</font>' ],
  [ '%tick%', '<font face="ZapfDingbats" color="green">', '4', '</font>' ],
]

should change %cross% in Markdown text ('md1') or HTML text ('html') to <font face="ZapfDingbats" color="green">8</font> and similarly for %tick%. This happens after the Markdown is converted to HTML (but before the HTML is parsed), so make sure your macro text (e.g., %tick%) isn't something Markdown will try to interpret on its own! Also, Perl's regular expression parser seems to get upset with some characters, such as |, so don't use them as delimiters (e.g., |cross|). You don't have to wrap your macro name in delimiters, but it can make the text structure clearer, and may be necessary in order not to do substitutions in the wrong place. ๐Ÿ˜ญ

  • 'state' => \%state โ€” this is the state of processing, including (in particular) information on all the requested references (<a>, <_ref>) and targets (<_reft> and specific id's). Before use, it must be created and initialized. During multiple passes across multiple column() calls, 'state' preserves all the link information. It can even preserve information across the creation of multiple related PDFs, though that may require writing and reading back from a file. There's no information in 'state' that a user is likely to care about (i.e., it's all internal data). If 'state' isn't given, it will (in most cases) be impossible to define various kinds of links (including cross references). A URL link to a browser does not need 'state', but every other kind of link to this or other PDF files does. ๐Ÿ”—
  • 'page' => [ $ppn, $extfile, $fpn, $LR, $bind ] โ€” this array of values gives column() the info it needs for generating links (both goto and pdf annotations), and (TBD) left- and right-hand page processing, including how much to shift column() definitions to the outside of the page for binding purposes (TBD). The link info goes like this:
    • $ppn โ€” the Physical Page Number of the page currently being generated. It's always an integer greater than 0, taking a value 1,2,3,... You need it if this page is used as the target for an external (across PDFs) link, using a physical page number and not a Named Destination. Remember to increment it every time the code calls the page() method. It may be left undefined if you're sure you're never gonna generate a link (via pdf call, not using a Named Destination) to this PDF file from another PDF.
    • $extfile โ€” describes the external path, filename, and extension of this PDF being created. Needed if this page is used as the target for an external (across PDFs) link. Remember that this is the final location and name of where this file will live when in use โ€” not necessarily where it's being created at this very moment! It may be left undefined or given a random name if you're sure you're never gonna generate a link (via pdf call) to this PDF file from another PDF.
    • $fpn โ€” the Formatted Page Number of the page being generated. In the simplest case it equals the Physical Page Number, but often you'll wanna get fancy with numbering โ€” like a prefix for an appendix ('C-2', 'Glossary-5', etc.), lowercase Roman numerals in the front matter, all that. You might even want to carry one single sequence of decimal page numbers across multiple PDFs, thus starting at something other than "1". If you leave it undefined, certain kinds of links and cross reference formats (where the formatted page number is shown) will not be possible.
    • $LR โ€” says whether it's a left-hand page or a right-hand page, for purposes of formatting layout and shifting the column() outline left or right (towards the "outside" of the page) to allow binding space. If undefined, it defaults to an 'R' right-hand page. This ability is currently unused.
    • $bind โ€” the number of points to shift the column() coordinates towards the "outside" of the page for purposes of binding multiple pages together, whether left-right alternation or all right-hand pages (e.g., punched for a notebook or spiral binding, or just stapled on the inside, or glued or sewn into a paperback or hard-cover binding). If undefined, the default is 0. This ability is currently unused. ๐ŸŽ€
  • 'restore' => *flag* โ€” okay so this integer flag decides what kind of cleanup column() does on its way out, i.e. whether it restores the font state or nope. And "font state" here means face, bold-or-normal weight, italic-or-normal style, size, and color. All the good stuff. ๐ŸŒˆ

What it actually does depends on your return code, so buckle up bestie, there are two cases:

for rc = 0 (all input markup was used up, without running out of column):

  • restore => 0 โ€” the default ๐Ÿ’–. When it exits, column() tries to put the state back to what you'd see if there were yet more text to be output. Ngl, that's not necessarily the same as what you'd see if the entire state got restored to entry conditions. The whole intent here is that you can immediately make another column() call using whatever font state the previous call left lying around โ€” as if the two calls' markup inputs had just been concatenated. ๐Ÿงต
  • restore => 1 โ€” this value of "restore" commands that no change at all be made to the font state. So column() exits with the font state still sitting in the last text output. Whether that's a vibe or a disaster is very much situational, especially if that last text output left your text in a state you did not expect ๐Ÿ™ˆ.
  • restore => 2 โ€” this value of "restore" attempts to bring the font state all the way back to what it was upon entry to the routine, as if it had never been called ๐Ÿ•ฐ๏ธ. But heads up: if column() was called with no global font settings, that can't be undone โ€” although the color can be changed back to its original state, usually black.

CAUTION: ๐Ÿšจ The Font Manager is not synchronized with whatever state the font is returned to. You should not request the 'current' font โ€” instead explicitly set it to a specific face, etc., which resets 'current'. Periodt.

for rc = 1 (ran out of column space before all the input markup was used up):

  • restore => 0 โ€” the default. On exit, no changes get made to the font state. Since the code is mid-output, the font state is kept the same, so the next column() call (for the overflow) can pick up where the previous call left off, font-state-wise ๐Ÿซถ. It is equivalent to "restore = 1".
  • restore => 1 โ€” this is the same as "restore = 0". Literally the same. ๐Ÿ’€
  • restore => 2 โ€” this value of "restore" attempts to bring the font state all the way back to what it was upon entry to the routine, as if it had never been called. Note that if column() was called with no global font settings, that can not be undone, although the color can be changed back to its original state, usually black.

CAUTION: ๐Ÿšจ Again, the Font Manager is not synchronized with whatever state the font is returned to. You should not request the 'current' font, but should instead explicitly set it to a specific face, etc., which resets 'current'.


๐Ÿ“ฆ Data returned by this call ๐Ÿ“ฆ

If there is more text than can be accommodated by the column size, the unused portion is returned, with a return code of 1 ๐Ÿ‘€. It's an empty list if all the text could be formatted, and the return code is 0. "next_y" is the y coordinate where any additional text (column() call) could be added to a column (as "start_y") that wasn't completely filled. That would be at the starting point of a new column (i.e., the last paragraph is ended).

Yo, important: the application code should check if this position is too far down the page (in the bottom margin) and not blindly use it! ๐Ÿ™…โ€โ™€๏ธ Also, as 'md1' is first converted to HTML, any unused portion will be returned as 'pre' markup, rather than Markdown or HTML. Be sure to specify 'pre' for any continuation of the column (with one or more additional column() calls), rather than 'none', 'md1', or 'html'. Write that down ๐Ÿ“.
  • $rc โ€” the return code. ๐ŸŽซ
    • '0' โ€” a return code of 0 indicates that the call completed, while using up all the input $txt. It did not run out of defined column space. โœ…

NOTE: if "restore" has a value of 1, the column() call makes no effort to "restore" conditions to any starting values. If your last bit of text left the "current" font with some "odd" face/family, size, italicized, bolded, or colored โ€” that is exactly what will be used by the next column call (or other PDF::Builder text calls) ๐Ÿ’…. This is done on purpose, so you can easily chain from one column to the next without having to manually tell the system what font, color, etc. you want to return to. On the other hand, in some cases you may want to start from the same initial conditions as usual. You may want to add get_font(), font(), fillcolor(), and strokecolor() calls as necessary before the next text output, to get the expected text characteristics. Or, you can simply let "restore" default to 0 to get the same effect. Either way, slay ๐Ÿซถ.

  • '1' โ€” a return code of 1 indicates that the call completed by filling up the defined column space. It did not run out of input $txt. You will need to make one or more calls with empty column space (to fill), to use up the remaining input text (with "pre" $markup) ๐Ÿ”.

If "restore" defaults to 0 (or is set to 1), the text settings in the "current" font are left as-is, so that whatever you were doing when you ran out of defined column (as regards to font face/family, size, italic and bold states, and color) should automatically be the same when you make the next column() call to make more output. Seamless. โœจ

  • Additional return codes may be added in the future, to indicate failures of one sort or another. ๐Ÿ”ฎ
  • $next_y โ€” the next page "y" coordinate to start at, if using the same column definition as the previous column() definition did (i.e., you didn't completely fill the column, and received a return code of 0). In that case, $next_y would give the page "y" coordinate to pass to column() (as "start_y") to start a new paragraph at. ๐Ÿ“

If the return code $rc was 1 (column was used up), the $next_y returned will be -1, as it would be meaningless to use it. ๐Ÿšซ

  • $unused โ€” this is the unused portion of the input text (return code $rc is 1), in a format ("pre" $markup) suitable for input as $txt. It will be a reference to an array of hashes ๐Ÿ—‚๏ธ.

If $rc is 0 (all input was used up), $unused is an empty anonymous array. It contains nothing to be used. ๐Ÿซ™


๐Ÿ’พ Special notes on saving and restoring the font ๐Ÿ’พ

Okay so it is important to let column() know what font face (font-family), weight, and style to use, so it can switch between normal, bold, and italic as desired. There are several methods to explicitly select a font face (font-family) and its variants (weight, style) upon entry to column():

  1. Use the "font_info" option to "column", including -fm- (default) to use FontManager's default font (core Times-Roman).
  2. Use the "style" option to column() to override the body default CSS.
  3. If using HTML or Markdown, add a <style> tag to the beginning of the text markup, in order to set the body CSS (as with "style").

All of these methods will set the body's font. ๐Ÿ‘‘

If nothing special is done, the font selection upon entry to column() will default to using the default FontManager settings (core Times-Roman, equivalent to 'font_info'=>'-fm-'). "font_info" may also be explicitly set to specify the body text font-family (optionally also style, weight, and color) ๐ŸŽจ.

'font_info'=>'-ext-' may be given to tell FontManager to pick up an already-loaded font in this text context. It will label that font -external- and use it as the current font. However, be aware that if doing this, column() will not know the actual face (font-family) of whatever font this is, and thus can not change the font-weight (bold) or font-style (italic). These change requests will be ignored. ๐Ÿ™ˆ If no font is already loaded, the FontManager's default font (-fm- core Times-Roman) will be selected (and no -external- font defined).

Whatever way is used to specify the body font-family on the command line, it may be overridden by a <style> tag or 'style'=> command line CSS specification. ๐Ÿ‘€

Once column() has already been called within a given text context, whatever font is in force at the end of the call will be preserved by the text context, available to be picked up by the next column() call with 'font_info'=>'-ext' within this text context. column() will still not know the font-family, since this information is not carried in the text context! ๐Ÿ˜ญ

Note that a text context is limited to a single page of a PDF, at most (it must be defined by the $page->text() call, and is reset with each new page). The user code may of course choose to load a new font externally to column(), in order to use that one upon entry. An -external- font still cannot change style or weight. ๐Ÿงฑ

Any font "face" used must be first registered with FontManager. The standard core fonts (as well as Windows extensions) are preregistered. โญ If user code loads an arbitrary font outside of column(), it will only be known as -external- (as described above). column() calls (including CSS font-family) only recognize registered faces, so it knows where to find the font file and other information, and can cache the loaded font ๐Ÿ—ƒ๏ธ. It can keep track of which font is currently being used, and know how to set bold and italic variants. Iconic. ๐Ÿ‘‘

When you reach the end of your defined column (and the text source isn't exhausted yet ๐Ÿ˜ญ), all the open tags get preserved, so the next column() call (with pre formatting) can pick up with the same font settings as before. Slay. But bestie, this works only as long as the complete font description is set in the tags (including the face). If the font face isn't given in the tags, it will not be known, and bold and italic will likely not work at the next change. ๐Ÿ™ˆ And if the text is sitting in the middle of a highlighted phrase (bold, italic, or a different font), that particular font should be picked up again. However, the body font face and variant may not be correctly resumed if it is assumed that the proper font has been inherited by the next column() call. Explicitly setting the body font should allow the font to return to a known starting condition, although it is possible that (based on nesting of font changes at the column break) other aspects might be incorrect. ๐Ÿ’€

To summarize, the best practice is to register (add_font) to FontManager any fonts you wish to use, and then explicitly use font_info or style to let column() know what the base font is for your text. This is better than externally loading a font and depending on its being inherited from the text context โ€” which may in turn leave it in some other state after a column() call, plus you wouldn't be able to change bold and italic. ๐Ÿ’…


โœจ Markup supported โœจ

pre (already formatted from another format) ๐Ÿ“ฆ

This is an internal format, essentially the output from HTML::TreeBuilder. As this data is consumed by output, it is removed from the array. If any is left over when the column is filled, it is returned to the user, and may be used in a 'pre' format call to column() to finish the job. ๐Ÿซถ

If you wish to manually generate 'pre' format data, you may do so โ€” although it's usually easier to use a higher level markup such as 'md1' or 'html'.

none ๐Ÿ˜

This format simply has empty lines separating paragraphs. Otherwise it has no markup. That's it, that's the whole vibe.

md1 (Markdown) ๐ŸŒธ

This is the version of the Markdown language supported by the Text::Markdown library. It is converted into the equivalent HTML and then processed by HTML::TreeBuilder. โœจ

Standard Markdown ๐Ÿ“

  • * or _ produces italic text
  • ** produces bold text
  • *** produces bold+italic text ๐Ÿ”ฅ
  • * (in column 1) produces a bulleted list
  • 1. (2., 3., etc. if desired) in column 1 produces a numbered list 1., 2., etc.
  • # produces a level 1 heading. ## produces a level 2 heading, etc. (up to ###### level 6 heading)
  • ---, ===, or ___ produces a horizontal rule
  • ~~ enclose a section of text to be line-through'd (strike-out)
  • [label](URL) external links (to HTML page or within this document, see <a> for URL/href formats)
  • [label][n] reference-style links โ€” NOT currently supported ๐Ÿšซ
  • [label][^n] footnote-style links โ€” NOT currently supported ๐Ÿšซ
  • ` (backticks) enclose a "code" format phrase
  • ``` (backticks) enclose a "code" format block โ€” NOT currently supported ๐Ÿšซ
  • ![alt text](path_to_image) image โ€” NOT currently supported ๐Ÿšซ
  • table entries with | and - (or HTML tags) โ€” NOT currently supported ๐Ÿšซ
  • superscripts (^) and subscripts (~) (or HTML tags) โ€” NOT currently supported ๐Ÿšซ
  • definition lists with : โ€” NOT currently supported ๐Ÿšซ
  • task lists - [ ] โ€” NOT currently supported ๐Ÿšซ
  • emojis will NEVER be supported. We have a perfectly good alphabet. ๐Ÿ˜ค
  • highlighting (inline == or HTML <mark>) โ€” NOT currently supported ๐Ÿšซ

HTML (see below) may be mixed in as desired (although not within "code" blocks marked by backticks, where <, >, and & get turned into HTML entities, disabling the intended tags). Markdown will be converted into HTML, which will then be interpreted into PDF. Note that Text::Markdown may produce HTML for certain features that is not yet supported by HTML processing (see the 'html' section below). Let us know if you need such a feature! ๐Ÿ’Œ

The input txt is a list (anonymous array reference) of strings, each containing one or more paragraphs and other markup. A single string may also be given. Per Markdown formatting, an empty line between paragraphs may be used to separate the paragraphs. Separate array elements will first be glued together into a single string before processing, permitting paragraphs to span array elements if desired. ๐Ÿงฉ

Extended Markdown ๐Ÿฆ‹

CSS (Cascading Style Sheets) may be defined for resulting HTML tags (or "body" for global settings), via the "style=>" column() option. You may also prepend a "<style>" HTML tag, with CSS markup, to your Markdown source. ๐Ÿ’–

Standard Markdown permits an 'id' to be defined in a heading, by suffixing the text with "{#id_name}". This is equivalent to "id="id_name"" in HTML markup. Although Text::Markdown does not currently support it, column() implements this way of defining a target's id, and in fact extends it to permit an id to be defined for any tag with child text. ๐Ÿ‘‘

Markdown is further extended by column() to permit a 'title' to be defined for any tag with child text, by use of "{^title_text}". Note that this 'title' is the link title to be used, not browser style "hover" popup text. It is the equivalent of "title="title_text"" in <a> or <_ref> HTML markup. Any link tag may define the PDF "fit" to use at the target, by "{%fit_type,parm(s)}" or "fit="fit_type,parm(s)"" in <a> or <_ref> HTML markup. ๐ŸŽฏ

There are other HTML equivalents defined by Standard Markdown which may not be implemented (converted) by Text::Markdown. Among these are "~~" line-through (strike-out) and "===" horizontal rule, which have been fixed with post-processing of the generated HTML. Let us know if you find any more such cases, and we may be able to extend the functionality of 'md1' formatting, or if necessary, implement 'md2' format to use a different library. By default, Text::Markdown disables extended <_tagname> calls, but these all should be handled properly in post-processing. There are also Markdown features that may be implemented by Text::Markdown, but the resulting HTML is not supported by column() (yet). If you are missing a needed feature, ask about our moving it up on the priority list. ๐Ÿ“‹

html (HTML) ๐ŸŒˆ

This is the HTML language to be processed by the HTML::TreeBuilder library. It is processed into an array of tags and text strings ('pre' format), which is interpreted by column(). A substantial subset of CSS (Cascading Style Sheets) is also interpreted by column(), although selectors are primitive compared to what a browser supports. ๐Ÿ’€

Standard HTML tags ๐ŸŽ€

A good many HTML tags are implemented, although not all of them:

  • <i> or <em> produces italic or slanted/oblique text, where available through FontManager
  • <b> or <strong> produces bold text, where available through FontManager
  • <s>, <strike>, and <del> produce text line-through (strike-out or strike-through)
  • <u> and <ins> produce underlined text
  • <code> produce 'code'-style fixed-pitch text
  • <h1> through <h6> produce level 1 through 6 headings and subheadings
  • <hr> produce a horizontal rule
    • The "width="length"" attribute gives a length (width, in pixels) less than the full column width, and "size="height"" attribute gives the height (thickness) of the rule. CSS properties "width" and "height" are the equivalent, permitting other units of measure.
    • The default "width" is the full column, and "size" (thickness) of the line is 0.5pt.
    • Note that most browsers default to center alignment if the width is less than the full column, which is the default here. The align attribute is available here to specify left alignment of the rule, center alignment (default), or right alignment. Note that this attribute is deprecated in the HTML standard, however, PDF::Builder does not yet support the suggested CSS methods (properties) for doing this. โš ๏ธ
  • <blockquote> produces a quotation block, a paragraph indented on both sides and of smaller font size
  • <p> produces a paragraph
  • <font face="font-family" color="color" size="font-size"> as selecting font face, color, and size (considered better to use CSS)
  • <span> needs a style= attribute with CSS to do anything useful
  • <ul> produces an unordered (bulleted) list. The "type" attribute to override the default marker is supported
  • <ol> produces an ordered (numbered) list. "start=", "type=", and "reverse=" attributes are supported to override the default starting count, format, and direction
  • <li> adds a list item to a list (ul, ol, or _sl). The "value=" attribute may be given to override the ordered list counter, and the "type=" attribute may be given to override the default marker type
  • <a href="URL"> produces a link to a browser URL or to this or another PDF document. "URL" is anchor/link, web page URL or this document target "#p[-x-y[-z]]" (p is physical page number), or path to external PDF document before the #. ##NamedDest and extPDF##NamedDest are supported. Otherwise treat as an "id" (id=).
    • href="protocol://..." a link will be generated to an HTML browser or (for protocol "mailto") an email client. The tag remains <a> and a's CSS properties are used. Otherwise, internally the tag will be changed to <_ref>, whose CSS properties will be used
    • href="#p" or "#p-x-y" or "#p-x-y-zoom" a link will be generated to a physical page number "p" in this document. Optionally, an x-y location on the page (for fit="xyz") may be given with an optional zoom factor
    • "PDF_document_path#p" etc. a link will be generated to a physical page number "p" in an external document. Note that the path and filename must point to either an absolute address or to one relative to where this PDF will be located
    • "##Named_destination" a link will be generated to a Named Destination in this document (see <_nameddest>). Note that the Named Destination itself will define the "fit" to be used
    • "PDF_document_path##Named_destination" a link will be generated to a Named Destination defined in an external document. Note that the path and filename must point to either an absolute address or to one relative to where this PDF will be located, and that the Named Destination itself will define the "fit" to be used
  • #id_name or id_name โ€” drop one of these and a link gets generated to the id of that name, bestie. That target can live in this PDF doc or in another one (as long as it all got processed in the same run). โœจ Big warning though: if you start it with a #, the name must not be all decimal digits, or all decimal digits followed by a - and other parts โ€” because that pattern gets interpreted as a #p physical page link! ๐Ÿ’€

So the link's child text, if it's not empty, becomes the resulting link text. If there isn't any, then whatever title attribute or {^title text} came along with the target (like a <_reft>) gets used instead. And if still nothing? Then any native "child text" (like a heading's own text content) steps up. ๐Ÿซถ

If you're working in HTML markup, any tag that has an id= can be a target. Especially for Markdown use, any tag with child text (and not just a heading's text, okay) may include {#idname} so it gets parsed out as id="idname" โ€” and now it's usable as a target. ๐Ÿ’…

You can also hand an explicit fit= attribute to the <a> tag, to specify the page fit the PDF Reader uses at the target location. For example, fit="xyz,45,600,1.5" puts the window's upper left corner at 45,600 with a 150% zoom factor. ๐Ÿ” For Markdown usage, {%xyz,45,600,1.5} in the link text (title) is the equivalent (xyz fit, at 45,600, zoom 1.5). For a page number target (#p), you can add -x-y (and optionally -zoom) for the same effect (xyz fit). null or undef may be used for undefined items. For any fit, %x and %y may be used for the target's x and y location, so you use the actual target location instead of a fixed location on a page. ๐ŸŒธ

  • In plan, but not yet implemented ๐Ÿšง
    • 'pre' (preformatted blocks),
    • 'cite', 'q', 'samp', 'var', 'kbd' (various highlights),
    • 'big', 'bigger', 'small', 'smaller' (various font sizes),
    • 'img' (image display),
    • 'br', 'nobr' (line break, line break suppression),
    • 'sup', 'sub' (superscript and subscript),
    • 'dl', 'dt', 'dd' (definition lists),
    • 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td' (tables),
    • 'mark' (highlightingโ€ฆ requires ability to set background color),
    • 'div' (handle div's in some manner),
    • 'center',
    • 'caption', 'figure', 'figcap' (optional sub- and super-sections)
    • 'nav', 'header', 'footer', 'address', 'article', 'aside', 'canvas', 'section', 'summary' (possibly some sectioning)

Numbered entities (both decimal and hexadecimal) are supported, and so are named entities (like &mdash;)! Lists get a gutter (for the marker) that's marker_width points wide, plus a gap between the marker's field and where the item's text starts (marker_gap points wide), so list alignments stay consistent across the whole call. ๐Ÿ‘‘


Extended HTML tags ๐Ÿฆ‹

A bunch of HTML-like tags whose names start with an underscore _ have been implemented to do various little jobs. The lineup:

  • <_ref> โ€” defines an alternative form of a link to this or another PDF document (not for URLs to HTML or email โ€” for that, use <a>). The attribute tgtid= is required, and it's equivalent to <a>'s href=. The attribute title= is optional, and provides title text for the link. The attribute fit= is optional, and provides a non-default fit for the target page (heads up: a Named Destination target provides its own fit). For a 'fit' of 'xyz', you may use '%x' for the x value and '%y' for the y value to use the current positions rather than fixed values. And ngl: any <a> link that isn't pointing at a browser or email client gets internally converted to <_ref>, so CSS for formatting the link text (title) will be defined under _ref. ๐Ÿ˜Œ
  • <_reft> โ€” defines a target id for a link (via the id= attribute), especially if an existing id isn't conveniently at hand. See id= attributes in most HTML tags, and {#id_name} for many Markdown "tags". An optional attribute title= may be given to provide a default link text for the link (<a> or <_ref>) referring to this id. ๐ŸŽฏ
  • <_nameddest> โ€” defines a Named Destination inside this document, reachable via a ## format link href, or from some PDF Readers on the command line (one or more of #ND_name, #name=ND_name, or #nameddest=ND_name will usually work, when appended to the PDF file path and name, just like with HTML anchor id's). The attribute name="ND_name" is required, to globally name this Destination (the character set allowed and the maximum length vary among Readers!). The optional attribute fit="fit_info" may be given to specify a non-default "fit" when it's invoked. It's the type of fit (e.g., xyz, fith, etc.) followed by any location values that fit requires, all separated by commas. "xyz,%x-100,$y+100,null" is the default fit. ๐Ÿ’ซ
  • <_marker> โ€” gives you a place to specify, via CSS, on a per-list-item basis, overrides to the default marker settings (see also the _marker-* CSS extensions below). If you skip it, the same HTML list markers and CSS properties are used for every list item (per usual practice). The whole point of this tag is to allow styling changes like font, color, and alignment for one individual list item (<li>). Place this tag immediately before the <li> it applies to. ๐ŸŽ€
  • <_move> โ€” the way to explicitly move the current write point left or right. Attribute x="value" is an absolute move (in points), while attribute dx="value" is a relative move from the current write point. Along with the text-align CSS property, this can give you a way to fine tune text position within a column line. ๐Ÿ“

An x value that's a bare number (no units) is assumed to specify points, equivalent to units of pt. The unit may also be %, where 0% is the left end of the column, 50% is the center, and 100% is the right end. A dx value that's a bare number (no units) is assumed to specify points, equivalent to units of pt. The unit may also be %, a fraction of the column width to move (+ right, - left). Note that results are unpredictable if you move beyond the edge of the column in either direction. ๐Ÿ˜ญ

  • <_sl> โ€” provides a simple list, very similar to an unordered list, except for no list markers. ๐ŸŒˆ
  • In plan, but not yet implemented ๐Ÿšง
    • '_k' (manual kerning control)
    • '_ovl' (overline, similar to underline and line-through)
    • '_lig' (specify a particular ligature to use here)
    • '_nolig' (suppress ligatures by HarfBuzz)
    • '_swash' and '_altg' (specify a particular alternate glyph to use here)
    • '_sc' (specify "small caps" font variant, with forced end after N words)
    • '_pc' (specify "petite caps" font variant, with forced end after N words)
    • '_dc' (specify "dropped cap" font variant in some manner, also CSS)
    • ? (specify conditional and unconditional page breaks)

Standard CSS properties and values โœจ

CSS (Cascading Style Sheets) may be defined for HTML tags (or body for global settings), via the style=> column() option. You may also add one or more <style> HTML tags, with CSS markup, into your HTML source. Those entries get combined into a global style section. ๐Ÿ’–

<style> tags may go in an optional <head> section, or inside the <body>. In the latter case, style tags get pulled out of the body and added (in order) on to the end of any style tag(s) defined in a head section. Multiple style tags get condensed into a single collection (later definitions of equal precedence overriding earlier ones). These stylings have global effect, as though they were defined in the head. As with normal CSS, the hierarchy of a given property (in decreasing precedence) is:

  • appearance in a style= tag attribute
  • appearance in a tag attribute (possibly a different name than the property)
  • appearance in a #IDname selector in a <style>
  • appearance in a .classname selector in a <style>
  • appearance in a tag name selector in a <style>

Selectors are quite simple: a single tag name (e.g., body), a single class (.cname), or a single ID (#iname). There are no combinations (e.g., p.abstract or ol, ul), no hierarchies (e.g., ol > li), no specified number of appearance, no pseudotags, none of those other complications you'd find in a browser's CSS. Sorry! ๐Ÿ™ˆ

Length Measures ๐Ÿ“

Property values that are lengths (including font-size) may have units of pt (points, 72 to the inch), px (pixels, currently fixed at 78 to the inch), in (inches), cm, mm, em (equal to font-size), en (0.5em), and ex (currently 0.5em, but in the future may be able to query the font's actual x-height). % (percentage) of the current font-size (in most cases, unless otherwise noted) is allowed, although some properties may in the future support % of the enclosing object size. Sizes may be negative numbers (useful only for margins). ๐Ÿงš

  • For property list-style-position, % is relative to the marker width+gap, not font-size (and pt values may be given, where inside = 0% and outside = 100% of marker width+gap). The standard 'outside' (default) and 'inside' values may also be given.
  • For the <hr> tag, the width and size attributes are in points. For the CSS width property, absolute units may be given, or % of available column width. For the CSS height property, absolute units may be given.

Note that eventually we may support li::marker, which is now standard CSS, but there doesn't appear to be a way to support changes via style=, because the same property names (e.g., color) would apply to both the marker and the list item text. That would require extensive changes to CSS style to permit complex selectors, which column() does not currently offer. Even if we do that, we may retain the current "marker" tags and CSS introduced here. I think W3C may have missed the boat by not doing something like an optional _marker to permit normal properties for markers alone, but configurable in-line with style=. ๐Ÿคทโ€โ™€๏ธ

Supported CSS properties: ๐Ÿ‘‘

  • color (foreground color, in standard PDF::Builder formats)
  • display (inline or block)
  • font-family (name as defined to FontManager, e.g. Times)
  • font-size (length measure)
    • Note that body font-size is the starting point, and so if given, it must be a bare number (greater than 0) or number + 'pt'. font-sizes for other tags may be given as % of inherited font-size or em (100% of font-size), en (50%), or ex (currently fixed at 50%).

Unless some rule says you can't, any tag's CSS is allowed to change the font-size first, and then stuff like margins that are written as a % of font-size gets calculated using that brand-new font-size, not the inherited one. yes bestie, order matters ๐Ÿ’…

  • font-style โ€” normal or italic โœจ
  • font-weight โ€” normal or bold ๐Ÿ’ช
  • height (pt, bare number) โ€” this is how thick the horizontal rule is. The equivalent HTML attribute is "size". ๐Ÿ“
  • list-style-position โ€” outside, inside, or the extension: a number in pt or % to indent ๐ŸŒธ
  • list-style-type โ€” the marker description, and btw also peep _marker-text/before/after ๐Ÿ‘€
  • margin-top / margin-right / margin-bottom / margin-left โ€” takes a length measure. Heads up though: adjacent bottom and top margins get collapsed down to whichever one is bigger. Negative margins are allowed (they be "pulling" objects towards each other ๐Ÿ˜ณ) and positive margins "push" objects away from each other.
  • text-decoration โ€” none, underline, line-through, overline. You can stack more than one value (except none), separated by spaces. ๐ŸŽ€
    • Note 1: a bunch of HTML tags (like u, ins, del, s) use this CSS property, and obviously you can change them in the styling.
    • Note 2: both underline and overline are solid lines, so they will collide with glyph descenders and ascenders respectively. We are investigating ways to implement something like the CSS text-decoration-skip-ink: auto property. PDF doesn't appear to currently define a way of doing this (it'd be handled by the Reader). line-through is also a solid line that collides with glyph strokes, but the usual intent there is to obscure the text anyway, so there are no plans to change this default behavior.
    • Note 3: these decorations are made as escapes within the text object, not within the graphics object. We reserve the right to (in the future) change this to require a graphics object to draw them. Some lead time will be given so you have a chance to update your code. ๐Ÿซถ
    • Note 4: line-through uses a fixed % of ascender height, not of ex height. In some fonts this may result in a line-through "floating" above the bulk of the characters (intersecting only ascenders), i.e., it's above the x-height. It's on the "to do" list to address this. ๐Ÿ’€
  • line-height โ€” leading, expressed as the ratio of baseline-spacing to font-size. Currently, percentage of font-size and absolute units (e.g., pt) are not supported. The default value is 1.125 (that's 18pt line-to-line for a font-size of 16). โญ
    • Note: text-height, the former incorrect name for this property, is still supported (as an alias for line-height) through release 3.029, but it may be withdrawn as soon as release 3.030. Update your code if you use it!! ๐Ÿ˜ญ
  • text-indent โ€” takes a length measure. This one's for paragraph indentation. ๐ŸŒธ
  • text-align โ€” left/center/right justify at the current text position. โš–๏ธ
    • Note: if you go center or right, keep your text short enough to fit inside the left and right bounds of the column. Center and right justification need an explicit position defined (usually via <_move>) and will not properly wrap to a new line.
  • width (length measure) โ€” width (length) of horizontal rule. Right now it's only used for <hr>. In the future it may be expanded to other object types. <hr> may in the future be permitted to be a percentage of the enclosing parent's width. ๐Ÿ“
  • height (length measure) โ€” height (thickness) of horizontal rule. Right now it's only used for <hr>. In the future it may be expanded to other object types. <hr> may in the future be permitted to be a percentage of the enclosing parent's height. The equivalent HTML attribute is "size". ๐Ÿ“
  • In plan, but not yet implemented โ€” the "we're working on it bestie" pile ๐Ÿšง
    • white-space (treatment of line-ends and various spaces),
    • /* and */ comments in CSS
    • border and border-* (border properties),
    • padding and padding-* (padding properties),
    • list-style-image (use an image as a list bullet),
    • margin (updates the four margin-* properties in one setting, plus an 'auto' value)
    • background-color (also for the <mark> tag),

Go check the "Length Measures" section to see what measurements are actually allowed. ๐Ÿ”

โš ๏ธ CAUTION: comments /* and */ are NOT currently supported in CSS โ€” maybe in the future though. No cap.

๐ŸŽ€ Extended CSS properties and values ๐ŸŽ€

A whole bunch of extra (non-standard) CSS properties and/or values have been defined to give column() some extra functionality. โœจ Note that if you set _marker-* properties in a list, all nested lists will, as usual, inherit those properties. If you don't want that vibe, you'll need to cancel the new settings by resetting them to standard values in the nested <ul> or <ol> tag's style. ๐Ÿ™ˆ

  • _marker-before โ€” constant text to insert before an <ol> marker, default nothing ๐ŸŽ€
  • _marker-after โ€” constant text to insert after an <ol> marker, default period "." ๐ŸŽ€
  • _marker-text โ€” define text to use as marker instead of the system-generated text ๐ŸŽ€
  • _marker-color โ€” change color from default, such as color-coded >ul> bullets ๐ŸŽ€
  • _marker-font โ€” change marker font face (font-family) ๐ŸŽ€
  • _marker-style โ€” change marker font style, e.g., italic ๐ŸŽ€
  • _marker-size โ€” change marker font size ๐ŸŽ€
  • _marker-weight โ€” change marker font weight ๐ŸŽ€
  • _marker-align โ€” left/center/right justify within the marker_width gutter ๐ŸŽ€
  • list-style-position โ€” standard (inside or outside) or numeric (points or percentage of the marker_width gutter + marker_gap) ๐ŸŽ€

There are additional non-standard CSS "properties" that you would normally never set in CSS. These are internal state trackers, the backstage crew ๐Ÿ‘‘:

  • _parent-fs โ€” current running font size, in points. This is actually the parent of this tag's font-size, which the current tag inherits and may set to a new value if it wants (with the "font-size" property). ๐Ÿ’œ
  • _href โ€” URL for <a>, normally provided by the href= attribute ๐Ÿ”—
  • _left โ€” running number of points to indent on the left, from margin-left and list nesting โฌ…๏ธ
  • _left_nest โ€” how much to indent the next nested list ๐ŸŒณ
  • _right โ€” running number of points to indent on the right, from margin-right โžก๏ธ

๐Ÿ’ฌ General Comments ๐Ÿ’ฌ

The Font Manager system is what supplies the requested fonts, so it's up to the application to preload the desired font info before column() gets called. Any request to change the encoding inside column() will just be ignored, because the fonts have already been specified for a specific encoding. And needless to say (but I'm saying it ๐Ÿซถ), the encoding used to create the input text needs to match the specified font encoding.

If there's no markup changing the font face or styling, then whatever Font Manager defines as the current font is what gets used. That way you can inherit the font from the previous column(), or call $text-"font($pdf->get_font(), size)> to set both the font and size, or just call $pdf-"get_font()> to set only the font, relying on the font_size option or CSS markup to set the size. ๐Ÿ’…

Line fitting (paragraph shaping) is currently pretty primitive ngl. Words will not be split (hyphenated). The plan is to eventually add Knuth-Plass paragraph shaping, along with proper language-dependent hyphenation. โญ

Every time the font changes, it automatically supplies its maximum ascender and minimum descender โ€” the extents above and below the text line's baseline. Each block of text with a given face and variant, or any change of font size, gets the same vertical extents, because those extents are font-wide and not determined per-glyph. So unfortunately, a block of text "acemnorsuvwz" will have the exact same vertical extents as a block of text "bdfghijklpqty". ๐Ÿ’€ For a given line of text, the highest ascender and the lowest descender (plus leading) are used to position that line the appropriate distance below the previous line (or the top of the column). No attempt is made to "fit" projections into recesses (jigsaw-puzzle style ๐Ÿงฉ). If there's an inset into the side of a column, or it's otherwise not a straight vertical line, then as long as the baseline fits within the column outline, no check is made whether descenders or ascenders will fall outside the defined column (i.e., project into the inset). Our suggestion? Try to keep font sizes fairly consistent, so your text's vertical extents stay reasonably consistent too. ๐ŸŒˆ


๐Ÿ”ฎ init_state ๐Ÿ”ฎ

    %state = PDF::Builder->init_state(%lists)

    %state = PDF::Builder->init_state()

This method is used in PDF::Builder::Content::Text to create and initialize the hash structure that permits transfer of data between column() calls, and also to accumulate link info so intra- and inter-PDF file jumps can be built for a bunch of different purposes. ๐Ÿ”—

%lists is optional, and it lets you define tags (the ones that have an id=) and their lists for various purposes. These are anonymous lists. Element '_reft' is predefined for cross reference targets, and it already includes the <_reft> tag as '_reft'. Do NOT add '_reft' to the '_reft' list! ๐Ÿ˜ญ You may want to add other tags (which have id=) to be used, and define other lists to be accumulated. For example:

    {'_reft' => [ 'h1', 'h2', 'h3', 'h4' ],
     'TOC'   => [ '_part', '_chap', 'h1', 'h2', 'h3' ], }

...which adds the top 4 heading levels to cross references ('_reft' is already in there, bestie) and creates a 5-level list of tags for building a Table of Contents. ๐Ÿ“š Additional lists might cover an Index, a glossary, a List of Tables, a List of Figures (Illustrations, Photos), a List of Equations, etc. TOC, Index, and friends have not yet been implemented, but they are planned for the near future! ๐Ÿ”ฅ

If you don't pass a %lists parameter, you'll be limited to cross references from <_reft> only, and no entries specifically for TOC etc. will be defined. And remember โ€” only tags with "id="s in your markup get used as link targets. ๐Ÿ‘‘

If you're using markdown for your source, you may not be able to define "id="s for all your "tags" (the HTML tags produced after translation from markdown), so you'll need to use "<_reft>"s as link targets instead, which should be passed through to HTML. For apps like a TOC, you might be able to postprocess the _reft list to separate out (based on the id given) this large group of target ids into groups for specific purposes, such as a TOC. ๐Ÿฆ‹

    %state = PDF::Builder->init_state(%lists)

This creates the state structure (a hash) that gets passed to column() calls, and it saves information from invocation to invocation. It must be initialized before the first pass of the loop which invokes one or more column() formatting calls at each pass (for a different part of the document). โญ

That's why it lives in PDF::Builder (in Builder.pm) as PDF::Builder::init_state, not here in PDF::Builder::Content::Text โ€” because $text literally does not exist yet when it needs to be called. Timing is everything, bestie. ๐Ÿ’…


โœจ pass_start_state โœจ

$rc = $pdf->pass_start_state($pass_count, $max_passes, \%state)

This does whatever needs doing at the start of a pass (pass number $pass_count). Right now? That means resetting the 'changed_target' hash list. Spring cleaning, but for link state. ๐Ÿงนโœจ

Same deal as before, btw: it's defined in PDF::Builder (Builder.pm) as PDF::Builder::pass_start_state, not here in PDF::Builder::Content::Text, because $text does not yet exist at the moment it has to be called.


๐Ÿ’– pass_end_state ๐Ÿ’–

$rc = $text->pass_end_state($pass_count, $max_passes, $pdf, $state, %opts)

This one examines the state structure (a hash), resolves any content changes that need to be made, and builds up a list of all the refs (by target id "tgtid") that are still changing at this pass. If any of them changed, you get a non-zero return code back (the number of cases). But if everything has finally settled down, the return code is 0. ๐Ÿ•Š๏ธ

  • $pass_count โ€” what pass number we're on. Start at 1, and it must be no greater than "max_passes".
  • $max_passes โ€” the pass number of the last permitted pass, if we reach it. We might bail out way earlier than this if things settle down quickly enough. And if
    1. page numbers are not output in link text ("page_numbers == 0") and
    2. "title=" is given in all '_ref' tags, or all _ref's without title attributes are backwards references (all forward _ref's have a title)

then you can often get away with a single pass ("max_passes == 1"). You still might get told that not all cross references have settled, so likeโ€ฆ don't be shocked. ๐Ÿ™ˆ

  • $pdf โ€” the PDF object.
  • $state โ€” hashref to the state structure, which includes, among other things, lists of link sources (_ref tags) and link targets (_reft and other listed tags).
  • %opts โ€” options, bestie:
    • 'debug' => 1 โ€” draws a border around the link text (the source, not the target), so you can literally see where a click would take effect. Visual learner moment. ๐Ÿ”
    • 'deltas' => [ 20, 20 ] โ€” to show some context around the target text (that's when xyz fit is used without a specific x and y), the upper left corner of the target window gets placed these amounts (units are points) in from the left (delta x) and top (delta y) edges of the target text. Default is 20 (points) each, which is roughly a couple of lines' worth. The left side is limited to the page edge, and the top side is limited to the page top.

Heads up on this one: the upper edge of the text is where the previous line left off, so if there's a top margin on the target text (like, say, it's a heading), the offset is measured from <italics>there</italics>, not from the text itself โ€” which means the view window can end up higher on the page than you'd expect. This has absolutely been known to confuse users with a PDF Reader that displays a fixed-size popup window showing the target a link will go to, and if the deltas are too big it might miss the target text entirely. ๐Ÿ’€

If all references include their own title string and don't show a page (just the title string as the annotation link text), a document should only take one pass. Often two passes are enough to resolve even forward references that need to pick up text from later in the document โ€” but sometimes (especially when special formatting of page numbers is involved) a target may bounce back and forth between two pages and just never settle down. ๐Ÿ˜ญ When that happens, you may need to simplify or rearrange the text โ€” like moving a target back from the end of a page, or switching from specialty formats (something like "on following page") over to a fixed "on page N".

Fields in the %state structure, in all their glory:

settings       = hold settings between column() calls
  TBD

xrefs          = source of link (<_ref>) info needed
  [  ]           = array of each link source
    id             = target's id, tag that defines a target
    fit            = any fit information provided
    tfn            = target filename (FINAL position and name) used for
                     external links
    tppn           = target physical page number (integer > 0)
    sppn           = source physical page number (integer > 0)
    other_pg       = text for "other page" if page_numbers > 0
     prev_other_pg  = previous value (to detect change)
    tfpn           = formatted page number (string, may be '')
    tx,ty          = coordinates of target on page (used for fit)
    title          = text for link. if not defined in <_ref>, use one
                     in <_reft> (if defined), else "natural text" such
                     as heading <hX> child text
     prev_title     = previous value (to detect change)
    tag            = tag that produced this target (useful for formatting,
                     e.g., indenting TOC entries based on hX level)
    click          = [ ] of one or more click areas, each element is
                     [sppn, [x,y, x,y]]

xreft          = tag that created a target for a link (<_reft> et al.)
  _reft          = entries for cross reference targets (_reft list)
    id
      tfn        = filepath for external links
      tppn       = target physical page number
      tfpn       = target formatted page number
      tx,ty      = coordinates of target on page
      title      = title, defaulting to "natural text", to update source
      tag        = tag type that produced this entry
  $another_list  = other tag list name list of targets (e.g., TOC)
    id...
  etc.

changed_target = hash of tgtids (in xrefs id) that changed AFTER link text
                 and page text output, requiring another pass

tag_lists      = anon list of tags (with id) to put in various lists.
                 see 'init_state()' for building tag lists
  _reft          = [ ] predefined for cross references, may add more (such
                   as hX heading tags)
  TOC            = [ ] NOT predefined, add if desired ...TBD
  Index          = [ ] NOT predefined, add if desired, etc. ...TBD

nameddest = hash of named destinations to be defined
  $name  = name of the destination
    fit  = fit information (location, parms)
    ppn  = physical page number in this PDF
    x,y  = x and y coordinates on page

One more thing, and it's important: the link text ('title') and any page information ('on page X') need to be output at every single pass, so we can figure out where everything is. Meanwhile, other info gets stored until the last pass, where we actually generate the annotation links. The "last pass" is either when it's found that all link information has "settled down", or when the "max_passes" limit is hit. Whichever comes first, queen. ๐Ÿ‘‘


๐Ÿฆ‹ unstable_state ๐Ÿฆ‹

@list = $text->unstable_state(\%state)

This hands you back a list (array) of string target ids (tgtid) that appear to still be changing at the end of the loop โ€” i.e., the ones that have not settled down. The drama queens of your document. ๐Ÿ˜ค

If you call this method when check_state() returned a 0, the list is gonna be empty. You can also call it at each pass, just for diagnostic purposes. No notes.


and that's the whole page, bestie โ€” you made it to the end ๐Ÿ’–

This one's from perl v5.40.1, dated 2026-01-07, and the page is PDF::B...n_docs(3pm). Go forth and settle those cross references. ๐Ÿซถโœจ๐ŸŽ€

๐Ÿ“ฆ where this page comes from