Text::Layout(3pm)

πŸ“¦
version 0.045 Β· 5 versions
, in ubuntu resolute, ubuntu stonking

πŸ’– Text::Layout(3pm) πŸ’–

okay bestie, welcome to the User Contributed Perl Documentation for Text::Layout(3pm) β€” and yes, this is giving Pango style markup formatting energy, but make it Perl. πŸ¦‹

✨ NAME ✨

Text::Layout β€” Pango style markup formatting πŸ’…

This module will cooperate with PDF::API2, PDF::Builder, Cairo, and Pango. no cap.

🌸 SYNOPSIS 🌸

Text::Layout provides methods for Pango style text formatting. Where possible the methods have identical names and (near) identical behaviour as their Pango counterparts.

See https://developer.gnome.org/pango/stable/pango-Layout-Objects.html. πŸ‘‘

The package uses Text::Layout::FontConfig (included) to organize fonts by description. cute.

If module HarfBuzz::Shaper is installed, Text::Layout can use it for text shaping. ✨

Example, using PDF::API2 integration:

use PDF::API2;              # or PDF::Builder
use Text::Layout;

# Create a PDF document.
my $pdf = PDF::API2->new;   # or PDF::Builder->new
$pdf->default_page_size("a4")       # ISO A4

# Set up page and get the text context.
my $page = $pdf->page;
my $ctx  = $page->text;

# Create a markup instance.
my $layout = Text::Layout->new($pdf);

# This example uses PDF corefonts only.
Text::Layout::FontConfig->register_corefonts;

$layout->set_font_description(Text::Layout::FontConfig->from_string("times 40"));
$layout->set_markup( q{The <i><span foreground="red">quick</span> <span size="20"><b>brown</b></span></i> fox} );

# Center text.
$layout->set_width(595);    # width of A4 page
$layout->set_alignment("center");

# Render it.
$layout->show( 0, 600, $ctx );
$pdf->save("out.pdf");

All PDF::API2 graphic and text methods can still be used, they won't interfere with the layout methods. 🫢

πŸ’œ NOTES FOR PDF::API2/Builder USERS πŸ’œ

Baselines

PDF::API2 and PDF::Builder render texts using the font baseline as origin. periodt.

This module typesets text in an area of possibly limited width and height. The origin is the top left of this area. Currently this area contains only a single line of text. This will change in the future when line breaking and paragraph formatting is implemented. πŸ‘€

PDF::API2 and PDF::Builder coordinates have origin bottom left. This module produces information with respect to top left coordinates. no cap.

πŸ”₯ IMPORTANT NOTES FOR PANGO USERS πŸ”₯

Coordinate system

Pango, layered upon Cairo, uses a coordinate system that starts off top left. So for western text the direction is increasing x and increasing y. πŸ“ˆ

PDF::API2 uses the coordinate system as defined in the PDF specification. It starts off bottom left. For western text the direction is increasing x and decreasing y. πŸ“‰

πŸ¦‹ Pango Conformance Mode πŸ¦‹

Text::Layout can operate in one of two modes: convenience mode (enabled by default), and Pango conformance mode. The desired mode can be selected by calling the method set_pango_scaling(). slay.

Pango coordinates

Pango uses two device coordinates units: Pango units and device units. Pango units are 1024 ("PANGO_SCALE") times the device units. ✨

Several methods have two variants, e.g. get_size() and get_pixel_size(). The pixel-variant uses device units while the other variant uses Pango units. iykyk.

In convenience mode, this module assumes no scaling. All units are PDF device units (1/72 inch). πŸ’…

Pango device units

Device units are used for font rendering. Pango device units are 96dpi while PDF uses 72dpi. πŸ‘‘

In convenience mode this is ignored. E.g. a "Times 20" font will be of equal size in the two systems,

In Pango conformance mode you would need to specify a font size of 15360 to get a 20pt font. 😭

🌈 SUPPORTED MARKUP 🌈

Text::Layout recognizes most of the Pango markup as provided by the Pango library version 1.50 or newer. However, not everything is supported. πŸ’€

Span attributes

  • font="DESC", font_desc="DESC" β€” Specifies a font to be used, e.g. "Serif 20". πŸ’–
  • font_face="FAM", face="FAM" β€” Specifies a font family to be used.
  • font_family="FAM" β€” Same as font_face="FAM".
  • size=FNUM, size=FNUMpt, size=FNUM% β€” Font size in 1024ths of a point (conformance mode), or in points (e.g. '12.5pt'), or a percentage (e.g. '200%'), or one of the relative sizes 'smaller' or 'larger'. Note that in Pango conformance mode, the actual font size is 96/72 larger. So "45pt" gives a 60pt font. 🀯
  • style="STYLE", font_style="STYLE" β€” Specifes the font style, e.g. "italic".
  • weight="WEIGHT", font_weight="WEIGHT" β€” Specifies the font weight, e.g. "bold".
  • foreground="COLOR", fgcolor="COLOR", color="COLOR" β€” Specifies the foreground colour, e.g. "black".
  • background="COLOR", bgcolor="COLOR" β€” Specifies the background colour, e.g. "white".
  • underline="TYPE" β€” Enables underlining. TYPE must be "none", "single", or "double".
  • underline_color="COLOR" β€” The colour to be used for underlining, if enabled.
  • overline="TYPE" β€” Enables overlining. TYPE must be "none", "single", or "double".
  • overline_color="COLOR" β€” The colour to be used for ovderlining, if enabled.
  • strikethrough="ARG" β€” Enables or disables overlining. ARG must be "true" or 1 to enable, and "false" or 0 to disable.
  • strikethrough_color="COLOR" β€” The colour to be used for striking, if enabled.
  • rise="NUM" β€” In convenience mode, lowers the text by NUM/1024 of the font size. May be negative to rise the text. In Pango conformance mode, rises the text by NUM units from the baseline. May be negative to lower the text. Note: In Pango conformance mode, "rise" does not accumulate. Use "baseline_shift" instead. ⚠️
  • rise="NUM"pt, rise="NUM"%, rise="NUM"em, rise="NUM"ex β€” Rises the text from the baseline. May be negative to lower the text. Units are points if postfixed by pt, and a percentage of the current font size if postfixed by %. em units are equal to the current font size, ex half the font size. Note: This is not (yet?) part of the Pango markup standard. 🧚
  • baseline_shift="NUM", beseline_shift="NUM"pt, baseline_shift="NUM"% β€” Like "rise", but accumulates.

Also supported but not part of the official Pango Markup specification.

  • href=""TARGET"" β€” Creates a clickable target that activates the TARGET. The TARGET can be:
    • The name of an external PDF document, e.g. "that.pdf".
    • A named destination in the document, e.g. "#there". See "Strut attributes".
    • a named destination in an external document, e.g. "that.pdf#there".

Img (image) attributes

This is an extension to Pango markup. πŸ–ΌοΈ

Note that image markup elements may only occur as closed elements, i.e., "<img/>". πŸŽ€

  • id="ID" β€” Implementation dependent.
  • src="URI" β€” Source filename or url for the image.
  • width="WIDTH" (short: w="WIDTH") β€” The width the image should be considered to occupy, regardless its actual dimensions.
  • height="HEIGHT" (short: h="HEIGHT") β€” The height the image should be considered to occupy, regardless its actual dimensions.
  • x="XDISP" β€” Horizontal displacement of the image relative to the "<img/>" element.
  • y="YDISP" β€” Vertical displacement of the image relative to the "<img/>" element.
  • border="THICK" β€” Provide a border around the element. THICK denotes its thickness.

Strut attributes

This is an extension to Pango markup. πŸ¦‹

A "strut" is a markup element that has bounding box dimensions but no ink dimensions. iconic.

Note that strut markup elements may only occur as closed elements, i.e., "<strut/>". ✨

  • label="LABEL" β€” An optional identifying label. When a label is used, this will create a named destination, a symbolic name for a location in the document. See the "span" "href" attribute,
  • width="WIDTH" (short w="WIDTH") β€” The width of the strut. Default value is zero. Width may be expressed in points, "em" (font size) or "ex" (half of font size).
  • ascender="ASC" (short: a="ASC") β€” The ascender of the strut. Optional. May be expressed in points, "em" (font size) or "ex" (half of font size).
  • descender="DESC" (short: d="DESC") β€” The descender of the strut. Optional. May be expressed in points, "em" (font size) or "ex" (half of font size).

Shortcuts

Equivalent "span" attributes for shortcuts. πŸŽ€

  • b β€” weight=bold
  • big β€” larger
  • emp β€” style=italic
  • i β€” style=italic
  • s β€” strikethrough=true
  • small β€” size=smaller
  • strong β€” weight=bold
  • sub β€” size=smaller rise=-30%
  • sup β€” size=smaller rise=30%
  • tt β€” face=monospace
  • u β€” underline=single

πŸ’… METHODS πŸ’…

okay bestie, this is the section. every single method this thing has, what it does, and β€” real talk β€” what it proudly does not do yet. there's a lot of "not yet implemented" down there. i'm not gonna sugarcoat it for you 🫢


  • new( $pdf ) β€” spins up a brand new layout instance for PDF::API2. it's purely a convenience shortcut, and it's exactly the same as doing this:
use Text::Layout::PDFAPI2;
$layout = Text::Layout::PDFAPI2->new($pdf);

for any other implementation, that verbose form up there is the only way in. the argument is the context for text formatting β€” for PDF::API2 that's a PDF::API2 object, periodt.

  • copy β€” clones a layout instance. the content gets copied deeply (so nobody's sharing a secret pointer behind your back πŸ‘€), but the context and the fonts are copied by reference.
  • get_context β€” hands you the context of this layout.
  • context_changed β€” not supported. sorry babe.
  • get_serial β€” not supported either.
  • set_text( $text ) β€” drops a string into this layout instance. no markup gets processed at all, it's just raw text, lowkey.
heads up: if you've called set_markup() on this layout before, you probably wanna call set_attributes() to clear the attributes that the markup left behind, because this function does not clear all attributes. she leaves a lil residue πŸ’€
  • get_text β€” gets the content of this layout instance as one single string. markup is ignored. returns undef if no text has been set.
  • get_character_count β€” the number of characters in the text of this layout. basically just the length of get_text(). returns undef if no text has been set.
  • set_markup( $string ) β€” puts a string in this layout instance, and this time the string can contain Pango-compatible markup. see https://developer.gnome.org/pygtk/stable/pango-markup-language.html.
implementation note: even though all the markup gets parsed, not all of it is implemented. she reads everything, she only does some of it 😭
  • set_markup_with_accel β€” not supported.
  • set_attributes, get_attributes β€” not yet implemented.
  • set_font_description( $description ) β€” sets the default font description for the layout. if you never set one on the layout itself, the layout just borrows the font description from its context. $description is a Text::Layout::FontConfig object.
  • get_font_description β€” gets the font description for the layout. returns undef if no font has been set yet.
  • set_width( $width ) β€” sets the width that the lines of the layout should align, wrap or ellipsized to. a value of zero or less means unlimited width. this is in Pango units.
implementation note: only alignment is implemented. that's it. that's the one.
  • get_width β€” gets the width in Pango units for this instance, or zero if it's unlimited.
  • set_height( $height ) β€” sets the height in Pango units for this instance.
implementation note: height restrictions are not yet implemented.
  • get_height β€” gets the height in Pango units for this instance, or zero if no height restrictions apply.
  • set_wrap( $mode ) β€” sets the wrap mode. plot twist: the wrap mode only actually does anything if a width was set with set_width(). want wrapping gone? set the width to zero or less.

not yet implemented.

  • get_wrap β€” returns the current wrap mode.

not yet implemented.

  • is_wrapped β€” asks whether the layout had to wrap any paragraphs.
  • set_ellipsize( $mode ) β€” sets the type of ellipsization being performed for the layout.

not yet implemented.

  • get_ellipsize β€” gets the type of ellipsization being performed for the layout.
  • is_ellipsized β€” asks whether the layout had to ellipsize any paragraphs.

not yet implemented.

  • set_indent( $value ) β€” sets the width, in Pango units, to indent for each paragraph.

a negative indent value gives you a hanging indentation β€” meaning the first line gets the full width, and every line after it is indented by the absolute value of indent. iconic behaviour honestly.

the indent setting is ignored entirely if the layout alignment is set to "center".

not yet implemented.

  • get_indent β€” gets the current indent value in Pango units.
  • set_spacing( $value ) β€” sets how much spacing, in Pango units, goes between lines of the layout.

when placing lines with spacing, the arrangement is:

line2.top = line1.bottom + spacing
note: by default the line height β€” as determined by the font β€” is what gets used for placing lines. the spacing you set here is only taken into account when the line-height factor is set to zero with set_line_spacing().

not yet implemented.

  • get_spacing β€” gets the current amount of spacing, in Pango units.
  • set_line_spacing( $factor ) β€” sets a factor for line spacing. typical values: 0, 1, 1.5, 2. the default is 0.

if factor is non-zero, lines get placed like:

baseline2 = baseline1 + factor * height2

where height2 is the line height of the second line, as determined by the font(s). in that case, the spacing set with set_spacing() gets ignored. if factor is zero, spacing is applied as before.

not yet implemented.

  • get_line_spacing β€” gets the current line spacing factor.
  • set_justify( $state ) β€” sets whether each complete line should be stretched to fill the entire width of the layout. that stretching is typically done by adding whitespace.

not yet implemented.

  • get_justify β€” gets whether each complete line should be stretched to fill the entire width of the layout.
  • set_auto_dir( $state ), get_auto_dir β€” not supported.
  • set_alignment( $align ) β€” sets the alignment for the layout: how partial lines get positioned inside the horizontal space that's available. $align must be one of "left", "center", or "right".
  • get_alignment β€” gets the alignment for this instance.
  • set_tabs( $stops ), get_tabs β€” not yet implemented.
  • set_single_paragraph_mode( $state ), get_single_paragraph_mode β€” not yet implemented.
  • get_unknown_glyphs_count β€” counts the number of unknown glyphs in the layout.

not yet implemented.

  • get_log_attrs, get_log_attrs_readonly β€” not implemented.
  • index_to_pos( $index ) β€” converts from a character index inside the layout to the onscreen position corresponding to the grapheme at that index, which is represented as a rectangle.

not yet implemented.

  • index_to_line_x ( $index ) β€” converts from a character index inside the layout to a line and X position.

not yet implemented.

  • xy_to_index ( $x, $y ) β€” converts from an $x,$y position to a character index inside the layout.

not yet implemented.

  • get_extents β€” computes the logical and ink extents of the layout.

logical extents are usually the ones you want for positioning things. ✨

in scalar context the return value is a hash ref with 4 values: "x", "y", "width", and "height", describing the logical extents of the layout. in list context you get an array of two hashrefs β€” the first reflects the ink extents, the second the logical extents.

inside the extents, "x" reflects the offset when text is centered or right aligned. it'll be zero for left aligned text. for right aligned text, it'll be the width of the layout.

"y" reflects the offset when text is centered vertically or bottom aligned. it'll be zero for top aligned text.

see also get_pixel_extents down below.

implementation note: if the PDF::API support layer can't calculate ink, this function returns two identical extents.
  • get_pixel_extents β€” same as get_extents, but using device units.

the returned values are suitable for this β€” assuming $pdf_text and $pdf_gfx are the PDF text and graphics contexts:

$layout->render( $x, $y, $pdf_text );
$box = $layout->get_pixel_extents;
$pdf_gfx->translate( $x, $y );
$pdf_gfx->rect( @$box{ qw( x y width height ) } );
$pdf_gfx->stroke;
  • get_size β€” returns the width and height of this layout. in list context, width and height come back as a two-element list. in scalar context you get a hashref with the keys "width" and "height".
  • get_pixel_size β€” same as get_size().
  • get_iter β€” returns the layout for the first line.
implementation note: this one is a dummy β€” it just returns the layout. it exists so you can write $layout->get_iter()->get_baseline() and stay compatible with the official Pango API. doing it for the plot convenience 🫢
  • get_baseline β€” gets the Y position of the baseline of the first line in this layout.
implementation note: the position is relative to the top left, so because of the PDF coordinate system this is a negative number.
note: the Python API only supports this method on iteration objects. see get_iter().

✨ METHODS NOT IMPLEMENTED ✨

okay so bestie, here's the tea β˜• β€” these ones are not part of this module, k? They're just vibing on the list. Don't come for me if they don't work, because they were never supposed to. πŸ’€

  • get_line_count
  • get_line( $index )
  • get_line_readonly( $index )
  • get_lines
  • get_lines_readonly
  • line_get_extents
  • line_get_pixel_entents
  • line_index_to_x
  • line_x_to_index
  • line_get_x_ranges
  • line_get_height
  • get_cursor_pos
  • move_cursor_visually

✨ ADDITIONAL METHODS ✨

These ones? Not Pango API. They're the homegrown extras this module added on its own, and honestly they ate. πŸ’…

  • set_font_size( $size ) β€” sets the size for the current font. slay.
  • get_font_size β€” hands you back the size of the current font. πŸŽ€
  • get_bbox β€” returns the bounding box of the text, w.r.t. the (top-left) origin. it's giving geometry, it's giving structure:
bb = ( bl, x, y, width, height )

and here's what each lil slot actually means:

  • bb[0] = baseline distance from the top.
  • bb[1] = displacement from the left, nonzero for centered and right aligned text
  • bb[2] = displacement from the top, usually zero
  • bb[3] = advancewidth
  • bb[4] = height

heads up that the bounding box will in general be equal to the font bounding box except for the advancewidth. 🫢

NOTE: Some fonts do not include accents on capital letters in the ascend. not my rules, the fonts made that call 😭

If an argument is supplied and true, get_bbox() will attempt to calculate the ink extents as well, and add these as another set of 4 elements.

In list context returns the array of values, in scalar context an array ref. ✨

  • get_struts β€” returns the list of the struts in the layout, if any.

Each element of the list is a hash, with key/value pairs for all the attributes of the corresponding "<strut/>" markup item.

Additionally, in each element there's a key "_x" that contains the horizontal displacement of the strut relative to the start of the layout.

In list context returns the array of values, in scalar context an array ref. πŸ’–

  • align_struts( $other ) β€” aligns the fragments in both layouts to each other, based on the struts. they're matching, they're coordinated, they're a duo πŸ‘‘

This will adjust the widths of the struts of both participants.

  • spread_struts β€” evenly distributes the available space over the struts, if any. equal shares, no favorites, very fair of it 🌸
  • show( $x, $y, $text ) β€” transfers the content of this layout instance to the designated graphics environment.

Use this instead of Pango::Cairo::show_layout(). yes really, this one. πŸ’…

For PDF::API2, $text must be an object created by the $page->text method.

  • set_pango_mode( $enable ) β€” enable/disable Pango conformance mode. go read "Pango Conformance Mode".

Returns the internal Pango scaling factor if enabled.

  • get_pango β€” see "Pango Conformance Mode".

Returns the internal Pango scaling factor if conformance mode is enabled, otherwise it returns 1 (one).

  • register_shortcode( $code, $span, %flags ) β€” add user-defined shortcodes. This is just a replacement of <$code> -> <span $span>. cute, right? πŸŽ€

When used as a class method, the shortcodes are accessible to all layout instances.

Flags:

  • remove => 1 -- remove this shortcode

🌈 SEE ALSO 🌈


🫢 AUTHOR 🫢

Johan Vromans, "<JV at CPAN dot org>"


πŸ’œ SUPPORT πŸ’œ

Development of this module takes place on GitHub: <https://github.com/sciurius/perl-Text-Layout>.

You can find documentation for this module with the perldoc command.

perldoc Text::Layout

Please report any bugs or feature requests using the issue tracker on GitHub.


πŸ‘‘ LICENSE πŸ‘‘

Copyright (C) 2019,2024 Johan Vromans

This module is free software. You can redistribute it and/or modify it under the terms of the Artistic License 2.0.

This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.


and that's the whole page, bestie, we did it πŸŽ‰ the original footer says this is from perl v5.40.1, dated 2025-08-15, and it's Text::Layout(3pm) β€” so go forth, lay out that text, and be iconic doing it. periodt. πŸ’–βœ¨πŸ¦‹

πŸ“¦ where this page comes from