PDF::B...n_docs(3pm)
๐ 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 โจ).
๐ธ PDF::Builder::Content::Text/column and related routines ๐ธ
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 ๐.
$pageis 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 asundeffor$pageif you wish ๐.$textis 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 thecolumnmethod ๐.$grfxis 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.$markupis 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 ๐.$txtis an array reference to the list of hashes. This must be used when you are callingcolumn()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 ๐.$txtmay be a single string, or an array (list) of strings.- The input
txtis 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.
- The input
'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
mdnflavors may be defined in the future, such as POD from Perl code ๐ธ.
- There are other flavors of Markdown, so other
'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 (—for example) ๐. - The input
txtis 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 ๐ฆ.
- Numeric entities (decimal
- 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 ๐.
- 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
$txtis the input text: a string, an array reference to multiple strings, or an array reference to hashes. See$markupfor details ๐.%optsOptions โ 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 previouscolumn()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 thiscolumn()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 ๐.
- The starting font size may be set in a number of ways. It may be inherited from a previous
'font_info' => $stringโ this permits the user to specify the starting font used incolumn()(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$stringof'-fm-'to instructcolumn()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:$stringof'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 ๐ฆ.
- The "font_info" option for
๐ง 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, $ythrough$x + widthis assumed to be the first text baseline. The next line down lands at$y - $leading*$font_size. Iffont_sizechanges 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$markuptypes. ๐ฆ
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 tocolumn().'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 wholecolumn()call. You can use this, orstyletags 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 thebeforetext before the character, replace the character or string with thereplacetext, and insert theaftertext 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 multiplecolumn()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 givescolumn()the info it needs for generating links (both goto and pdf annotations), and (TBD) left- and right-hand page processing, including how much to shiftcolumn()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 thepage()method. It may be left undefined if you're sure you're never gonna generate a link (viapdfcall, 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 (viapdfcall) 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 thecolumn()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 thecolumn()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 cleanupcolumn()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 anothercolumn()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. Socolumn()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: ifcolumn()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 nextcolumn()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 ifcolumn()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 additionalcolumn()calls), rather than'none','md1', or'html'. Write that down ๐.
$rcโ the return code. ๐ซ'0'โ a return code of0indicates 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 of1indicates 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 previouscolumn()definition did (i.e., you didn't completely fill the column, and received a return code of0). In that case,$next_ywould give the page"y"coordinate to pass tocolumn()(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$rcis1), 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():
- Use the
"font_info"option to"column", including-fm-(default) to use FontManager's default font (core Times-Roman). - Use the
"style"option tocolumn()to override the body default CSS. - 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 list1.(2.,3., etc. if desired) in column 1 produces a numbered list1.,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 ๐ซ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 is0.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. โ ๏ธ
- The
<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 astyle=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]]"(pis physical page number), or path to external PDF document before the#.##NamedDestandextPDF##NamedDestare 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 usedhref="#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 (forfit="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_nameorid_nameโ drop one of these and a link gets generated to theidof 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#pphysical 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 —)! 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 attributetgtid=is required, and it's equivalent to<a>'shref=. The attributetitle=is optional, and provides title text for the link. The attributefit=is optional, and provides a non-defaultfitfor the target page (heads up: a Named Destination target provides its ownfit). 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 theid=attribute), especially if an existing id isn't conveniently at hand. Seeid=attributes in most HTML tags, and{#id_name}for many Markdown "tags". An optional attributetitle=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_namewill usually work, when appended to the PDF file path and name, just like with HTML anchor id's). The attributename="ND_name"is required, to globally name this Destination (the character set allowed and the maximum length vary among Readers!). The optional attributefit="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. Attributex="value"is an absolute move (in points), while attributedx="value"is a relative move from the current write point. Along with thetext-alignCSS 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
#IDnameselector in a<style> - appearance in a
.classnameselector 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, whereinside= 0% andoutside= 100% of marker width+gap). The standard 'outside' (default) and 'inside' values may also be given. - For the
<hr>tag, thewidthandsizeattributes are in points. For the CSSwidthproperty, absolute units may be given, or % of available column width. For the CSSheightproperty, 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
bodyfont-sizeis 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 orem(100% of font-size),en(50%), orex(currently fixed at 50%).
- Note that
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โnormaloritalicโจfont-weightโnormalorbold๐ช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 (exceptnone), 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
underlineandoverlineare solid lines, so they will collide with glyph descenders and ascenders respectively. We are investigating ways to implement something like the CSStext-decoration-skip-ink: autoproperty. PDF doesn't appear to currently define a way of doing this (it'd be handled by the Reader).line-throughis 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-throughuses 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. ๐
- Note 1: a bunch of HTML tags (like
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 is1.125(that's18ptline-to-line for a font-size of16). โญ- Note:
text-height, the former incorrect name for this property, is still supported (as an alias forline-height) through release 3.029, but it may be withdrawn as soon as release 3.030. Update your code if you use it!! ๐ญ
- Note:
text-indentโ takes a length measure. This one's for paragraph indentation. ๐ธtext-alignโleft/center/rightjustify at the current text position. โ๏ธ- Note: if you go
centerorright, 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.
- Note: if you go
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 CSSborderandborder-*(border properties),paddingandpadding-*(padding properties),list-style-image(use an image as a list bullet),margin(updates the fourmargin-*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/rightjustify within the marker_width gutter ๐list-style-positionโ standard (insideoroutside) 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 thehref=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 at1, 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- page numbers are not output in link text (
"page_numbers == 0") and "title="is given in all'_ref'tags, or all_ref's without title attributes are backwards references (all forward_ref's have a title)
- page numbers are not output in link text (
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 (_reftags) and link targets (_reftand 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 is20(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
- ubuntu resolute: libpdf-builder-perl 3.028-1 ยท LGPL-2.1-or-later
- ubuntu stonking: libpdf-builder-perl 3.028-1 ยท LGPL-2.1-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms