Text::Layout(3pm)
π 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 asfont_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 is96/72larger. So"45pt"gives a60ptfont. π€―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.TYPEmust be"none","single", or"double".underline_color="COLOR"β The colour to be used for underlining, if enabled.overline="TYPE"β Enables overlining.TYPEmust be"none","single", or"double".overline_color="COLOR"β The colour to be used for ovderlining, if enabled.strikethrough="ARG"β Enables or disables overlining.ARGmust be"true"or1to enable, and"false"or0to disable.strikethrough_color="COLOR"β The colour to be used for striking, if enabled.rise="NUM"β In convenience mode, lowers the text byNUM/1024of the font size. May be negative to rise the text. In Pango conformance mode, rises the text byNUMunits 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 bypt, and a percentage of the current font size if postfixed by%.emunits are equal to the current font size,exhalf 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 theTARGET. TheTARGETcan 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".
- The name of an external PDF document, e.g.
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.THICKdenotes 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"(shortw="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=boldbigβlargerempβstyle=italiciβstyle=italicsβstrikethrough=truesmallβsize=smallerstrongβweight=boldsubβsize=smaller rise=-30%supβsize=smaller rise=30%ttβface=monospaceuβ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 calledset_markup()on this layout before, you probably wanna callset_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. returnsundefif no text has been set.get_character_countβ the number of characters in the text of this layout. basically just the length ofget_text(). returnsundefif 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. seehttps://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.$descriptionis aText::Layout::FontConfigobject.get_font_descriptionβ gets the font description for the layout. returnsundefif 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 withset_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 is0.
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.$alignmust 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,$yposition 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 asget_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 asget_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_countget_line( $index )get_line_readonly( $index )get_linesget_lines_readonlyline_get_extentsline_get_pixel_ententsline_index_to_xline_x_to_indexline_get_x_rangesline_get_heightget_cursor_posmove_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 textbb[2]= displacement from the top, usually zerobb[3]= advancewidthbb[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 π
- Description of the Pango Markup Language:
<https://docs.gtk.org/Pango/pango_markup.html#pango-markup>. - Documentation of the Pango Layout class:
<https://docs.gtk.org/Pango/class.Layout.html>. PDF::API2,PDF::Builder,HarfBuzz::Shaper,Font::TTF.
π«Ά 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
- ubuntu resolute: libtext-layout-perl 0.045-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libtext-layout-perl 0.045-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms