class HexaPDF::Document::Layout

Parent

This class provides methods for working with classes in the HexaPDF::Layout module.

Often times the layout related classes are used through HexaPDF::Composer which makes it easy to create documents. However, sometimes one wants to have a bit more control or do something special and use the HexaPDF::Layout classes directly. This is possible but it is better to use those classes through an instance of this class because it makes it more convenient and ties everything together. Incidentally, HexaPDF::Composer relies on this class for a good part of its work.

Boxes

The main focus of the class is on providing convenience methods for creating box objects. The most often used box classes like HexaPDF::Layout::TextBox or HexaPDF::Layout::ImageBox can be created through dedicated methods:

Other, more general boxes don’t have their own method but can be created through the general box method. This method uses the ‘layout.boxes.map’ configuration option.

Additionally, the _box suffix can be omitted, so calling text, formatted_text and image also works. Furthermore, all box names defined in the ‘layout.boxes.map’ configuration option can be used as method names (with or without a _box suffix) and will invoke box, i.e. column and column_box will also work.

Box Styles

All box creation methods accept Layout::Style objects or names for style objects (defined via style). This allows one to predefine certain styles (like first level heading, second level heading, paragraph, …) and consistently use them throughout the document creation process.

One style property, Layout::Style#font, is handled specially:

  • If no font is set on a style, the default font specified via the configuration option ‘font.default’ is automatically set because otherwise there would be problems with text drawing operations (font is the only style property that has no valid default value).

  • Standard style objects only allow font wrapper objects to be set via the Layout::Style#font method. This class makes usage easier by allowing strings or an array [name, options_hash] to be used, like with e.g Content::Canvas#font. So to use Helvetica as font, one could just do:

    style.font = 'Helvetica'

    And if Helvetica in its bold variant should be used it would be:

    style.font = ['Helvetica', variant: :bold]

    Helvetica in bold could also be set the conventional way:

    style.font = 'Helvetica bold'

    However, using an array it is also possible to specify other options when setting a font, like the :subset option.

Public Class Methods

new(document)

Creates a new Layout object for the given PDF document.

Public Instance Methods

box(name = :base, width: 0, height: 0, style: nil, **box_options, &block)

Creates the named box and returns it.

The name argument refers to the registered name of the box class that is looked up in the ‘layout.boxes.map’ configuration option. The box_options are passed as-is to the initialization method of that box class.

If a block is provided, a ChildrenCollector is yielded and the collected children are passed to the box initialization method via the :children keyword argument. There is one exception to this rule in case name is base: The provided block is passed to the initialization method of the base box class to function as drawing method.

See text_box for details on width, height and style (note that there is no style_properties argument).

Example:

layout.box(:column, columns: 2, gap: 15)   # => column_box_instance
layout.box(:column) do |column|            # column box with one child
  column.lorem_ipsum
end
layout.box(width: 100) do |canvas, box|
  canvas.line(0, 0, box.content_width, box.content_height).stroke
end
formatted_text(data, width: 0, height: 0, style: nil, properties: nil, box_style: nil, **style_properties)
Alias for: formatted_text_box
formatted_text_box(data, width: 0, height: 0, style: nil, properties: nil, box_style: nil, **style_properties)

Creates a HexaPDF::Layout::TextBox like text_box but allows parts of the text to be formatted differently.

The argument data needs to be an array of String, HexaPDF::Layout::InlineBox and/or Hash objects and is transformed so that it is suitable as argument for the text box initialization method.

  • A String object is treated like {text: data}.

  • A HexaPDF::Layout::InlineBox is used without modification.

  • Hashes can contain any style properties and the following special keys:

    text

    The text to be formatted. If this is set and :box is not, the hash will be transformed into text fragments.

    link

    A URL that should be linked to. If no text is provided but a link, the link is used for the text. If this is set and :box is not, the hash will be transformed into text fragments with an appropriate link overlay.

    style

    The style to use as base style instead of the style created from the style and style_properties arguments. This can either be a style name set via style or anything HexaPDF::Layout::Style::create allows.

    If any style properties are set, the used style is duplicated and the additional properties applied.

    The final style is used for a created text fragment.

    properties

    The custom properties that should be set on the created text fragments.

    box

    An inline box to be used. If this is set, the hash will be transformed into an inline box.

    The value must be one or more (as an array) positional arguments to be used with the inline_box method. The rest of the hash keys are passed as keyword arguments to inline_box except for :block which would be passed as the block.

See text_box for details on width, height, style, style_properties, properties and box_style.

Examples:

# Text without special styling
layout.formatted_text_box(["Some string"])

# A predefined inline box
ibox = layout.inline_box(:text, 'Hello')
layout.formatted_text_box([ibox])

# Text with styling properties
layout.formatted_text_box([{text: "string", fill_color: 128}])

# Text referencing a base style
layout.formatted_text_box([{text: "string", style: :bold}])

# Text with a link
layout.formatted_text_box([{link: "https://example.com",
                            fill_color: 'blue', text: "Example"}])

# Inline boxes created from the given data
layout.formatted_text_box([{box: [:text, "string"], valign: :top}])
block = lambda {|list| list.text("First item"); list.text("Second item") }
layout.formatted_text_box(["Some ", {box: :list, item_spacing: 10, block: block}])

# Combining the above variants
layout.formatted_text_box(["Hello", {box: [:text, 'World!']}, "Here comes a ",
                          {link: 'https://example.com', text: 'link'}, '!',
                          {text: 'And more!', style: :bold, font_size: 20}])

See: text_box, inline_box, HexaPDF::Layout::TextBox, HexaPDF::Layout::TextFragment, HexaPDF::Layout::InlineBox

Also aliased as: formatted_text
image(file, width: 0, height: 0, properties: nil, style: nil, **style_properties)
Alias for: image_box
image_box(file, width: 0, height: 0, properties: nil, style: nil, **style_properties)

Creates a HexaPDF::Layout::ImageBox for the given image.

The file argument can be anything that is accepted by HexaPDF::Document::Images#add or a HexaPDF::Type::Form object.

See text_box for details on width, height, style, style_properties and properties.

Examples:

layout.image_box(machu_picchu, border: {width: 3})
layout.image_box(machu_picchu, height: 30)

See: HexaPDF::Layout::ImageBox

Also aliased as: image
inline_box(box_or_name, *args, valign: :baseline, **kwargs, &block)

Creates an inline box for use together with text fragments.

The valign argument ist used to specify the vertical alignment of the box within the text line. See HexaPDF::Layout::Line for details.

If a box instance is provided as first argument, it is used. Otherwise the first argument has to be the name of a box creation method and args, kwargs and block are passed to it.

Example:

layout.inline_box(:text, "Hallo")
layout.inline_box(:list) {|list| list.text("Hallo") }
lorem_ipsum(sentences: 4, count: 1, **text_box_properties)
Alias for: lorem_ipsum_box
lorem_ipsum_box(sentences: 4, count: 1, **text_box_properties)

Uses text_box to create count paragraphs with sentences number of sentences (1 to 4) of lorem ipsum text.

The text_box_properties arguments are passed as is to text_box.

Also aliased as: lorem_ipsum
method_missing(name, *args, **kwargs, &block)

Allows creating boxes using more convenient method names: The name of a pre-defined box class like column will invoke box appropriately. Same if used with a ‘_box’ suffix.

Calls superclass method
style(name) → style
style(name, base: :base, **properties) → style

Creates or updates the Layout::Style object called name with the given property values and returns it.

If neither base nor any style properties are specified, the style name is just returned.

This method allows convenient access to the stored styles and to update them. Such styles can then be used by name in the various box creation methods, e.g. text_box or image_box.

If the style name does not exist yet and the argument base specifies the name of another style, that style is duplicated and used as basis for the style. This also means that the referenced base style needs be defined first!

The special name :base should be used for setting the base style which is used for the base argument when no specific style is specified.

Note that the style property ‘font’ is handled specially, see the class documentation for details.

Example:

layout.style(:base, font_size: 12, leading: 1.2)
layout.style(:header, font: 'Helvetica', fill_color: "008")
layout.style(:header1, base: :header, font_size: 30)

See: HexaPDF::Layout::Style

styles → styles
styles(**mapping) → styles

Returns the mapping of style names to Layout::Style instances. If mapping is provided, also defines the given styles using style.

The argument mapping needs to be a hash mapping a style name (a Symbol) to style properties. The special key :base can be used to define the base style. For details see style.

table(data, column_widths: nil, header: nil, footer: nil, cell_style: nil, width: 0, height: 0, style: nil, properties: nil, **style_properties)
Alias for: table_box
table_box(data, column_widths: nil, header: nil, footer: nil, cell_style: nil, width: 0, height: 0, style: nil, properties: nil, **style_properties) { |collector| ... }

Creates a HexaPDF::Layout::TableBox for the given table data.

This method is a small wrapper around the actual class and mainly facilitates transforming the contents of the data into the box instances needed by the table box implementation.

In addition to everything the table box implementation allows for data, it is also possible to specify strings as cell contents. Those strings will be converted to text boxes by using the text_box method. Note that this functionality is not available for the header and footer!

Additional arguments for the text_box invocations can be specified using the optional block that yields a CellArgumentCollector instance. This allows customization of the text boxes. By specifying the special key :cell it is also possible to assign style properties to the cells themselves, irrespective of the type of content of the cells. See CellArgumentCollector#[]= for details.

See HexaPDF::Layout::TableBox::new for details on column_widths, header, footer, and cell_style.

See text_box for details on width, height, style, style_properties and properties.

Examples:

layout.table_box([[layout.text('A'), layout.text('B')],
                  [layout.image(image_path), layout.text('D')]]
layout.table_box([['A', 'B'], [layout.image(image_path), 'D]])     # same as above

layout.table_box([['A', 'B'], ['C', 'D]]) do |args|
  # assign the predefined style :cell_text to all texts
  args[] = {style: :cell_text}
  # row 0 has a grey background and bold text
  args[0] = {font: 'Helvetica bold', cell: {background_color: 'eee'}}
  # text in last column is right aligned
  args[0..-1, -1] = {text_align: :right}
end

See: HexaPDF::Layout::TableBox

Also aliased as: table
text(text, width: 0, height: 0, style: nil, properties: nil, box_style: nil, **style_properties)
Alias for: text_box
text_box(text, width: 0, height: 0, style: nil, properties: nil, box_style: nil, **style_properties)

Creates a HexaPDF::Layout::TextBox for the given text.

This method is of the two main methods for creating text boxes, the other being formatted_text_box.

width, height

The arguments width and height are used as constraints and are respected when fitting the box. The default value of 0 means that no constraints are set.

style, style_properties

The box and the text are styled using the given style. This can either be a style name set via style or anything Layout::Style::create accepts. If any additional style_properties are specified, the style is duplicated and the additional styles are applied.

properties

This can be used to set custom properties on the created text box. See Layout::Box#properties for details and usage.

box_style

Sometimes it is necessary for the box to have a different style than the text, e.g. when using overlays. In such a case use box_style for specifiying the style of the box (a style name set via style or anything Layout::Style::create accepts).

The style together with the style_properties will be used for the text style.

Examples:

layout.text_box("Test is on " * 15)
layout.text_box("Now " * 7, width: 100)
layout.text_box("Another test", font_size: 15, fill_color: "hp-blue")
layout.text_box("Different box style", fill_color: 'white', box_style: {
  underlays: [->(c, b) { c.rectangle(0, 0, b.content_width, b.content_height).fill }]
})

See: formatted_text_box, HexaPDF::Layout::TextBox, HexaPDF::Layout::TextFragment

Also aliased as: text
text_fragments(text, style: nil, properties: nil, **style_properties)

Creates an array of HexaPDF::Layout::TextFragment objects for the given text.

This method uses the configuration option ‘font.on_invalid_glyph’ to map Unicode characters without a valid glyph in the given font to zero, one or more glyphs in a fallback font.

style, style_properties

The text is styled using the given style. This can either be a style name set via style or anything Layout::Style::create accepts. If any additional style_properties are specified, the style is duplicated and the additional styles are applied.

properties

This can be used to set custom properties on the created text fragments. See Layout::Box#properties for details and usage.