layout

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 22 Imported by: 4 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package layout implements a high-level, CSS-like element model for building PDF pages from composable building blocks.

Elements are positioned through a two-phase process: layout then render. During layout, each Element is given a LayoutArea and returns a LayoutPlan describing the placed content and any overflow that did not fit. During render, PlacedBlock draw closures emit PDF content-stream operators.

Available elements:

  • Paragraph: text with word wrapping, alignment, and rich-text spans
  • Div: block container with padding, borders, and background
  • Table: row/column grid with cell spanning and border collapse
  • List: ordered and unordered lists with nested sub-lists
  • ImageElement: raster image placement with aspect-ratio control
  • BarcodeElement: inline barcode (QR, Code 128, EAN-13)
  • Heading: section heading for auto-generated bookmarks
  • Flex: flexbox-style row/column layout
  • Grid: CSS Grid-style two-dimensional layout
  • Columns: multi-column text flow with balanced filling
  • Float: float-left/right content wrapping
  • LineSeparator: horizontal rule
  • AreaBreak: force a new page or column
  • Link: clickable hyperlink annotation
  • TabbedLine: tabular alignment with tab stops
  • SVGElement: inline SVG rendering

Affine transformations (rotate, scale, translate) are supported via Div.SetTransform using TransformOp values computed by ComputeTransformMatrix.

The Renderer drives the layout loop: it feeds elements into pages, handles page breaks and overflow, and collects PageResult values containing content streams and resource references.

Index

Examples

Constants

View Source
const CounterPagePlaceholder = "{counter(page)}"

CounterPagePlaceholder is the deferred sentinel produced by CSS `counter(page)` evaluations whose value is not yet known when the containing TextRun is built (HTML→Element conversion runs before pagination). The placeholder travels through paragraph layout and is substituted at content-stream emission with the resolved 1-based page index. The same string is emitted by `html/page.go` for `@page` margin-box content.

A `counter(page)` with an explicit list-style argument (e.g. `counter(page, upper-roman)`) is encoded as `{counter(page,STYLE)}`, where STYLE is the normalized list-style-type. The style-less form below is equivalent to `{counter(page,decimal)}` and is kept verbatim for backward compatibility with existing emitters.

View Source
const CounterPagesPlaceholder = "{counter(pages)}"

CounterPagesPlaceholder is the deferred sentinel for CSS `counter(pages)`. It is substituted with the document's final page total once pagination is complete and emission begins. The styled form is `{counter(pages,STYLE)}` (see CounterPagePlaceholder).

View Source
const LeadingNormal = -1

LeadingNormal is the sentinel Paragraph.SetLeading value for CSS `line-height: normal`. Unlike a literal multiplier, it defers resolution to layout time, where it's derived from the actual font's vertical metrics (see [resolveLineHeight]) instead of a flat fontSize*1.2 — fonts that declare a larger line-gap get proportionally more leading, matching how browsers resolve `normal`.

Variables

View Source
var (
	ColorBlack     = Color{R: 0, G: 0, B: 0}
	ColorWhite     = Color{R: 1, G: 1, B: 1}
	ColorRed       = Color{R: 1, G: 0, B: 0}
	ColorGreen     = Color{R: 0, G: 0.5, B: 0}
	ColorBlue      = Color{R: 0, G: 0, B: 1}
	ColorYellow    = Color{R: 1, G: 1, B: 0}
	ColorCyan      = Color{R: 0, G: 1, B: 1}
	ColorMagenta   = Color{R: 1, G: 0, B: 1}
	ColorGray      = Color{R: 0.5, G: 0.5, B: 0.5}
	ColorLightGray = Color{R: 0.75, G: 0.75, B: 0.75}
	ColorDarkGray  = Color{R: 0.25, G: 0.25, B: 0.25}
	ColorOrange    = Color{R: 1, G: 0.647, B: 0}
	ColorNavy      = Color{R: 0, G: 0, B: 0.5}
	ColorMaroon    = Color{R: 0.5, G: 0, B: 0}
	ColorPurple    = Color{R: 0.5, G: 0, B: 0.5}
	ColorTeal      = Color{R: 0, G: 0.5, B: 0.5}
)

Common color constants.

Functions

func ComputeTransformMatrix

func ComputeTransformMatrix(ops []TransformOp) (a, b, c, d, e, f float64)

ComputeTransformMatrix multiplies all transform operations in order and returns the combined 2D affine matrix [a b c d e f].

The PDF transformation matrix maps to:

| a  b  0 |
| c  d  0 |
| e  f  1 |

func CounterPlaceholder added in v0.9.1

func CounterPlaceholder(name, style string) string

CounterPlaceholder builds the placeholder token for a page/pages counter with an optional list-style. name must be "page" or "pages"; style is a list-style-type ("" or "decimal" yields the canonical style-less placeholder). The token is opaque to everything between emission of the content string and the final substitution pass.

func GraphemeBreaks added in v0.7.0

func GraphemeBreaks(s string) []int

GraphemeBreaks returns the byte offsets of grapheme cluster boundaries in s, including 0 and len(s). See grapheme.Breaks for the underlying implementation.

func GraphemeCount added in v0.7.0

func GraphemeCount(s string) int

GraphemeCount returns the number of extended grapheme clusters in s. See grapheme.Count.

func InsertKashidas added in v0.7.0

func InsertKashidas(s string, count int) string

InsertKashidas returns a copy of s with up to count tatweel characters (U+0640) inserted at the highest-priority candidate sites. If count is zero or there are no legal sites, s is returned unchanged. If count exceeds the number of legal sites, only the available sites are used and the remaining slack is left for the caller to consume by other means (whitespace stretching).

Insertion strategy: candidates are ranked by priority (descending), with ties broken by position (ascending in logical order). At most one tatweel is inserted at each candidate site — duplicates would compound at a single connection and produce a visually wrong stair-stepped result. Callers wanting more elongation than there are sites should fall back to whitespace stretching.

Precondition: count >= 0. Negative counts are treated as zero.

func NextGraphemeBreak added in v0.7.0

func NextGraphemeBreak(s string, start int) int

NextGraphemeBreak returns the byte offset of the next cluster boundary strictly after start, or len(s) if start is already in the final cluster. See grapheme.NextBreak.

func RenderLinearGradient

func RenderLinearGradient(width, height int, angle float64, stops []GradientStop) *image.RGBA

RenderLinearGradient creates a gradient image with the given dimensions, angle (in degrees, 0 = to top, 90 = to right), and color stops. Returns an RGBA image suitable for embedding as a PDF XObject.

func RenderRadialGradient

func RenderRadialGradient(width, height int, stops []GradientStop) *image.RGBA

RenderRadialGradient creates a radial gradient image from center outward. Returns an RGBA image suitable for embedding as a PDF XObject.

func ResolveAll

func ResolveAll(values []UnitValue, totalWidth float64) []float64

ResolveAll converts a slice of UnitValues to point widths. Percentages are resolved against totalWidth. If the values don't sum to totalWidth, the remainder is unaccounted for (callers should validate or normalize as needed).

func ShapeArabic added in v0.7.0

func ShapeArabic(s string) string

ShapeArabic applies Arabic contextual shaping to a string by substituting base Arabic codepoints with their Presentation Forms-B positional variants. Non-Arabic characters pass through unchanged. The function also handles lam-alef ligature formation.

This function should be called on each word's text BEFORE width measurement, since the shaped codepoints may have different glyph widths in the font. Spaces break the joining context, so word-by-word shaping produces correct results for whitespace-delimited Arabic text.

func ShapeArabicWithFont added in v0.7.0

func ShapeArabicWithFont(s string, face font.Face) string

ShapeArabicWithFont applies Arabic contextual shaping using the font's OpenType GSUB tables when available, falling back to the Presentation Forms-B table when the font has no GSUB or for characters not covered by the font's substitutions.

The face parameter is the EmbeddedFont's underlying Face; pass nil to use the Presentation Forms-B table unconditionally.

func ShapeDevanagari added in v0.7.0

func ShapeDevanagari(s string, face font.Face, gsub *font.GSUBSubstitutions) []uint16

ShapeDevanagari is the Devanagari-specific entry point, kept for backwards compatibility with the original API. It forwards to ShapeIndic with devanagariConfig.

func ShapeDevanagariWithEmbedded added in v0.7.0

func ShapeDevanagariWithEmbedded(s string, ef *font.EmbeddedFont) ([]uint16, bool)

ShapeDevanagariWithEmbedded is retained for backwards compatibility. New callers should use ShapeIndicWithEmbedded with the resolved script.

func ShapeIndic added in v0.8.0

func ShapeIndic(s string, face font.Face, gsub *font.GSUBSubstitutions, cfg *indicScriptConfig) []uint16

ShapeIndic runs the full five-phase Indic shaping pipeline on s under the given script config. It is the script-neutral entry point; the script-specific wrappers (ShapeDevanagari, ShapeBengali, etc.) simply select a config and delegate here.

When gsub is nil or the face has no features for this script, the function still runs the scanner and phase-2/phase-4 reordering so that the returned GID stream is in visual order using the base codepoint GIDs. This is the "no-GSUB fallback" and it renders passably for fonts that have glyphs but no shaping tables.

func ShapeIndicWithEmbedded added in v0.8.0

func ShapeIndicWithEmbedded(s string, ef *font.EmbeddedFont, sc Script) ([]uint16, bool)

ShapeIndicWithEmbedded is the script-dispatching convenience wrapper used by paragraph layout. It picks the right config based on the UAX #24 script of the input, pulls GSUB tables from the embedded font, and runs the shaper. Returns (gids, true) on success; (nil, false) if the script is not Indic, the font is nil, or the input is empty.

func ToAlpha added in v0.9.1

func ToAlpha(n int, base byte) string

ToAlpha converts n to alphabetic numbering using base as the first letter ('a' or 'A'): 1=a, 2=b, ..., 26=z, 27=aa. Non-positive n falls back to decimal.

func ToRoman added in v0.9.1

func ToRoman(n int, upper bool) string

ToRoman converts n to a Roman numeral string (lower-case, or upper-case when upper is true). Values outside 1..3999 fall back to decimal.

Types

type AbsoluteOpts

type AbsoluteOpts struct {
	RightAligned bool // x is a right-edge offset
	ZIndex       int  // negative = render behind normal flow
	PageIndex    int  // -1 = last page
	Fixed        bool // position: fixed — draw on every page
}

AbsoluteOpts configures an absolutely positioned element.

type Align

type Align int

Align specifies horizontal text alignment.

const (
	AlignLeft Align = iota
	AlignCenter
	AlignRight
	AlignJustify
)

type AlignItems

type AlignItems int

AlignItems controls alignment of items along the cross axis.

const (
	CrossAlignStretch AlignItems = iota // stretch to fill cross axis (default)
	CrossAlignStart                     // align to cross-start
	CrossAlignEnd                       // align to cross-end
	CrossAlignCenter                    // center on cross axis
)

type AnchorInfo added in v0.10.1

type AnchorInfo struct {
	Name string  // fragment id (the value of href="#name")
	Y    float64 // y position in PDF coordinates (top of the target block)
}

AnchorInfo records a fragment identifier (an element's HTML id) found during rendering, with the y position of its target block's top. The document layer registers these as PDF named destinations.

type AreaBreak

type AreaBreak struct{}

AreaBreak is a layout element that forces a page break. When the renderer encounters an AreaBreak, it starts a new page and continues laying out subsequent elements there.

func NewAreaBreak

func NewAreaBreak() *AreaBreak

NewAreaBreak creates an element that forces a page break.

func (*AreaBreak) Layout

func (ab *AreaBreak) Layout(maxWidth float64) []Line

Layout returns a single line with a page break marker. Retained for internal use; the renderer handles AreaBreak by type assertion.

func (*AreaBreak) PlanLayout

func (ab *AreaBreak) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. AreaBreak is handled by type assertion in the renderer, so this returns an empty plan.

type BackgroundImage

type BackgroundImage struct {
	Image    *folioimage.Image   // the image to draw
	Size     string              // "auto", "cover", "contain"
	SizeW    float64             // explicit width (0 = auto)
	SizeH    float64             // explicit height (0 = auto)
	Position [2]ResolvableLength // x, y; resolved against the background box at draw time
	FontSize float64             // font-size in points, for em/rem resolution of Position
	Repeat   string              // "no-repeat", "repeat", "repeat-x", "repeat-y"
}

BackgroundImage describes a background image for a Div container.

type BarcodeElement

type BarcodeElement struct {
	// contains filtered or unexported fields
}

BarcodeElement is a layout element that renders a barcode in the document flow.

func NewBarcodeElement

func NewBarcodeElement(bc *barcode.Barcode, width float64) *BarcodeElement

NewBarcodeElement creates a layout element from a generated barcode. Width sets the display width in points. Height is computed from the barcode's aspect ratio if 0.

Example
package main

import (
	"fmt"

	"github.com/carlos7ags/folio/barcode"
	"github.com/carlos7ags/folio/layout"
)

func main() {
	bc, _ := barcode.NewQR("https://example.com")
	elem := layout.NewBarcodeElement(bc, 100).SetAlign(layout.AlignCenter)

	plan := elem.PlanLayout(layout.LayoutArea{Width: 468, Height: 500})
	fmt.Println("QR fits:", plan.Status == layout.LayoutFull)

}
Output:
QR fits: true

func (*BarcodeElement) Layout

func (be *BarcodeElement) Layout(maxWidth float64) []Line

Layout implements Element.

func (*BarcodeElement) MaxWidth

func (be *BarcodeElement) MaxWidth() float64

MaxWidth implements Measurable.

func (*BarcodeElement) MinWidth

func (be *BarcodeElement) MinWidth() float64

MinWidth implements Measurable.

func (*BarcodeElement) PlanLayout

func (be *BarcodeElement) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element.

func (*BarcodeElement) SetAlign

func (be *BarcodeElement) SetAlign(a Align) *BarcodeElement

SetAlign sets horizontal alignment.

func (*BarcodeElement) SetAltText added in v0.5.2

func (be *BarcodeElement) SetAltText(text string) *BarcodeElement

SetAltText sets alternative text for accessibility (PDF/UA).

func (*BarcodeElement) SetHeight

func (be *BarcodeElement) SetHeight(h float64) *BarcodeElement

SetHeight sets an explicit display height. If 0, height is computed from the barcode's module aspect ratio.

type Border

type Border struct {
	Width float64     // line width in points (0 = no border)
	Color Color       // stroke color
	Style BorderStyle // line style (default: solid)
}

Border defines the style for one side of a cell or container border.

func DashedBorder

func DashedBorder(width float64, c Color) Border

DashedBorder creates a dashed border with the given width and color.

func DefaultBorder

func DefaultBorder() Border

DefaultBorder returns a thin black solid border.

func DottedBorder

func DottedBorder(width float64, c Color) Border

DottedBorder creates a dotted border with the given width and color.

func DoubleBorder

func DoubleBorder(width float64, c Color) Border

DoubleBorder creates a double-line border with the given width and color. The total visual width is approximately 3x the line width.

func SolidBorder

func SolidBorder(width float64, c Color) Border

SolidBorder creates a solid border with the given width and color.

type BorderStyle

type BorderStyle int

BorderStyle specifies how a border line is drawn.

const (
	BorderSolid  BorderStyle = iota // continuous line (default)
	BorderDashed                    // repeating dash pattern
	BorderDotted                    // repeating dot pattern
	BorderDouble                    // two parallel lines
	BorderNone                      // no border (same as Width=0)
	BorderHidden                    // CSS2.1 §17.6.2: never draws, and always wins a border conflict
)

type BoxShadow

type BoxShadow struct {
	OffsetX float64 // horizontal offset (positive = right)
	OffsetY float64 // vertical offset (positive = down)
	Blur    float64 // blur radius (approximate)
	Spread  float64 // expand/contract shadow size
	Color   Color   // shadow color
}

BoxShadow represents a CSS box-shadow effect.

type Cell

type Cell struct {
	// contains filtered or unexported fields
}

Cell represents a single cell in a table.

func (*Cell) Background added in v0.9.1

func (c *Cell) Background() *Color

Background returns a copy of the cell's background fill color, or nil if the cell has no background. A copy is returned so callers cannot mutate the cell's internal fill through the pointer. Provided for testing.

func (*Cell) BorderRadii added in v0.9.1

func (c *Cell) BorderRadii() [4]float64

BorderRadii returns the cell's per-corner radii in CSS order (top-left, top-right, bottom-right, bottom-left), in points. A value of 0 means the corner is sharp. Provided for testing.

func (*Cell) Content added in v0.9.1

func (c *Cell) Content() Element

Content returns the cell's rich content Element, or nil if the cell holds plain text instead. When the cell owns and draws the box fill (background + border-radius), callers use this to detect and clear a redundant block-level background on the content element (see issue #329).

func (*Cell) SetAlign

func (c *Cell) SetAlign(a Align) *Cell

SetAlign sets the horizontal text alignment within the cell.

func (*Cell) SetBackground

func (c *Cell) SetBackground(color Color) *Cell

SetBackground sets the cell background fill color.

func (*Cell) SetBorderRadius added in v0.6.1

func (c *Cell) SetBorderRadius(r float64) *Cell

SetBorderRadius sets a uniform corner radius on all four corners.

func (*Cell) SetBorderRadiusPerCorner added in v0.6.1

func (c *Cell) SetBorderRadiusPerCorner(tl, tr, br, bl float64) *Cell

SetBorderRadiusPerCorner sets per-corner radii: top-left, top-right, bottom-right, bottom-left (matching CSS border-radius order).

func (*Cell) SetBorders

func (c *Cell) SetBorders(b CellBorders) *Cell

SetBorders sets the cell borders.

func (*Cell) SetColspan

func (c *Cell) SetColspan(n int) *Cell

SetColspan sets the number of columns this cell spans.

func (*Cell) SetPadding

func (c *Cell) SetPadding(p float64) *Cell

SetPadding sets uniform padding on all sides (in points).

func (*Cell) SetPaddingSides

func (c *Cell) SetPaddingSides(p Padding) *Cell

SetPaddingSides sets different padding for each side.

func (*Cell) SetRowspan

func (c *Cell) SetRowspan(n int) *Cell

SetRowspan sets the number of rows this cell spans.

func (*Cell) SetVAlign

func (c *Cell) SetVAlign(v VAlign) *Cell

SetVAlign sets the vertical alignment within the cell.

func (*Cell) SetWidthHint

func (c *Cell) SetWidthHint(pts float64) *Cell

SetWidthHint sets the CSS width hint for this cell (in points). Used by auto-sizing to influence column width allocation.

func (*Cell) SetWidthHintUnit added in v0.6.2

func (c *Cell) SetWidthHintUnit(u UnitValue) *Cell

SetWidthHintUnit sets a lazy width hint resolved at layout time against the column track's available width. Use this instead of SetWidthHint for percentage widths (e.g. <td style="width:50%">) so the hint resolves against the table's actual maxWidth instead of whatever container width was current at convert time. Without lazy resolution, a cell inside a narrow flex column can resolve 50% against the outer page width and overflow the column on render.

type CellBorders

type CellBorders struct {
	Top    Border
	Right  Border
	Bottom Border
	Left   Border
}

CellBorders holds the four borders of a cell or container.

func AllBorders

func AllBorders(b Border) CellBorders

AllBorders returns CellBorders with the same border on all sides.

func NoBorders

func NoBorders() CellBorders

NoBorders returns CellBorders with no borders.

type Clearable

type Clearable interface {
	ClearValue() string // "left", "right", "both", or ""
}

Clearable is implemented by elements that support the CSS clear property.

type Color

type Color struct {
	R, G, B    float64    // RGB components (0-1), used when Space == ColorSpaceRGB
	C, M, Y, K float64    // CMYK components (0-1), used when Space == ColorSpaceCMYK
	Space      ColorSpace // color space (default: RGB)
}

Color represents a color value. The zero value is RGB black. Use RGB(), CMYK(), Gray(), or Hex() constructors to create colors.

func CMYK

func CMYK(c, m, y, k float64) Color

CMYK creates a DeviceCMYK color from values in [0, 1].

func Gray

func Gray(v float64) Color

Gray creates a grayscale Color from a single value in [0, 1] where 0 is black and 1 is white.

func Hex

func Hex(hex string) Color

Hex creates a Color from a hex string like "#FF8800" or "FF8800".

func RGB

func RGB(r, g, b float64) Color

RGB creates a Color from values in [0, 1].

type ColorSpace

type ColorSpace int

ColorSpace identifies the color space of a Color value.

const (
	ColorSpaceRGB  ColorSpace = iota // DeviceRGB (default)
	ColorSpaceCMYK                   // DeviceCMYK
)

type ColumnRule added in v0.6.0

type ColumnRule struct {
	Width float64 // line width in points (default 0 = no rule)
	Color Color   // line color (default black)
	Style string  // "solid" (default), "dashed", "dotted"
}

ColumnRule defines a visual separator drawn between columns.

type Columns

type Columns struct {
	// contains filtered or unexported fields
}

Columns is a block-level element that arranges child elements side by side in equal-width (or custom-width) columns.

func BalancedColumns

func BalancedColumns(cols int, gap float64, elements ...Element) *Columns

BalancedColumns creates a multi-column layout that equalizes column heights. All elements are placed into column 0 initially; at layout time Columns.PlanLayout measures each element and redistributes them across columns using a greedy packing algorithm that targets (totalHeight / numColumns) per column. This produces visually balanced output even when elements have different heights.

func NewColumns

func NewColumns(cols int) *Columns

NewColumns creates a multi-column layout with the given number of columns. Panics if cols < 1.

func (*Columns) Add

func (c *Columns) Add(col int, elem Element) *Columns

Add adds an element to a specific column (0-indexed).

func (*Columns) Layout

func (c *Columns) Layout(maxWidth float64) []Line

Layout implements Element. It lays out each column independently, then combines them row by row, with each output line representing one horizontal slice across all columns.

func (*Columns) PlanLayout

func (c *Columns) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. Columns lay out each column independently and combine them. When balanced is set, elements are redistributed across columns by measured height before final layout.

func (*Columns) SetBalanced added in v0.7.0

func (c *Columns) SetBalanced(b bool) *Columns

SetBalanced enables height-based redistribution at layout time. When true, PlanLayout measures all elements (regardless of which column they were added to) and redistributes them across columns to equalize heights. Elements are packed in document order using a greedy algorithm that targets (totalHeight / numColumns) per column. This is the CSS column-fill: balance behavior.

func (*Columns) SetColumnRule added in v0.6.0

func (c *Columns) SetColumnRule(rule ColumnRule) *Columns

SetColumnRule sets the vertical rule drawn between columns. CSS equivalent: column-rule: 1px solid gray.

func (*Columns) SetColumnRuleWidth added in v0.6.0

func (c *Columns) SetColumnRuleWidth(width float64) *Columns

SetColumnRuleWidth sets just the rule width (shorthand for a solid black rule).

func (*Columns) SetGap

func (c *Columns) SetGap(gap float64) *Columns

SetGap sets the gap between columns in points (default 12). Negative values are clamped to 0.

func (*Columns) SetWidths

func (c *Columns) SetWidths(widths []float64) *Columns

SetWidths sets explicit column width fractions. Each value is a fraction of the total available width (after subtracting gaps). They should sum to 1.0. If not set, columns are equal width.

type Direction added in v0.7.0

type Direction int

Direction specifies the base text direction for bidi (bidirectional) layout. It controls how the Unicode Bidirectional Algorithm (UAX #9) resolves the paragraph embedding level and, consequently, how words are visually ordered on each line and which alignment default applies.

DirectionAuto (the zero value) auto-detects from the first strong directional character in the text — Hebrew/Arabic characters produce RTL, Latin/CJK characters produce LTR, and text with no strong characters falls back to LTR.

DirectionLTR and DirectionRTL set the fallback direction when the text contains no strong directional characters. When strong characters ARE present, the first strong character still determines the resolved direction (per UAX #9 rules P2/P3). This matches CSS `direction` behavior for the common case of pure-script paragraphs. Forcing a base level override on mixed-script text (CSS `unicode-bidi: bidi-override`) is not yet supported.

const (
	DirectionAuto Direction = iota // detect from first strong character (default)
	DirectionLTR                   // left-to-right fallback
	DirectionRTL                   // right-to-left fallback
)

type Div

type Div struct {
	// contains filtered or unexported fields
}

Div is a generic block container that holds child elements. It supports borders, background color, padding, and margin, similar to an HTML <div>. All child elements are laid out vertically within the container's padded area.

Example
package main

import (
	"fmt"

	"github.com/carlos7ags/folio/font"
	"github.com/carlos7ags/folio/layout"
)

func main() {
	box := layout.NewDiv().
		SetPadding(12).
		SetBorder(layout.SolidBorder(1, layout.ColorBlack)).
		SetBackground(layout.ColorLightGray).
		Add(layout.NewHeading("Notice", layout.H2)).
		Add(layout.NewParagraph("Important information goes here.", font.Helvetica, 12))

	plan := box.PlanLayout(layout.LayoutArea{Width: 468, Height: 500})
	fmt.Println("Div fits:", plan.Status == layout.LayoutFull)

}
Output:
Div fits: true

func NewDiv

func NewDiv() *Div

NewDiv creates an empty Div container.

func (*Div) Add

func (d *Div) Add(e Element) *Div

Add appends a child element to the Div.

func (*Div) AddBoxShadow added in v0.6.0

func (d *Div) AddBoxShadow(shadow BoxShadow) *Div

AddBoxShadow appends a box-shadow effect. Multiple shadows are drawn in reverse order (last added is drawn first, appearing behind earlier ones), matching CSS stacking behavior.

func (*Div) AddOverlay

func (d *Div) AddOverlay(elem Element, x, y, width float64, rightAligned bool, zIndex int) *Div

AddOverlay adds an absolutely positioned child element that will be rendered at (x, y) relative to the Div's content area, without participating in normal flow layout. This implements CSS position:absolute within a containing block.

func (*Div) Background added in v0.9.1

func (d *Div) Background() *Color

Background returns a copy of the Div's background fill color, or nil if the Div has no background. A copy is returned so callers cannot mutate the Div's internal fill through the pointer. Provided for testing.

func (*Div) BorderRadii added in v0.9.1

func (d *Div) BorderRadii() [4]float64

BorderRadii returns the per-corner radii in CSS order (top-left, top-right, bottom-right, bottom-left), in points. A value of 0 means the corner is sharp. Provided for testing.

func (*Div) BorderRadiusPercent added in v0.9.1

func (d *Div) BorderRadiusPercent() [4]float64

BorderRadiusPercent returns the per-corner percentage radii as fractions (0..1), indexed [TL, TR, BR, BL]. A zero entry means the corner is driven by an absolute radius (or is sharp). Exposed for introspection and tests.

func (*Div) Children

func (d *Div) Children() []Element

Children returns the child elements of the Div.

func (*Div) ClearHeightUnit

func (d *Div) ClearHeightUnit()

ClearHeightUnit removes the explicit height, reverting to content-based sizing.

func (*Div) ClearValue

func (d *Div) ClearValue() string

ClearValue returns the CSS clear value.

func (*Div) ClearWidthUnit

func (d *Div) ClearWidthUnit()

ClearWidthUnit removes the explicit width, allowing the element to use the full available width from its parent layout area.

func (*Div) ForceHeight

func (d *Div) ForceHeight(u UnitValue)

ForceHeight implements HeightSettable. Sets explicit height for cross-axis stretch.

func (*Div) GetSpaceAfter

func (d *Div) GetSpaceAfter() float64

GetSpaceAfter returns the extra vertical space after the Div.

func (*Div) GetSpaceBefore

func (d *Div) GetSpaceBefore() float64

GetSpaceBefore returns the extra vertical space before the Div.

func (*Div) HasExplicitHeight

func (d *Div) HasExplicitHeight() bool

HasExplicitHeight returns true if the Div has an explicit CSS height set.

func (*Div) KeepTogether added in v0.6.0

func (d *Div) KeepTogether() bool

KeepTogether reports whether the Div should avoid splitting across pages.

func (*Div) Layout

func (d *Div) Layout(maxWidth float64) []Line

Layout returns a single synthetic line representing the Div. It delegates to PlanLayout to compute dimensions.

func (*Div) MaxWidth

func (d *Div) MaxWidth() float64

MaxWidth implements Measurable. Returns padding + max child MaxWidth, or the div's own explicit width if set.

func (*Div) MinWidth

func (d *Div) MinWidth() float64

MinWidth implements Measurable. Returns padding + max child MinWidth, or the div's own explicit width if set.

func (*Div) Padding added in v0.9.1

func (d *Div) Padding() Padding

Padding returns the Div's per-side padding.

func (*Div) PlanLayout

func (d *Div) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. A Div splits its children across pages.

func (*Div) SetAspectRatio added in v0.6.1

func (d *Div) SetAspectRatio(ratio float64) *Div

SetAspectRatio sets the width/height ratio for the Div (CSS aspect-ratio). When set and no explicit height is provided, the height is computed from the width: height = width / ratio. A value of 0 means no constraint.

func (*Div) SetBackground

func (d *Div) SetBackground(c Color) *Div

SetBackground sets the background fill color.

func (*Div) SetBackgroundImage

func (d *Div) SetBackgroundImage(img *BackgroundImage) *Div

SetBackgroundImage sets a background image for the Div container.

func (*Div) SetBorder

func (d *Div) SetBorder(b Border) *Div

SetBorder sets the same border on all four sides.

func (*Div) SetBorderRadius

func (d *Div) SetBorderRadius(r float64) *Div

SetBorderRadius sets a uniform corner radius for all four corners (in points).

func (*Div) SetBorderRadiusPerCorner added in v0.6.0

func (d *Div) SetBorderRadiusPerCorner(tl, tr, br, bl float64) *Div

SetBorderRadiusPerCorner sets per-corner radii: top-left, top-right, bottom-right, bottom-left (matching CSS border-radius order).

func (*Div) SetBorderRadiusPercent added in v0.9.1

func (d *Div) SetBorderRadiusPercent(pct [4]float64) *Div

SetBorderRadiusPercent sets per-corner percentage radii as fractions (0..1), indexed [TL, TR, BR, BL]; 0 means the corner is not a percentage. A percentage corner resolves rx against the box width and ry against the box height at draw time, yielding elliptical corners (e.g. 0.5 on a square box draws a circle; on a rectangle it draws a pill). It composes with SetBorderRadius / SetBorderRadiusPerCorner: a corner with a non-zero percentage overrides the absolute radius for that corner.

func (*Div) SetBorders

func (d *Div) SetBorders(b CellBorders) *Div

SetBorders sets the borders around the Div.

func (*Div) SetBoxShadow

func (d *Div) SetBoxShadow(shadow BoxShadow) *Div

SetBoxShadow sets a single box-shadow effect on the Div, replacing any previously set shadows. For multiple shadows, use AddBoxShadow.

func (*Div) SetClear

func (d *Div) SetClear(v string) *Div

SetClear sets the CSS clear property ("left", "right", "both").

func (*Div) SetHCenter

func (d *Div) SetHCenter(enabled bool) *Div

SetHCenter enables horizontal centering (margin: 0 auto behavior).

func (*Div) SetHRight

func (d *Div) SetHRight(enabled bool) *Div

SetHRight enables right-alignment (margin-left: auto behavior).

func (*Div) SetHeightUnit

func (d *Div) SetHeightUnit(u UnitValue) *Div

SetHeightUnit sets an explicit height as a UnitValue, resolved at layout time. Forces the Div to this exact height (used for CSS height property).

func (*Div) SetKeepTogether added in v0.6.0

func (d *Div) SetKeepTogether(v bool) *Div

SetKeepTogether prevents the Div from splitting across pages (CSS page-break-inside: avoid). If the Div doesn't fit on the current page, it moves to the next page instead of splitting.

func (*Div) SetMaxHeight

func (d *Div) SetMaxHeight(pts float64) *Div

SetMaxHeight sets the maximum outer height of the Div (in points).

func (*Div) SetMaxHeightUnit

func (d *Div) SetMaxHeightUnit(u UnitValue) *Div

SetMaxHeightUnit sets the max-height as a UnitValue, resolved at layout time.

func (*Div) SetMaxWidth

func (d *Div) SetMaxWidth(pts float64) *Div

SetMaxWidth sets the maximum outer width of the Div (in points). The Div will not exceed this width even if more space is available.

func (*Div) SetMaxWidthUnit

func (d *Div) SetMaxWidthUnit(u UnitValue) *Div

SetMaxWidthUnit sets the max-width as a UnitValue, resolved at layout time.

func (*Div) SetMinHeight

func (d *Div) SetMinHeight(pts float64) *Div

SetMinHeight sets the minimum outer height of the Div (in points).

func (*Div) SetMinHeightUnit

func (d *Div) SetMinHeightUnit(u UnitValue) *Div

SetMinHeightUnit sets the min-height as a UnitValue, resolved at layout time.

func (*Div) SetMinWidth

func (d *Div) SetMinWidth(pts float64) *Div

SetMinWidth sets the minimum outer width of the Div (in points).

func (*Div) SetMinWidthUnit

func (d *Div) SetMinWidthUnit(u UnitValue) *Div

SetMinWidthUnit sets the min-width as a UnitValue, resolved at layout time.

func (*Div) SetOpacity

func (d *Div) SetOpacity(o float64) *Div

SetOpacity sets the opacity for the entire Div (0 = transparent, 1 = opaque).

func (*Div) SetOutline

func (d *Div) SetOutline(width float64, style string, color Color, offset float64) *Div

SetOutline sets an outline around the Div (drawn outside the border edge).

func (*Div) SetOverflow

func (d *Div) SetOverflow(v string) *Div

SetOverflow sets the overflow behavior ("visible" or "hidden"). "hidden" clips child content to the Div's bounds.

func (*Div) SetPadding

func (d *Div) SetPadding(p float64) *Div

SetPadding sets uniform padding on all sides.

func (*Div) SetPaddingAll

func (d *Div) SetPaddingAll(p Padding) *Div

SetPaddingAll sets different padding for each side.

func (*Div) SetRelativeOffset

func (d *Div) SetRelativeOffset(dx, dy float64) *Div

SetRelativeOffset sets position:relative offsets. The element is visually shifted by (dx, dy) without affecting layout flow.

func (*Div) SetShrinkToFit added in v0.9.1

func (d *Div) SetShrinkToFit(v bool) *Div

SetShrinkToFit enables shrink-to-fit (CSS fit-content) sizing. When enabled and no explicit width is set, the Div sizes to its content's max-content width (clamped to the available area) instead of filling the area width.

func (*Div) SetSpaceAfter

func (d *Div) SetSpaceAfter(pts float64) *Div

SetSpaceAfter sets extra vertical space after the Div.

func (*Div) SetSpaceBefore

func (d *Div) SetSpaceBefore(pts float64) *Div

SetSpaceBefore sets extra vertical space before the Div.

func (*Div) SetTag added in v0.5.2

func (d *Div) SetTag(tag string) *Div

SetTag sets a custom PDF structure tag for accessibility (PDF/UA). Common tags: "Sect", "Art", "BlockQuote", "Caption", "Part". If empty, the default "Div" tag is used.

func (*Div) SetTransform

func (d *Div) SetTransform(ops []TransformOp) *Div

SetTransform sets the CSS transform operations for this Div.

func (*Div) SetTransformOrigin

func (d *Div) SetTransformOrigin(x, y float64) *Div

SetTransformOrigin sets the transform origin point relative to the element's top-left corner (in points).

func (*Div) SetWidth

func (d *Div) SetWidth(pts float64) *Div

SetWidth sets an explicit outer width for the Div (in points). When set, the Div will use exactly this width (clamped by maxWidth).

func (*Div) SetWidthPercent

func (d *Div) SetWidthPercent(pct float64) *Div

SetWidthPercent sets the outer width as a fraction of the available area width. pct is a value between 0 and 1 (e.g. 0.5 = 50%). Resolved at layout time.

func (*Div) SetWidthUnit

func (d *Div) SetWidthUnit(u UnitValue) *Div

SetWidthUnit sets the width as a UnitValue, resolved lazily at layout time. Use Pt(v) for absolute points or Pct(v) for percentage of available width.

type DrawContext

type DrawContext struct {
	Stream *content.Stream
	Page   *PageResult
	// ActualText, when true, allows drawTextLine to emit ISO 32000-2
	// §14.9.4 /Span /ActualText marked-content sequences around shaped
	// Arabic words so that copy/paste and accessibility tools recover the
	// original Unicode codepoints rather than the Presentation Forms-B
	// substitutions emitted by ShapeArabic. The Renderer sets this from
	// its actualText field; tests that build a DrawContext directly may
	// leave it false to suppress emission.
	ActualText bool
	// PageIdx is the 0-based index of the page this draw call targets.
	// Used to substitute CSS counter(page) placeholders in body-flow
	// text. Tests building a DrawContext for non-paged rendering may
	// leave this zero.
	PageIdx int
	// TotalPages is the final page count of the document, set during the
	// emission pass after pagination completes. Used to substitute
	// counter(pages) placeholders. Zero indicates the count is not yet
	// known; placeholders remain in the emitted text in that case.
	TotalPages int
}

DrawContext provides the rendering target for PlacedBlock.Draw closures.

type Element

type Element interface {
	// PlanLayout computes the layout within the given area.
	// The implementation must not mutate the receiver.
	// If the element doesn't fit entirely, it returns LayoutPartial
	// with Overflow set to a new element containing the remainder.
	PlanLayout(area LayoutArea) LayoutPlan
}

Element is anything the layout engine can render into a page. It computes a height-aware layout plan within a given area, supporting content splitting across pages via overflow.

func NewAnchor added in v0.10.1

func NewAnchor(inner Element, name string) Element

NewAnchor wraps inner so that its first PlacedBlock records name as a named-destination target. The returned Element implements Measurable iff inner does, so wrapping does not change a caller's measurement contract. An empty name is a no-op wrap.

func NewBookmarkAnchor added in v0.8.0

func NewBookmarkAnchor(inner Element, level int, label string, closed bool) Element

NewBookmarkAnchor wraps inner so that its first PlacedBlock records the given bookmark level/label/closed state. The returned Element implements Measurable iff inner does, so wrapping does not change a caller's measurement contract.

An empty label is allowed when level == -1 (a "skip" anchor that suppresses outline emission on a continuation page); a level >= 1 with an empty label still records BookmarkLevel and BookmarkClosed so render_plans can decide what to do, but won't write HeadingText — render_plans drops empty-text entries, so the outline node is effectively suppressed without losing the closed/level intent for downstream debugging.

type ExtGStateEntry

type ExtGStateEntry struct {
	Name    string  // resource name (e.g. "GS1")
	Opacity float64 // ca / CA value (0..1)
}

ExtGStateEntry is a named graphics state dictionary registered on a page.

type Flex

type Flex struct {
	// contains filtered or unexported fields
}

Flex is a container that lays out children using flexbox semantics. It implements Element and Measurable.

func NewFlex

func NewFlex() *Flex

NewFlex creates an empty flex container.

func (*Flex) Add

func (f *Flex) Add(elem Element) *Flex

Add appends a child element with default flex properties (grow=0, shrink=1, basis=auto).

func (*Flex) AddItem

func (f *Flex) AddItem(item *FlexItem) *Flex

AddItem appends a FlexItem with explicit flex properties.

func (*Flex) ClearBackground

func (f *Flex) ClearBackground() *Flex

ClearBackground removes the background color.

func (*Flex) ClearHeightUnit

func (f *Flex) ClearHeightUnit()

ClearHeightUnit removes the forced height.

func (*Flex) ForceHeight

func (f *Flex) ForceHeight(u UnitValue)

ForceHeight implements HeightSettable. Forces height for cross-axis stretch.

func (*Flex) GetSpaceAfter

func (f *Flex) GetSpaceAfter() float64

GetSpaceAfter returns the extra vertical space after the Flex container.

func (*Flex) GetSpaceBefore

func (f *Flex) GetSpaceBefore() float64

GetSpaceBefore returns the extra vertical space before the Flex container.

func (*Flex) HasExplicitHeight

func (f *Flex) HasExplicitHeight() bool

HasExplicitHeight returns true if the Flex has an explicit CSS height set.

func (*Flex) Items added in v0.9.1

func (f *Flex) Items() []*FlexItem

Items returns the flex container's items in layout order. Provided for testing.

func (*Flex) Layout

func (f *Flex) Layout(maxWidth float64) []Line

Layout implements Element.

func (*Flex) MaxWidth

func (f *Flex) MaxWidth() float64

MaxWidth implements Measurable.

func (*Flex) MinWidth

func (f *Flex) MinWidth() float64

MinWidth implements Measurable.

func (*Flex) PlanLayout

func (f *Flex) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element.

func (*Flex) SetAlignContent added in v0.6.0

func (f *Flex) SetAlignContent(j JustifyContent) *Flex

SetAlignContent sets cross-axis distribution for multi-line flex containers (flex-wrap: wrap). Controls how wrapped lines are spaced within the container. Has no effect on single-line flex containers.

func (*Flex) SetAlignItems

func (f *Flex) SetAlignItems(a AlignItems) *Flex

SetAlignItems sets cross-axis alignment for all items.

func (*Flex) SetBackground

func (f *Flex) SetBackground(c Color) *Flex

SetBackground sets the background fill color.

func (*Flex) SetBorder

func (f *Flex) SetBorder(b Border) *Flex

SetBorder sets the same border on all sides.

func (*Flex) SetBorders

func (f *Flex) SetBorders(b CellBorders) *Flex

SetBorders sets the borders around the container.

func (*Flex) SetColumnGap

func (f *Flex) SetColumnGap(gap float64) *Flex

SetColumnGap sets the gap between items on the same line.

func (*Flex) SetDefiniteCrossSize

func (f *Flex) SetDefiniteCrossSize(v bool) *Flex

SetDefiniteCrossSize marks that the Flex operates within a parent that constrains its cross-axis (e.g. a wrapper Div with explicit height). This enables cross-axis stretching even when the Flex itself has no heightUnit.

func (*Flex) SetDirection

func (f *Flex) SetDirection(d FlexDirection) *Flex

SetDirection sets the main axis direction.

func (*Flex) SetGap

func (f *Flex) SetGap(gap float64) *Flex

SetGap sets both row and column gap.

func (*Flex) SetJustifyContent

func (f *Flex) SetJustifyContent(j JustifyContent) *Flex

SetJustifyContent sets main-axis distribution.

func (*Flex) SetPadding

func (f *Flex) SetPadding(p float64) *Flex

SetPadding sets uniform padding on all sides.

func (*Flex) SetPaddingAll

func (f *Flex) SetPaddingAll(p Padding) *Flex

SetPaddingAll sets per-side padding.

func (*Flex) SetRowGap

func (f *Flex) SetRowGap(gap float64) *Flex

SetRowGap sets the gap between wrapped lines.

func (*Flex) SetSpaceAfter

func (f *Flex) SetSpaceAfter(pts float64) *Flex

SetSpaceAfter sets extra vertical space after the container.

func (*Flex) SetSpaceBefore

func (f *Flex) SetSpaceBefore(pts float64) *Flex

SetSpaceBefore sets extra vertical space before the container.

func (*Flex) SetWrap

func (f *Flex) SetWrap(w FlexWrap) *Flex

SetWrap enables or disables wrapping.

type FlexDirection

type FlexDirection int

FlexDirection controls the main axis of the flex container.

const (
	// FlexRow lays out children left-to-right (default).
	FlexRow FlexDirection = iota
	// FlexColumn lays out children top-to-bottom.
	FlexColumn
)

type FlexItem

type FlexItem struct {
	// contains filtered or unexported fields
}

FlexItem wraps a child element with flex-specific properties.

func NewFlexItem

func NewFlexItem(elem Element) *FlexItem

NewFlexItem creates a FlexItem wrapping an element.

func (*FlexItem) Element added in v0.9.1

func (fi *FlexItem) Element() Element

Element returns the layout element wrapped by this flex item. Provided for testing.

func (*FlexItem) SetAlignSelf

func (fi *FlexItem) SetAlignSelf(a AlignItems) *FlexItem

SetAlignSelf overrides the container's align-items for this item.

func (*FlexItem) SetBasis

func (fi *FlexItem) SetBasis(v float64) *FlexItem

SetBasis sets the flex-basis in points. 0 means auto (use intrinsic size).

func (*FlexItem) SetBasisUnit

func (fi *FlexItem) SetBasisUnit(u UnitValue) *FlexItem

SetBasisUnit sets the flex-basis as a UnitValue, resolved lazily at layout time.

func (*FlexItem) SetGrow

func (fi *FlexItem) SetGrow(v float64) *FlexItem

SetGrow sets the flex-grow factor.

func (*FlexItem) SetMarginLeftAuto

func (fi *FlexItem) SetMarginLeftAuto() *FlexItem

SetMarginLeftAuto marks this flex item to absorb remaining horizontal space before it (CSS margin-left: auto in flex row layout — pushes item to right).

func (*FlexItem) SetMarginTopAuto

func (fi *FlexItem) SetMarginTopAuto() *FlexItem

SetMarginTopAuto marks this flex item to absorb remaining vertical space before it (CSS margin-top: auto in flex column layout).

func (*FlexItem) SetMargins

func (fi *FlexItem) SetMargins(top, right, bottom, left float64) *FlexItem

SetMargins sets the margins on a flex item. Negative values extend beyond the parent.

func (*FlexItem) SetShrink

func (fi *FlexItem) SetShrink(v float64) *FlexItem

SetShrink sets the flex-shrink factor.

type FlexWrap

type FlexWrap int

FlexWrap controls whether items wrap to new lines.

const (
	FlexNoWrap FlexWrap = iota // single line (default)
	FlexWrapOn                 // wrap to new lines
)

type Float

type Float struct {
	// contains filtered or unexported fields
}

Float is a layout element that places content to the left or right of the flow, allowing subsequent elements to wrap around it.

Usage:

doc.Add(layout.NewFloat(layout.FloatLeft,
    layout.NewImageElement(img).SetSize(150, 0),
))
doc.Add(layout.NewParagraph("Text wraps around the image...", font.Helvetica, 12))

The Float element produces a PlacedBlock with the floated content and modifies the available width for subsequent siblings.

func NewFloat

func NewFloat(side FloatSide, content Element) *Float

NewFloat creates a floating element.

func (*Float) Layout

func (f *Float) Layout(maxWidth float64) []Line

Layout returns a single line representing the float's dimensions.

func (*Float) MaxWidth

func (f *Float) MaxWidth() float64

MaxWidth implements Measurable.

func (*Float) MinWidth

func (f *Float) MinWidth() float64

MinWidth implements Measurable.

func (*Float) PlanLayout

func (f *Float) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element.

func (*Float) SetMargin

func (f *Float) SetMargin(m float64) *Float

SetMargin sets the gap between the float and surrounding text (default 8pt).

type FloatSide

type FloatSide int

FloatSide specifies which side a floating element is placed on.

const (
	FloatLeft  FloatSide = iota // element floats to the left, text wraps on the right
	FloatRight                  // element floats to the right, text wraps on the left
)

type FontEntry

type FontEntry struct {
	Name     string
	Standard *font.Standard
	Embedded *font.EmbeddedFont
}

FontEntry is a font registered on a rendered page.

type GradientStop

type GradientStop struct {
	Color    Color
	Position float64 // 0-1
	Alpha    float64 // 0 = opaque (default), otherwise in (0, 1]
}

GradientStop defines a color and position within a gradient.

Alpha is the stop's alpha channel in (0, 1]. For backwards compatibility with the previous signature, the zero value is treated as fully opaque — callers that only set Color and Position continue to render exactly as before. SVG `stop-opacity` and CSS `rgba()` in gradient stops use this field to propagate partial transparency into the rasterized output.

A stop with a true 0 alpha (fully transparent) cannot be expressed in this scheme because the zero value is reserved for "opaque". This is a known limitation: CSS `linear-gradient(red, transparent)` still renders the transparent endpoint as opaque black. The practical impact is small — the common SVG use case is `stop-opacity="0.5"` for a semi-transparent midpoint, which this scheme handles correctly.

type Grid

type Grid struct {
	// contains filtered or unexported fields
}

Grid is a container that lays out children using CSS Grid semantics. It implements Element, Measurable, and HeightSettable.

func NewGrid

func NewGrid() *Grid

NewGrid creates an empty grid container.

func (*Grid) AddChild

func (g *Grid) AddChild(e Element) *Grid

AddChild appends a child element to the grid.

func (*Grid) Children added in v0.9.1

func (g *Grid) Children() []Element

Children returns the grid's child elements in insertion order.

func (*Grid) ClearHeightUnit

func (g *Grid) ClearHeightUnit()

ClearHeightUnit removes the forced height.

func (*Grid) ForceHeight

func (g *Grid) ForceHeight(u UnitValue)

ForceHeight implements HeightSettable.

func (*Grid) HasExplicitHeight

func (g *Grid) HasExplicitHeight() bool

HasExplicitHeight returns true if the Grid has an explicit CSS height set.

func (*Grid) Layout

func (g *Grid) Layout(maxWidth float64) []Line

Layout implements the Element interface via a synthetic line.

func (*Grid) MaxWidth

func (g *Grid) MaxWidth() float64

MaxWidth implements Measurable.

func (*Grid) MinWidth

func (g *Grid) MinWidth() float64

MinWidth implements Measurable.

func (*Grid) PlanLayout

func (g *Grid) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element.

func (*Grid) SetAlignContent

func (g *Grid) SetAlignContent(j JustifyContent) *Grid

SetAlignContent sets distribution of rows within the container.

func (*Grid) SetAlignItems

func (g *Grid) SetAlignItems(a AlignItems) *Grid

SetAlignItems sets vertical alignment of items within their cells.

func (*Grid) SetAutoRows

func (g *Grid) SetAutoRows(tracks []GridTrack) *Grid

SetAutoRows sets the implicit row track definitions (grid-auto-rows).

func (*Grid) SetBackground

func (g *Grid) SetBackground(c Color) *Grid

SetBackground sets the background fill color.

func (*Grid) SetBorder

func (g *Grid) SetBorder(b Border) *Grid

SetBorder sets the same border on all sides.

func (*Grid) SetBorders

func (g *Grid) SetBorders(b CellBorders) *Grid

SetBorders sets the borders around the container.

func (*Grid) SetColumnGap

func (g *Grid) SetColumnGap(gap float64) *Grid

SetColumnGap sets only the column gap.

func (*Grid) SetGap

func (g *Grid) SetGap(row, col float64) *Grid

SetGap sets both row and column gaps.

func (*Grid) SetJustifyContent

func (g *Grid) SetJustifyContent(j JustifyContent) *Grid

SetJustifyContent sets distribution of columns within the container.

func (*Grid) SetJustifyItems

func (g *Grid) SetJustifyItems(a AlignItems) *Grid

SetJustifyItems sets horizontal alignment of items within their cells.

func (*Grid) SetPadding

func (g *Grid) SetPadding(p float64) *Grid

SetPadding sets uniform padding on all sides.

func (*Grid) SetPaddingAll

func (g *Grid) SetPaddingAll(p Padding) *Grid

SetPaddingAll sets per-side padding.

func (*Grid) SetPlacement

func (g *Grid) SetPlacement(childIndex int, p GridPlacement) *Grid

SetPlacement sets explicit grid placement for a child by index.

func (*Grid) SetRowGap

func (g *Grid) SetRowGap(gap float64) *Grid

SetRowGap sets only the row gap.

func (*Grid) SetSpaceAfter

func (g *Grid) SetSpaceAfter(pts float64) *Grid

SetSpaceAfter sets extra vertical space after the container.

func (*Grid) SetSpaceBefore

func (g *Grid) SetSpaceBefore(pts float64) *Grid

SetSpaceBefore sets extra vertical space before the container.

func (*Grid) SetTemplateAreas

func (g *Grid) SetTemplateAreas(areas [][]string) *Grid

SetTemplateAreas sets named grid areas for area-based placement.

func (*Grid) SetTemplateColumns

func (g *Grid) SetTemplateColumns(tracks []GridTrack) *Grid

SetTemplateColumns sets the column track definitions.

func (*Grid) SetTemplateRows

func (g *Grid) SetTemplateRows(tracks []GridTrack) *Grid

SetTemplateRows sets the row track definitions.

type GridPlacement

type GridPlacement struct {
	ColStart int
	ColEnd   int
	RowStart int
	RowEnd   int
}

GridPlacement specifies explicit placement of a grid item. Line numbers are 1-based (matching CSS grid-line numbering). A zero value means "auto" (no explicit placement on that axis).

type GridTrack

type GridTrack struct {
	Type  GridTrackType
	Value float64
}

GridTrack defines a single column or row track in a CSS Grid.

type GridTrackType

type GridTrackType int

GridTrackType identifies the unit of a grid track size.

const (
	// GridTrackPx is an absolute size in PDF points.
	GridTrackPx GridTrackType = iota
	// GridTrackPercent is a percentage of the container width.
	GridTrackPercent
	// GridTrackFr is a fractional unit that shares remaining space.
	GridTrackFr
	// GridTrackAuto sizes to fit the content.
	GridTrackAuto
)

type Heading

type Heading struct {
	// contains filtered or unexported fields
}

Heading is a block-level text element with a preset size based on its level. It renders as a bold paragraph with spacing proportional to its level.

func NewHeading

func NewHeading(text string, level HeadingLevel) *Heading

NewHeading creates a heading using a standard font. Uses HelveticaBold by default. The font size is determined by the heading level.

func NewHeadingEmbedded

func NewHeadingEmbedded(text string, level HeadingLevel, ef *font.EmbeddedFont) *Heading

NewHeadingEmbedded creates a heading using an embedded font.

func NewHeadingWithFont

func NewHeadingWithFont(text string, level HeadingLevel, f *font.Standard, fontSize float64) *Heading

NewHeadingWithFont creates a heading with a specific standard font.

func (*Heading) Layout

func (h *Heading) Layout(maxWidth float64) []Line

Layout implements Element. Returns the heading lines with spacing.

func (*Heading) MaxWidth

func (h *Heading) MaxWidth() float64

MaxWidth implements Measurable by delegating to the inner Paragraph.

func (*Heading) MinWidth

func (h *Heading) MinWidth() float64

MinWidth implements Measurable by delegating to the inner Paragraph.

func (*Heading) PlanLayout

func (h *Heading) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element by delegating to the inner Paragraph and overriding the structure tag. When the heading wraps across a page break, the overflow is wrapped in a continuation Heading so the remaining lines on the next page keep their H1-H6 structure tag (see the continuation field).

func (*Heading) SetAlign

func (h *Heading) SetAlign(a Align) *Heading

SetAlign sets the horizontal alignment.

func (*Heading) SetBookmarkClosed added in v0.8.0

func (h *Heading) SetBookmarkClosed(closed bool) *Heading

SetBookmarkClosed marks the heading's outline subtree as collapsed by default in PDF viewers. Corresponds to the CSS bookmark-state: closed property.

func (*Heading) SetBookmarkLabel added in v0.6.0

func (h *Heading) SetBookmarkLabel(label string) *Heading

SetBookmarkLabel overrides the heading text used in the bookmark tree. Empty string means use the heading's text content.

The label is NFC-normalized for consistency with other layout-boundary inputs. Bookmark labels are PDF metadata, not flowed text, but normalizing here keeps the API uniform.

func (*Heading) SetBookmarkLevel added in v0.6.0

func (h *Heading) SetBookmarkLevel(level int) *Heading

SetBookmarkLevel overrides the auto-detected heading level for bookmark generation. Level 0 means use the default heading level. This corresponds to the CSS bookmark-level property.

func (*Heading) SetRuns

func (h *Heading) SetRuns(runs []TextRun) *Heading

SetRuns replaces the heading's paragraph runs with the given styled runs. The runs argument is not mutated: NFC normalization is performed on a fresh copy so callers retain ownership of their input slice.

func (*Heading) SetStringSet added in v0.6.0

func (h *Heading) SetStringSet(name, value string) *Heading

SetStringSet attaches a CSS string-set value to this heading. When the heading is placed during layout, the string value is captured and made available to margin boxes via the string() function.

type HeadingInfo

type HeadingInfo struct {
	Text   string  // heading text / bookmark label
	Level  int     // 1-6 (H1-H6 or explicit bookmark-level)
	Y      float64 // y position in PDF coordinates (top of heading)
	Closed bool    // bookmark-state: closed
}

HeadingInfo records a heading found during rendering.

Despite the name, this collects every block participating in the outline tree — both <h1>-<h6> and any non-heading element with an explicit CSS bookmark-level. Closed reflects bookmark-state: closed and is forwarded to the PDF Outline entry's /Count sign.

type HeadingLevel

type HeadingLevel int

HeadingLevel represents H1 through H6.

const (
	H1 HeadingLevel = iota + 1
	H2
	H3
	H4
	H5
	H6
)

type HeightSettable

type HeightSettable interface {
	ForceHeight(u UnitValue)
	ClearHeightUnit()
	HasExplicitHeight() bool // true if element has a CSS height set
}

HeightSettable is implemented by elements that can have their height forced before layout (used by flex cross-axis stretching).

type Hyphenator

type Hyphenator struct {
	// contains filtered or unexported fields
}

Hyphenator implements the Liang-Knuth hyphenation algorithm used in TeX. It uses a set of patterns to determine valid hyphenation points in words.

func DefaultHyphenator

func DefaultHyphenator() *Hyphenator

DefaultHyphenator returns the shared US English hyphenator instance. It is initialized lazily on first call.

func NewHyphenator

func NewHyphenator(patterns []string) *Hyphenator

NewHyphenator creates a Hyphenator from a list of TeX-format patterns. Each pattern is a string of letters interspersed with digits indicating hyphenation priorities (e.g., ".hy1p" means priority 1 between y and p after word start).

func (*Hyphenator) Hyphenate

func (h *Hyphenator) Hyphenate(word string) []int

Hyphenate returns the valid hyphenation break indices for a word. Each index i means a hyphen can be inserted after word[i-1] (i.e., the word can be split into word[:i] and word[i:]). Short words (fewer than 4 characters) return no break points.

Example
h := DefaultHyphenator()
breaks := h.Hyphenate("hyphenation")
runes := []rune("hyphenation")
var parts []string
prev := 0
for _, b := range breaks {
	parts = append(parts, string(runes[prev:b]))
	prev = b
}
parts = append(parts, string(runes[prev:]))
fmt.Println(strings.Join(parts, "-"))

type ImageElement

type ImageElement struct {
	// contains filtered or unexported fields
}

ImageElement is a layout element that places an image in the document flow.

func NewImageElement

func NewImageElement(img *folioimage.Image) *ImageElement

NewImageElement creates a layout element from an Image. By default, the image scales to fit the available width while preserving aspect ratio.

func (*ImageElement) Layout

func (ie *ImageElement) Layout(maxWidth float64) []Line

Layout implements Element. Returns a single Line representing the image.

func (*ImageElement) MaxWidth

func (ie *ImageElement) MaxWidth() float64

MaxWidth implements Measurable. Returns the explicit width or natural pixel width.

func (*ImageElement) MinWidth

func (ie *ImageElement) MinWidth() float64

MinWidth implements Measurable. Returns the explicit width or 0 (auto).

func (*ImageElement) PlanLayout

func (ie *ImageElement) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. An image never splits — FULL or NOTHING.

func (*ImageElement) SetAlign

func (ie *ImageElement) SetAlign(a Align) *ImageElement

SetAlign sets horizontal alignment of the image.

func (*ImageElement) SetAltText added in v0.5.2

func (ie *ImageElement) SetAltText(text string) *ImageElement

SetAltText sets alternative text for accessibility (PDF/UA). Screen readers use this to describe the image to visually impaired users.

func (*ImageElement) SetMaxSize added in v0.8.0

func (ie *ImageElement) SetMaxSize(maxWidth, maxHeight float64) *ImageElement

SetMaxSize sets CSS-style max-width and max-height upper bounds in PDF points. A value of 0 means "unbounded" on that axis. Bounds apply after the explicit / natural / aspect-ratio size is resolved — they shrink the rendered image while preserving aspect ratio. Pass 0/0 to clear any previous bound.

Per CSS 2.1 §10.7, max-width / max-height apply to replaced elements like <img>: they cap the rendered size without forcing a specific dimension. They never upscale a smaller intrinsic image.

func (*ImageElement) SetMinSize added in v0.8.0

func (ie *ImageElement) SetMinSize(minWidth, minHeight float64) *ImageElement

SetMinSize sets CSS-style min-width and min-height lower bounds in PDF points. A value of 0 means "no minimum" on that axis. Bounds apply after the explicit / natural / aspect-ratio size is resolved and after max-* clamps — min-* wins over max-* when they conflict, per CSS 2.1 §10.7.

func (*ImageElement) SetObjectFit added in v0.6.0

func (ie *ImageElement) SetObjectFit(fit string) *ImageElement

SetObjectFit sets the object-fit CSS property for controlling how the image fills its content box when explicit width and height are both set. Valid values: "contain", "cover", "fill", "none", "scale-down".

func (*ImageElement) SetObjectPosition added in v0.6.0

func (ie *ImageElement) SetObjectPosition(pos string) *ImageElement

SetObjectPosition sets the object-position CSS property for controlling image placement within its content box.

func (*ImageElement) SetSize

func (ie *ImageElement) SetSize(width, height float64) *ImageElement

SetSize sets explicit width and height in PDF points. If either is 0, it is calculated from the other preserving aspect ratio.

type ImageEntry

type ImageEntry struct {
	Name  string
	Image *folioimage.Image
}

ImageEntry is an image registered on a rendered page.

type JustifyContent

type JustifyContent int

JustifyContent controls distribution of items along the main axis.

const (
	JustifyFlexStart    JustifyContent = iota // pack toward start (default)
	JustifyFlexEnd                            // pack toward end
	JustifyCenter                             // center along main axis
	JustifySpaceBetween                       // equal space between items
	JustifySpaceAround                        // equal space around items
	JustifySpaceEvenly                        // equal space everywhere
)

type KashidaCandidate added in v0.7.0

type KashidaCandidate struct {
	// Position is the byte offset where a tatweel would be inserted.
	Position int
	// Priority indicates how preferred this site is. Higher values are
	// preferred. The priority table is documented above this type.
	Priority uint8
}

KashidaCandidate marks one rune-boundary position in a string where inserting a tatweel (U+0640) is legal under the simplified Arabic joining rules. Position is the byte offset of the boundary in the original string — i.e. the byte index at which a U+0640 would be inserted, NOT the byte offset of either neighbour.

func FindKashidaCandidates added in v0.7.0

func FindKashidaCandidates(s string) []KashidaCandidate

FindKashidaCandidates returns every legal tatweel insertion point in s, in left-to-right (logical) byte order. A site is legal when the rune to the left of the boundary can join on its left side AND the rune to the right can join on its right side. Each candidate carries a priority derived from the simple heuristic described in the priority constants.

The function operates on both raw Arabic codepoints and on already- shaped Presentation Forms-B glyphs, so callers can apply it either before or after Arabic shaping.

type LayoutArea

type LayoutArea struct {
	Width  float64 // available width in PDF points
	Height float64 // remaining height on the current page

	// AtFragmentTop reports that nothing has been placed above this area in
	// the current fragmentainer (page), so moving the element to the next
	// page would not give it more room. A container that would otherwise
	// defer content which cannot fit (returning LayoutNothing so it restarts
	// on a fresh page) must instead make progress here: place the oversized
	// child — splitting it, or letting an unsplittable one overflow — and
	// paginate what follows. Set by the renderer at the top of a page and
	// propagated by containers to their first in-flow child.
	AtFragmentTop bool
}

LayoutArea describes the available space for laying out an element.

type LayoutPlan

type LayoutPlan struct {
	Status   LayoutStatus  // how much fit
	Consumed float64       // total height consumed by fitted content
	Blocks   []PlacedBlock // positioned content ready to draw
	Overflow Element       // the part that didn't fit (nil if LayoutFull)
}

LayoutPlan is the immutable result of laying out an element. It contains positioned content blocks ready to draw, plus any overflow content that didn't fit in the available area.

LayoutPlan is pure data — no methods, no mutation, no side effects. This enables caching, concurrent layout, and easy testing.

type LayoutStatus

type LayoutStatus int

LayoutStatus indicates how much of an element fit in the available area.

const (
	// LayoutFull means the element fit entirely within the area.
	LayoutFull LayoutStatus = iota

	// LayoutPartial means part of the element fit. The fitted portion
	// is in LayoutPlan.Blocks; the remainder is in LayoutPlan.Overflow.
	LayoutPartial

	// LayoutNothing means the element could not fit at all;
	// the area is too small even for the first line or row.
	LayoutNothing
)

type Line

type Line struct {
	Words  []Word  // the words on this line (nil for table rows)
	Width  float64 // actual content width (sum of word widths + spaces)
	Height float64 // line height (fontSize * leading)
	SpaceW float64 // default space width (used for single-font lines)
	Align  Align   // alignment for this line
	IsLast bool    // true if this is the last line of a paragraph (justify→left)

	// Box model fields.
	SpaceBefore  float64 // extra vertical space before this line (points)
	SpaceAfterV  float64 // extra vertical space after this line (points)
	Background   *Color  // if non-nil, fill rect behind this line
	KeepWithNext bool    // don't page-break between this line and the next

	// Tagged PDF fields.
	StructTag string // if non-empty, wrap content in BDC/EMC with this tag
	MCID      int    // marked content ID (-1 = unassigned; set by document layer)
	Tagged    bool   // whether this line should emit marked content operators
	HintTag   string // element-provided tag override (e.g. "H1" for headings)
	// contains filtered or unexported fields
}

Line is a single horizontal line produced by layout. It carries enough information for the renderer to emit PDF operators.

func (*Line) IsTable

func (l *Line) IsTable() bool

IsTable reports whether a Line was produced by a Table element.

type LineSeparator

type LineSeparator struct {
	// contains filtered or unexported fields
}

LineSeparator is a layout element that draws a horizontal rule across the available width. Used to visually separate sections.

func NewLineSeparator

func NewLineSeparator() *LineSeparator

NewLineSeparator creates a thin black horizontal rule.

func (*LineSeparator) Layout

func (ls *LineSeparator) Layout(maxWidth float64) []Line

Layout implements Element.

func (*LineSeparator) MaxWidth

func (ls *LineSeparator) MaxWidth() float64

MaxWidth implements Measurable. A separator fills available width.

func (*LineSeparator) MinWidth

func (ls *LineSeparator) MinWidth() float64

MinWidth implements Measurable. A separator has no minimum width.

func (*LineSeparator) PlanLayout

func (ls *LineSeparator) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. A separator never splits — it's FULL or NOTHING.

func (*LineSeparator) SetAlign

func (ls *LineSeparator) SetAlign(a Align) *LineSeparator

SetAlign sets alignment when fraction < 1.0.

func (*LineSeparator) SetColor

func (ls *LineSeparator) SetColor(c Color) *LineSeparator

SetColor sets the stroke color.

func (*LineSeparator) SetFraction

func (ls *LineSeparator) SetFraction(f float64) *LineSeparator

SetFraction sets what fraction of available width to draw (0–1). Default is 1.0 (full width). Use with SetAlign to position shorter rules.

func (*LineSeparator) SetSpaceAfter

func (ls *LineSeparator) SetSpaceAfter(pts float64) *LineSeparator

SetSpaceAfter sets vertical space below the separator.

func (*LineSeparator) SetSpaceBefore

func (ls *LineSeparator) SetSpaceBefore(pts float64) *LineSeparator

SetSpaceBefore sets vertical space above the separator.

func (*LineSeparator) SetStyle

func (ls *LineSeparator) SetStyle(s BorderStyle) *LineSeparator

SetStyle sets the line style (solid, dashed, dotted).

func (*LineSeparator) SetWidth

func (ls *LineSeparator) SetWidth(w float64) *LineSeparator

SetWidth sets the line width in points.

type Link struct {
	// contains filtered or unexported fields
}

Link is a layout element that renders clickable styled text inline. It produces text words (like a Paragraph) but also carries a URI or named destination so the renderer can create a link annotation.

Usage:

doc.Add(layout.NewLink("Click here", "https://example.com", font.Helvetica, 12))
func NewInternalLink(text, destName string, f *font.Standard, fontSize float64) *Link

NewInternalLink creates a link to a named destination within the document.

func NewInternalLinkEmbedded added in v0.11.0

func NewInternalLinkEmbedded(text, destName string, ef *font.EmbeddedFont, fontSize float64) *Link

NewInternalLinkEmbedded creates a link to a named destination within the document, rendered with an embedded font.

func NewLink(text, uri string, f *font.Standard, fontSize float64) *Link

NewLink creates a link element with an external URI. The text is rendered as a styled paragraph and the entire area becomes a clickable link annotation.

func NewLinkEmbedded

func NewLinkEmbedded(text, uri string, ef *font.EmbeddedFont, fontSize float64) *Link

NewLinkEmbedded creates a link with an embedded font.

func (*Link) Layout

func (l *Link) Layout(maxWidth float64) []Line

Layout implements Element. Returns the paragraph's lines with link metadata attached so the renderer can create annotations.

func (*Link) MaxWidth

func (l *Link) MaxWidth() float64

MaxWidth implements Measurable by delegating to the inner Paragraph.

func (*Link) MinWidth

func (l *Link) MinWidth() float64

MinWidth implements Measurable by delegating to the inner Paragraph.

func (*Link) PlanLayout

func (l *Link) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element by delegating to the inner Paragraph and attaching link metadata to each placed block.

func (*Link) SetAlign

func (l *Link) SetAlign(a Align) *Link

SetAlign sets horizontal alignment.

func (*Link) SetColor

func (l *Link) SetColor(c Color) *Link

SetColor sets the text color (default is inherited from the paragraph).

func (*Link) SetUnderline

func (l *Link) SetUnderline() *Link

SetUnderline adds underline decoration to the link text.

type LinkArea

type LinkArea struct {
	X, Y, W, H float64 // bounding box in PDF points (bottom-left origin)
	URI        string  // external URL (empty if internal link)
	DestName   string  // internal named destination (empty if external)
}

LinkArea describes a clickable region on a rendered page.

type List

type List struct {
	// contains filtered or unexported fields
}

List is a block-level element that renders ordered or unordered items.

func NewList

func NewList(f *font.Standard, fontSize float64) *List

NewList creates an unordered list with a standard font.

func NewListEmbedded

func NewListEmbedded(ef *font.EmbeddedFont, fontSize float64) *List

NewListEmbedded creates an unordered list with an embedded font.

func (*List) AddItem

func (l *List) AddItem(text string) *List

AddItem adds a text item to the list.

func (*List) AddItemElement added in v0.9.1

func (l *List) AddItemElement(elem Element) *List

AddItemElement adds an item whose content is a rich Element (for block-level <li> children or a styled <li> box). The list marker is aligned to the first text line of the element rather than rendered inline with text runs. The element is laid out within the item's content column (to the right of the marker).

func (*List) AddItemElementWithSubList added in v0.9.1

func (l *List) AddItemElementWithSubList(elem Element) *List

AddItemElementWithSubList adds a rich-element item and returns a nested sub-list under it. The sub-list inherits the parent's font and font size.

func (*List) AddItemRuns added in v0.4.2

func (l *List) AddItemRuns(runs []TextRun) *List

AddItemRuns adds an item with styled text runs, supporting links, mixed fonts, and other inline formatting within the list item.

The Text field of every run is NFC-normalized into a freshly allocated slice so List measurement (MinWidth, MaxWidth) sees the same canonical form as Layout, and the caller's slice is not mutated.

func (*List) AddItemRunsWithSubList added in v0.4.2

func (l *List) AddItemRunsWithSubList(runs []TextRun) *List

AddItemRunsWithSubList adds a styled-runs item and returns a nested sub-list under it.

The run slice is copied and NFC-normalized so the caller's slice is not mutated and List measurement sees canonical text.

func (*List) AddItemWithSubList

func (l *List) AddItemWithSubList(text string) *List

AddItemWithSubList adds a text item and returns a nested sub-list under that item. The sub-list inherits the parent's font and font size.

func (*List) Indent added in v0.9.1

func (l *List) Indent() float64

Indent returns the left indent for item text. Item content (text runs or a rich element) is laid out in the column from this indent to the available width, so percentage box-model values on an element item must resolve against (availableWidth - Indent).

func (*List) Layout

func (l *List) Layout(maxWidth float64) []Line

Layout implements Element. Each item is rendered as a paragraph with a bullet or number prefix, indented from the left margin.

func (*List) MaxWidth

func (l *List) MaxWidth() float64

MaxWidth implements Measurable. Returns indent + widest item line.

func (*List) MinWidth

func (l *List) MinWidth() float64

MinWidth implements Measurable. Returns indent + widest word.

func (*List) PlanLayout

func (l *List) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. Lists split between items.

func (*List) SetDirection added in v0.7.0

func (l *List) SetDirection(d Direction) *List

SetDirection sets the text direction for list items. When RTL, markers are positioned on the right side and item text is indented from the right margin. Item paragraphs inherit this direction for bidi reordering.

func (*List) SetIndent

func (l *List) SetIndent(indent float64) *List

SetIndent sets the left indent for item text (default 18pt).

func (*List) SetLastItemMarker added in v0.9.1

func (l *List) SetLastItemMarker(text string) *List

SetLastItemMarker sets a verbatim CSS marker string on the most recently appended item (from li::marker { content }), overriding the style-derived marker. It is a no-op when the list has no items.

func (*List) SetLeading

func (l *List) SetLeading(leading float64) *List

SetLeading sets the line height multiplier.

func (*List) SetMarkerColor added in v0.6.0

func (l *List) SetMarkerColor(c Color) *List

SetMarkerColor sets an override color for list markers.

func (*List) SetMarkerFont added in v0.10.0

func (l *List) SetMarkerFont(std *font.Standard, emb *font.EmbeddedFont) *List

SetMarkerFont sets an override font for list markers, independent of the list's body font (used for CSS `::marker { font-style: italic }`). Exactly one of std/emb should be non-nil, mirroring how the list itself carries either a standard or an embedded font.

func (*List) SetMarkerFontSize added in v0.6.0

func (l *List) SetMarkerFontSize(size float64) *List

SetMarkerFontSize sets an override font size for list markers.

func (*List) SetMarkerInside added in v0.9.1

func (l *List) SetMarkerInside(inside bool) *List

SetMarkerInside controls marker placement. When inside is true (CSS list-style-position: inside) the marker flows inline with the first content line and wrapped lines align under the marker. The default (false) is outside: the marker sits in the left gutter with a hanging indent.

func (*List) SetStart added in v0.9.1

func (l *List) SetStart(n int) *List

SetStart sets the ordinal of the first item's marker for ordered lists, matching the HTML <ol start="N"> attribute. The first item is numbered n, the second n+1, and so on. Values below 1 are clamped to 1.

func (*List) SetStyle

func (l *List) SetStyle(s ListStyle) *List

SetStyle sets the list marker style (bullet, decimal, roman, alpha, or none).

func (*List) Start added in v0.9.1

func (l *List) Start() int

Start returns the ordinal of the first item's marker for ordered lists, i.e. the value set via SetStart (or the HTML <ol start="N"> attribute). It defaults to 1 when no start was configured.

type ListStyle

type ListStyle int

ListStyle determines the marker style for list items.

const (
	ListUnordered      ListStyle = iota // bullet points: •
	ListOrdered                         // decimal: 1. 2. 3.
	ListOrderedRoman                    // lower roman: i. ii. iii. iv.
	ListOrderedRomanUp                  // upper roman: I. II. III. IV.
	ListOrderedAlpha                    // lower alpha: a. b. c.
	ListOrderedAlphaUp                  // upper alpha: A. B. C.
	ListNone                            // no marker
)

type MarginBox

type MarginBox struct {
	Content  string     // template string with placeholders
	FontSize float64    // font size in points (0 = default 9pt)
	Color    [3]float64 // RGB color (0-1 each)
	// HasColor is true only when the source CSS explicitly set a `color`
	// declaration. It distinguishes an explicit `color: black` ({0,0,0})
	// from an unset color: when false the renderer applies the default
	// gray; when true it honours Color verbatim (including pure black).
	HasColor bool
	// Font is the standard PDF font to draw with when Embedded is nil,
	// resolved from the margin box's own font-style/font-weight/
	// font-family declarations. nil falls back to plain Helvetica — the
	// pre-fix behavior for a box with no font declarations of its own.
	Font *font.Standard
	// Embedded is the document's default body font, used to draw the
	// margin-box text. When non-nil the renderer emits the text with this
	// embedded font (Identity-H GID encoding), so the glyphs are subset
	// and embedded — required for PDF/A. When nil the renderer falls back
	// to Font, or plain Helvetica if Font is also nil.
	Embedded *font.EmbeddedFont
}

MarginBox holds the content template for a CSS margin box. Content may contain placeholders like {counter(page)} and {counter(pages)}.

type MarginBoxSet

type MarginBoxSet struct {
	Boxes map[string]MarginBox // e.g. "top-center" → content
}

MarginBoxSet holds margin boxes for a page variant.

type Margins

type Margins struct {
	Top    float64
	Right  float64
	Bottom float64
	Left   float64
}

Margins defines the page margins in PDF points.

type Measurable

type Measurable interface {
	// MinWidth returns the narrowest width this element can be rendered
	// at without clipping or overflow. For text, this is typically the
	// width of the longest word. For images, the minimum display width.
	MinWidth() float64

	// MaxWidth returns the natural width this element wants if
	// unconstrained. For text, this is the width of the entire text
	// on a single line. For images, the natural pixel width.
	MaxWidth() float64
}

Measurable is an optional interface that elements can implement to report their intrinsic width constraints. This enables features like auto-sizing table columns based on cell content.

type Padding

type Padding struct {
	Top    float64
	Right  float64
	Bottom float64
	Left   float64
}

Padding defines the padding on each side of a container.

func UniformPadding

func UniformPadding(p float64) Padding

UniformPadding creates Padding with the same value on all sides.

type PageResult

type PageResult struct {
	Stream     *content.Stream
	Fonts      []FontEntry
	Images     []ImageEntry
	Links      []LinkArea       // clickable link annotations produced by Link elements
	ExtGStates []ExtGStateEntry // graphics state dictionaries (opacity, etc.)
	Headings   []HeadingInfo    // headings found on this page (for auto-bookmarks)
	Anchors    []AnchorInfo     // fragment ids found on this page (for named destinations)
	PageHeight float64          // actual page height (non-zero only for auto-sized pages)
}

PageResult holds the content stream and font/image resources for one rendered page.

type Paragraph

type Paragraph struct {
	// contains filtered or unexported fields
}

Paragraph is a block of text that word-wraps within the available width. It is composed of one or more TextRuns, each with its own font, size, and color. All runs flow together as a single word-wrapped unit.

Example
package main

import (
	"fmt"

	"github.com/carlos7ags/folio/font"
	"github.com/carlos7ags/folio/layout"
)

func main() {
	p := layout.NewParagraph("Hello, World!", font.Helvetica, 12).
		SetAlign(layout.AlignCenter).
		SetSpaceBefore(10)

	plan := p.PlanLayout(layout.LayoutArea{Width: 468, Height: 500})
	fmt.Println("Status:", plan.Status == layout.LayoutFull)
	fmt.Println("Blocks:", len(plan.Blocks))

}
Output:
Status: true
Blocks: 1

func NewParagraph

func NewParagraph(text string, f *font.Standard, fontSize float64) *Paragraph

NewParagraph creates a paragraph with a single run using a standard PDF font. Panics if f is nil or fontSize is not positive.

func NewParagraphEmbedded

func NewParagraphEmbedded(text string, ef *font.EmbeddedFont, fontSize float64) *Paragraph

NewParagraphEmbedded creates a paragraph with a single run using an embedded font. Panics if ef is nil or fontSize is not positive.

func NewParagraphFallback added in v0.8.0

func NewParagraphFallback(text string, fb *font.Fallback, fontSize float64) *Paragraph

NewParagraphFallback creates a paragraph that mixes scripts in a single string by dispatching each script run to the first face in fb that covers its base codepoint. Internally the paragraph is built as N TextRuns, one per (face, substring) segment, so the rest of the pipeline (shaping, measurement, drawing, subsetting, ToUnicode) runs unchanged on each segment.

Phase 1 scope: cross-script fallback only. A whole script run (per UAX #24, with Common/Inherited resolved against neighbours) is locked to a single face so that per-script shapers (Arabic positional joining, Devanagari cluster formation, GPOS mark-to-base) see a coherent input. Within-script coverage gaps -- e.g. a Latin face missing U+1E9E -- are not yet resolved and will render as .notdef tofu; this is a Phase 2 extension that requires per-cluster face dispatch with shaper coordination.

Pointer identity: the *EmbeddedFont pointers stored on Fallback are passed verbatim into the generated TextRuns. The page-level font resource map dedupes by pointer, so the document still emits one Type0 font dict per underlying face regardless of how many paragraphs share the Fallback.

Panics if fb is nil or fontSize is not positive.

func NewStyledParagraph

func NewStyledParagraph(runs ...TextRun) *Paragraph

NewStyledParagraph creates a paragraph from multiple styled runs. Runs are concatenated and word-wrapped as a single flowing text. Panics if any text run has both Font and Embedded nil. Runs with InlineElement or IsLineBreak set are exempt from the font requirement.

The runs argument is not mutated. NFC normalization is performed on a fresh copy so callers retain ownership of their input slice.

func (*Paragraph) AddRun

func (p *Paragraph) AddRun(r TextRun) *Paragraph

AddRun appends a styled run to the paragraph. Panics if the run has both Font and Embedded nil (unless InlineElement or IsLineBreak is set).

func (*Paragraph) Align added in v0.8.0

func (p *Paragraph) Align() Align

Align reports the paragraph's text alignment. Returns the value most recently set via SetAlign, or the zero-value AlignLeft if SetAlign has never been called.

func (*Paragraph) Background added in v0.9.1

func (p *Paragraph) Background() *Color

Background returns a copy of the paragraph's background fill color, or nil if the paragraph has no block-level background. A copy is returned so callers cannot mutate the paragraph's internal fill through the pointer. Provided for testing and for callers that own the box fill (e.g. a wrapping Div) and need to detect and clear a redundant paragraph-level background.

func (*Paragraph) ClearBackground added in v0.9.1

func (p *Paragraph) ClearBackground() *Paragraph

ClearBackground removes the paragraph's block-level background fill. Per-run/word BackgroundColor (inline <span> highlights) is unaffected.

func (*Paragraph) ClearMatchingRunBackgrounds added in v0.9.1

func (p *Paragraph) ClearMatchingRunBackgrounds(bg Color) bool

ClearMatchingRunBackgrounds removes the per-run/word BackgroundColor highlight from every TextRun whose background equals bg. It returns true if at least one run background was cleared.

This exists for the case where an inline element (e.g. a bare <span>) that carries a block-level background is blockified into its own rounded box. The span's CSS background becomes a TextRun.BackgroundColor highlight, which the renderer paints as a plain (square-cornered) rectangle behind the text. When a wrapping Div now owns and draws the rounded box fill, that run highlight is a redundant square overdraw on top of the rounded corners (issue #329). Clearing it leaves a single rounded fill.

func (*Paragraph) Direction added in v0.7.0

func (p *Paragraph) Direction() Direction

Direction returns the paragraph's base text direction setting.

func (*Paragraph) GetSpaceAfter

func (p *Paragraph) GetSpaceAfter() float64

GetSpaceAfter returns the extra vertical space after the paragraph.

func (*Paragraph) GetSpaceBefore

func (p *Paragraph) GetSpaceBefore() float64

GetSpaceBefore returns the extra vertical space before the paragraph.

func (*Paragraph) HasRunBackground added in v0.9.1

func (p *Paragraph) HasRunBackground(bg Color) bool

HasRunBackground reports whether any TextRun carries a per-run/word BackgroundColor highlight equal to bg.

func (*Paragraph) Layout

func (p *Paragraph) Layout(maxWidth float64) []Line

Layout implements Element. It splits the paragraph text into wrapped lines that fit within maxWidth. Words from different runs carry their own styling.

func (*Paragraph) MaxWidth

func (p *Paragraph) MaxWidth() float64

MaxWidth implements Measurable. Returns the width of all text on a single line (the natural width without wrapping). Forced line breaks (a preserved newline under white-space:pre/pre-wrap/pre-line, or a <br> run) end a line, so the result is the widest such line. Each line keeps the same trailing inter-run space a single-line paragraph is measured with.

func (*Paragraph) MeasureHeight added in v0.8.0

func (p *Paragraph) MeasureHeight(maxWidth float64) float64

MeasureHeight reports the rendered height (in points) of this paragraph at maxWidth — the sum of each line's Height. Does NOT include SpaceBefore or SpaceAfter; the caller adds those if relevant.

Safe to call concurrently with other read methods (Layout, MeasureLines) as long as no goroutine is mutating the paragraph through setters.

func (*Paragraph) MeasureLines added in v0.8.0

func (p *Paragraph) MeasureLines(maxWidth float64) int

MeasureLines reports how many wrapped lines this paragraph produces at maxWidth. Equivalent to len(p.Layout(maxWidth)). Useful for clamp decisions ("if MeasureLines > 8 then split") without inspecting words.

Safe to call concurrently with other read methods (Layout, MeasureHeight) as long as no goroutine is mutating the paragraph through setters.

func (*Paragraph) MinWidth

func (p *Paragraph) MinWidth() float64

MinWidth implements Measurable. Returns the width of the longest word (the narrowest the paragraph can be without clipping). Under white-space:nowrap there is no wrap opportunity at all, so the paragraph can't shrink below its full single-line width — a shrink-to-fit/auto-width container sized to the longest *word* would be too narrow and the nowrap text would overflow it.

func (*Paragraph) PlanLayout

func (p *Paragraph) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. It computes word-wrapped lines that fit within the available area. If the paragraph doesn't fit entirely, it returns LayoutPartial with the remaining words as the Overflow element.

func (*Paragraph) Runs added in v0.8.0

func (p *Paragraph) Runs() []TextRun

Runs returns a copy of the paragraph's text runs for inspection. Mutating the returned slice does not affect the paragraph.

func (*Paragraph) SetAlign

func (p *Paragraph) SetAlign(a Align) *Paragraph

SetAlign sets the horizontal text alignment. When this method is called explicitly, the alignment is treated as an author override and will not be changed by the automatic RTL default (which would otherwise flip the alignment to AlignRight for right-to-left paragraphs).

func (*Paragraph) SetBackground

func (p *Paragraph) SetBackground(c Color) *Paragraph

SetBackground sets a background fill color for the paragraph.

func (*Paragraph) SetDirection added in v0.7.0

func (p *Paragraph) SetDirection(d Direction) *Paragraph

SetDirection sets the base text direction for bidi layout. The default is DirectionAuto, which auto-detects from the first strong directional character in the paragraph text. When direction resolves to RTL and no explicit SetAlign call has been made, the paragraph defaults to right-aligned.

func (*Paragraph) SetEllipsis

func (p *Paragraph) SetEllipsis(v bool) *Paragraph

SetEllipsis enables or disables text truncation with "..." when text overflows the available width. Typically used with overflow:hidden and a fixed width container.

func (*Paragraph) SetFirstLineIndent

func (p *Paragraph) SetFirstLineIndent(pts float64) *Paragraph

SetFirstLineIndent sets the indentation for the first line (in points). This corresponds to the CSS text-indent property.

func (*Paragraph) SetHyphens

func (p *Paragraph) SetHyphens(h string) *Paragraph

SetHyphens sets the hyphenation mode. "auto" enables automatic hyphenation at syllable boundaries. "none" disables all hyphenation. "manual" (default) only breaks at soft hyphens (&shy;).

func (*Paragraph) SetLeading

func (p *Paragraph) SetLeading(l float64) *Paragraph

SetLeading sets the line height multiplier (default 1.2).

func (*Paragraph) SetNoWrap added in v0.11.0

func (p *Paragraph) SetNoWrap(noWrap bool) *Paragraph

SetNoWrap sets CSS white-space:nowrap behavior. When true, a word wider than the available width overflows rather than being character-broken — matching how browsers treat an unbreakable nowrap run. Default is false.

func (*Paragraph) SetOrphans

func (p *Paragraph) SetOrphans(n int) *Paragraph

SetOrphans sets the minimum number of lines that must remain at the bottom of a page before a page break. If fewer lines would remain, the entire paragraph is pushed to the next page (via KeepWithNext). Default is 0 (disabled). Typical value: 2.

func (*Paragraph) SetSpaceAfter

func (p *Paragraph) SetSpaceAfter(pts float64) *Paragraph

SetSpaceAfter sets extra vertical space after the paragraph (in points).

func (*Paragraph) SetSpaceBefore

func (p *Paragraph) SetSpaceBefore(pts float64) *Paragraph

SetSpaceBefore sets extra vertical space before the paragraph (in points).

func (*Paragraph) SetStringSet added in v0.6.0

func (p *Paragraph) SetStringSet(name, value string) *Paragraph

SetStringSet attaches a CSS string-set value to this paragraph.

func (*Paragraph) SetTextAlignLast added in v0.6.0

func (p *Paragraph) SetTextAlignLast(a Align) *Paragraph

SetTextAlignLast sets the alignment for the last line of the paragraph. This is used to override the normal alignment (e.g. justify) for just the final line.

func (*Paragraph) SetWidows

func (p *Paragraph) SetWidows(n int) *Paragraph

SetWidows sets the minimum number of lines that must appear at the top of a page after a page break. If fewer lines would appear, additional lines are pulled from the previous page. Implemented by setting KeepWithNext on trailing lines. Default is 0 (disabled). Typical value: 2.

func (*Paragraph) SetWordBreak

func (p *Paragraph) SetWordBreak(wb string) *Paragraph

SetWordBreak sets the word-break behavior. "break-all" allows breaking within any word at character boundaries. "keep-all" prevents CJK characters from breaking individually (breaks only at spaces). Default is "normal" (CJK breaks at character boundaries, Latin breaks at spaces only).

func (*Paragraph) SplitAfterLine added in v0.8.0

func (p *Paragraph) SplitAfterLine(n int, maxWidth float64) (head, tail *Paragraph)

SplitAfterLine wraps the paragraph at maxWidth and splits it after the first n rendered lines. Returns:

  • head: a paragraph containing the first min(n, total) lines.
  • tail: a paragraph containing the remaining lines, or nil if no overflow (n >= total).

If n <= 0, head is nil and tail is the entire paragraph.

Both returned paragraphs are clones — the receiver is unchanged. Styling (fonts, colors, links, decorations, inline elements, shaped scripts) is preserved across the split via the same word-grouping rules used for page-break splits.

Spacing ownership: SpaceBefore stays with head only (the tail picks up where the head left off mid-paragraph; spaceBefore would double). SpaceAfter stays with tail only (symmetric reason). FirstLineIndent is dropped from both halves — re-laying the head at a different width re-applies indent to its first line, and the tail by definition is not the start of a paragraph.

Safe to call concurrently with other read methods on the receiver.

Re-laying the returned head/tail at a different maxWidth than the split is supported but may change line counts (the words are real — not pre-wrapped). Callers that want stable line counts should re-lay at the same width they passed to SplitAfterLine.

type PlacedBlock

type PlacedBlock struct {
	X      float64 // x position relative to the layout area's left edge
	Y      float64 // y offset from the top of the layout area (increases downward)
	Width  float64
	Height float64

	// Draw emits PDF content stream operators for this block.
	// Called during the rendering pass with the absolute PDF
	// coordinates (x = left edge, topY = top edge in PDF coords).
	// May be nil for structural containers that only hold children.
	Draw func(ctx DrawContext, x, topY float64)

	// PostDraw is called after all children are drawn. Used to restore
	// graphics state (e.g. after clipping or opacity changes).
	PostDraw func(ctx DrawContext, x, topY float64)

	// Tag is the PDF structure tag for accessibility (e.g. "P", "H1", "Figure").
	// Empty string means no tag (untagged content or structural wrapper).
	Tag string

	// AltText is alternative text for accessibility (used with Figure tags).
	AltText string

	// HeadingText is the plain text of a heading (for auto-bookmark generation).
	// Also used as the bookmark label for non-heading bookmark targets.
	HeadingText string

	// BookmarkLevel encodes the CSS bookmark-level override for this
	// block. 0 = use the level derived from Tag (H1-H6); -1 = explicit
	// "none" (skip from outline); 1-6 = explicit level. Non-heading
	// blocks set 1-6 to participate in the outline tree.
	BookmarkLevel int

	// BookmarkClosed corresponds to bookmark-state: closed. When true,
	// the outline subtree below this entry is collapsed by default in
	// PDF viewers (ISO 32000 §12.3.3 — emitted as a negative /Count).
	BookmarkClosed bool

	// AnchorName is the fragment identifier (an element's HTML id) that
	// resolves to this block's top position. The renderer surfaces it on
	// PageResult.Anchors and the document layer registers it as a PDF
	// named destination so <a href="#name"> links navigate here.
	AnchorName string

	// Children are nested content blocks (e.g. lines within a paragraph,
	// cells within a table row). The renderer draws them in order.
	Children []PlacedBlock

	// Links carries link annotations for this block. Each entry
	// describes a clickable region. A single line of text may contain
	// multiple links with different URIs.
	Links []LinkArea

	// StringSets holds CSS string-set values captured from this block.
	// Each entry maps a string name to its content value (e.g. "chapter" → "Chapter 3").
	// Used by running headers: string-set on an element captures text that
	// string() in margin boxes can reference.
	StringSets map[string]string
	// contains filtered or unexported fields
}

PlacedBlock is a positioned piece of content within a LayoutPlan. It carries a Draw closure that emits PDF operators when called.

PlacedBlocks form a tree: container elements (Div, Table) have children. Leaf elements (text lines, images) have no children.

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer lays out a sequence of elements into pages, handling page breaks automatically.

func NewRenderer

func NewRenderer(pageWidth, pageHeight float64, margins Margins) *Renderer

NewRenderer creates a renderer for the given page dimensions and margins. /ActualText emission for shaped Arabic words is enabled by default; call SetActualText(false) to opt out (e.g. to minimise content stream size).

func (*Renderer) Add

func (r *Renderer) Add(e Element)

Add appends an element to the layout queue.

func (*Renderer) AddAbsolute

func (r *Renderer) AddAbsolute(e Element, x, y, width float64)

AddAbsolute places an element at the given (x, y) coordinates on the last page produced by the normal flow. The element does not participate in normal vertical stacking — it is rendered on top of flow content. Coordinates are in PDF points from the bottom-left corner of the page. Width sets the layout width for the element (e.g. for word-wrapping); pass 0 to use the full page content width.

func (*Renderer) AddAbsoluteOnPage

func (r *Renderer) AddAbsoluteOnPage(e Element, x, y, width float64, pageIndex int)

AddAbsoluteOnPage places an element at (x, y) on a specific page (0-indexed). If the page index exceeds the number of pages produced by normal flow, the element is silently ignored.

func (*Renderer) AddAbsoluteRight

func (r *Renderer) AddAbsoluteRight(e Element, rightOffset, y, width float64)

AddAbsoluteRight places an element whose right edge is offset from the right page edge. The final X is computed after layout: pageWidth - rightOffset - elementWidth.

func (*Renderer) AddAbsoluteWithOpts

func (r *Renderer) AddAbsoluteWithOpts(e Element, x, y, width float64, opts AbsoluteOpts)

AddAbsoluteWithOpts places an element with full positioning control.

func (*Renderer) Render

func (r *Renderer) Render() []PageResult

Render lays out elements into pages. Each Element provides a PlanLayout method for height-aware layout with content splitting across pages.

func (*Renderer) RenderContext added in v0.9.0

func (r *Renderer) RenderContext(ctx context.Context) ([]PageResult, error)

RenderContext is the context-aware variant of Render. It checks ctx at page and element boundaries during layout and returns ctx.Err() (context.Canceled or context.DeadlineExceeded) if the context is done, with a nil page slice in that case. With a background context it behaves exactly like Render.

func (*Renderer) SetActualText added in v0.7.0

func (r *Renderer) SetActualText(enabled bool)

SetActualText controls whether the renderer emits ISO 32000-2 §14.9.4 /Span /ActualText marked-content sequences around words whose text was substituted by the Arabic shaper. When enabled (the default), copy/paste and accessibility consumers see the original Unicode codepoints rather than the Presentation Forms-B substitutions. Disabling shaves a few dozen bytes per shaped Arabic word and is appropriate for size-sensitive documents that do not require text round-tripping.

func (*Renderer) SetFirstMarginBoxes

func (r *Renderer) SetFirstMarginBoxes(boxes map[string]MarginBox)

SetFirstMarginBoxes sets margin boxes for the first page only.

func (*Renderer) SetFirstMargins

func (r *Renderer) SetFirstMargins(m Margins)

SetFirstMargins sets margins for the first page only (@page :first).

func (*Renderer) SetLeftMarginBoxes added in v0.9.1

func (r *Renderer) SetLeftMarginBoxes(boxes map[string]MarginBox)

SetLeftMarginBoxes sets margin boxes for left (even-numbered) pages (@page :left).

func (*Renderer) SetLeftMargins

func (r *Renderer) SetLeftMargins(m Margins)

SetLeftMargins sets margins for left (even-numbered) pages (@page :left).

func (*Renderer) SetMarginBoxes

func (r *Renderer) SetMarginBoxes(boxes map[string]MarginBox)

SetMarginBoxes sets default margin box content.

func (*Renderer) SetRightMarginBoxes added in v0.9.1

func (r *Renderer) SetRightMarginBoxes(boxes map[string]MarginBox)

SetRightMarginBoxes sets margin boxes for right (odd-numbered) pages (@page :right).

func (*Renderer) SetRightMargins

func (r *Renderer) SetRightMargins(m Margins)

SetRightMargins sets margins for right (odd-numbered) pages (@page :right).

func (*Renderer) SetTagged

func (r *Renderer) SetTagged(enabled bool)

SetTagged enables tagged PDF output. When true, the renderer wraps content in BDC/EMC marked content sequences and collects StructTagInfo for the document layer to build the structure tree.

func (*Renderer) StructTags

func (r *Renderer) StructTags() []StructTagInfo

StructTags returns the structure tags collected during rendering.

type ResolvableLength added in v0.8.0

type ResolvableLength interface {
	// Resolve returns the length in PDF points. Percent leaves evaluate
	// against container; em / rem leaves against fontSize. Plain length
	// leaves (px, pt, mm, in, cm) ignore both arguments.
	Resolve(container, fontSize float64) float64
}

ResolvableLength is a length that resolves lazily against a container dimension at draw time. Defined in layout (rather than imported from html) so the layout package stays free of html-parsing concerns; the html package's cssLength satisfies this interface. Used by BackgroundImage.Position so that plain lengths and mixed-unit calc on background-position can be resolved against the background box, which is only known at draw time. See issue #266.

type Row

type Row struct {
	// contains filtered or unexported fields
}

Row represents a row in a table.

func (*Row) AddCell

func (r *Row) AddCell(text string, f *font.Standard, fontSize float64) *Cell

AddCell adds a cell with text using a standard font.

func (*Row) AddCellElement

func (r *Row) AddCellElement(elem Element) *Cell

AddCellElement adds a cell containing any layout Element (paragraph, table, list, image, etc.) instead of plain text.

func (*Row) AddCellEmbedded

func (r *Row) AddCellEmbedded(text string, ef *font.EmbeddedFont, fontSize float64) *Cell

AddCellEmbedded adds a cell with text using an embedded font.

func (*Row) Cells added in v0.9.1

func (r *Row) Cells() []*Cell

Cells returns the row's cells in order. Provided for testing.

type SVGElement

type SVGElement struct {
	// contains filtered or unexported fields
}

SVGElement is a layout element that renders an SVG graphic in the document flow.

func NewSVGElement

func NewSVGElement(s *svg.SVG) *SVGElement

NewSVGElement creates a layout element from a parsed SVG. By default the element uses the SVG's intrinsic dimensions and left alignment.

func (*SVGElement) MaxWidth

func (se *SVGElement) MaxWidth() float64

MaxWidth implements Measurable. Returns the explicit width or SVG intrinsic width.

func (*SVGElement) MinWidth

func (se *SVGElement) MinWidth() float64

MinWidth implements Measurable. Returns the explicit width or SVG intrinsic width.

func (*SVGElement) PlanLayout

func (se *SVGElement) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. An SVG never splits — FULL or NOTHING.

func (*SVGElement) SetAlign

func (se *SVGElement) SetAlign(a Align) *SVGElement

SetAlign sets horizontal alignment.

func (*SVGElement) SetAltText added in v0.5.2

func (se *SVGElement) SetAltText(text string) *SVGElement

SetAltText sets alternative text for accessibility (PDF/UA).

func (*SVGElement) SetSize

func (se *SVGElement) SetSize(width, height float64) *SVGElement

SetSize sets explicit display dimensions. If either is 0 the value is computed from the SVG aspect ratio.

type Script added in v0.7.0

type Script uint8

Script identifies a Unicode script per UAX #24. The set of values is intentionally limited to the scripts the layout engine can currently distinguish for shaping decisions. All other codepoints (including the real UAX #24 Common and Inherited pseudo-scripts, plus any unrecognised script) map to ScriptCommon and are resolved against their neighbours.

const (
	// ScriptCommon covers UAX #24 "Common" and "Inherited" codepoints, plus
	// anything outside the recognised set. Runs of Common characters are
	// promoted to a neighbouring real script during segmentation.
	ScriptCommon Script = iota
	ScriptLatin
	ScriptArabic
	ScriptHebrew
	ScriptDevanagari
	ScriptBengali
	ScriptTamil
	ScriptThai
	ScriptHan
	ScriptHiragana
	ScriptKatakana
	ScriptHangul
	ScriptCyrillic
	ScriptGreek
	ScriptGujarati
	ScriptGurmukhi
	ScriptKannada
	ScriptMalayalam
	ScriptOriya
	ScriptTelugu
)

func ScriptOf added in v0.7.0

func ScriptOf(r rune) Script

ScriptOf returns the Script that r belongs to. ASCII letters take a fast path; everything else falls through an ordered list of unicode.RangeTable checks arranged roughly by real-world frequency so the common cases exit early. Characters outside the recognised scripts (digits, punctuation, symbols, combining marks, scripts we do not yet handle) return ScriptCommon; callers are expected to resolve these against neighbours.

type ScriptRun added in v0.7.0

type ScriptRun struct {
	Start  int
	End    int
	Script Script
}

ScriptRun describes a contiguous byte range of a string whose characters all resolve to the same Script per UAX #24 segmentation. Start and End are byte offsets into the original string; End is exclusive.

func SegmentByScript added in v0.7.0

func SegmentByScript(s string) []ScriptRun

SegmentByScript partitions s into runs where each rune resolves to the same Script. Common and Inherited runes inherit from their left neighbour; leading Common runs fall back to the nearest real script on the right, and a whole-Common input emits a single ScriptCommon run.

This is a linear pass: one walk to collect raw rune segments, a two-sweep resolution pass that promotes Commons against neighbours, then a coalescing emit. It implements the "inherit-from-neighbour" simplification of UAX #24; full Script_Extensions support can land in a later change.

type StructTagInfo

type StructTagInfo struct {
	Tag         string // structure type (e.g. "P", "H1", "Table")
	MCID        int    // marked content ID on this page
	PageIndex   int    // which page this tag is on
	AltText     string // alternative text (for Figure tags)
	ParentIndex int    // index of parent tag in the StructTags slice (-1 = top-level)
}

StructTagInfo records a structure tag emitted during rendering. The Document layer uses these to build the PDF structure tree.

type TabAlign

type TabAlign int

TabAlign specifies how text aligns relative to a tab stop position.

const (
	TabAlignLeft   TabAlign = iota // text starts at the tab position (default)
	TabAlignRight                  // text ends at the tab position
	TabAlignCenter                 // text is centered on the tab position
)

type TabStop

type TabStop struct {
	Position float64  // x position in points from the left edge of the content area
	Align    TabAlign // how text after the tab aligns to this position
	Leader   rune     // fill character between previous content and the tab (0 = none, '.' for dot leaders)
}

TabStop defines a position on a line where a tab character jumps to.

type TabbedLine

type TabbedLine struct {
	// contains filtered or unexported fields
}

TabbedLine is a layout element that renders a single line of text with tab stops. Unlike a Paragraph (which word-wraps), a TabbedLine always produces exactly one line with content positioned at tab stops.

This is used for table of contents entries, invoice line items, form fields, and anywhere you need aligned columns without a full Table.

Usage:

line := layout.NewTabbedLine(font.Helvetica, 12,
    layout.TabStop{Position: 400, Align: layout.TabAlignRight, Leader: '.'},
).SetSegments("Chapter 1", "15")

func NewTabbedLine

func NewTabbedLine(f *font.Standard, fontSize float64, stops ...TabStop) *TabbedLine

NewTabbedLine creates a tabbed line with the given font and tab stops.

func NewTabbedLineEmbedded

func NewTabbedLineEmbedded(ef *font.EmbeddedFont, fontSize float64, stops ...TabStop) *TabbedLine

NewTabbedLineEmbedded creates a tabbed line with an embedded font.

func (*TabbedLine) Layout

func (tl *TabbedLine) Layout(maxWidth float64) []Line

Layout returns a single line with tab-positioned words.

func (*TabbedLine) MaxWidth

func (tl *TabbedLine) MaxWidth() float64

MaxWidth implements Measurable. Same as MinWidth for tabbed lines.

func (*TabbedLine) MinWidth

func (tl *TabbedLine) MinWidth() float64

MinWidth implements Measurable. Returns the rightmost tab stop position (the narrowest width that shows all tab-positioned content).

func (*TabbedLine) PlanLayout

func (tl *TabbedLine) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. A tabbed line never splits — FULL or NOTHING.

func (*TabbedLine) SetColor

func (tl *TabbedLine) SetColor(c Color) *TabbedLine

SetColor sets the text color.

func (*TabbedLine) SetLeading

func (tl *TabbedLine) SetLeading(l float64) *TabbedLine

SetLeading sets the line height multiplier (default 1.2).

func (*TabbedLine) SetSegments

func (tl *TabbedLine) SetSegments(segments ...string) *TabbedLine

SetSegments sets the text segments. The first segment is placed at x=0, subsequent segments are placed at the corresponding tab stop.

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table is a layout element that renders a grid of cells with borders. Builder API backed by a flat grid internally.

Example (AutoColumns)
package main

import (
	"fmt"

	"github.com/carlos7ags/folio/font"
	"github.com/carlos7ags/folio/layout"
)

func main() {
	tbl := layout.NewTable().SetAutoColumnWidths()

	h := tbl.AddHeaderRow()
	h.AddCell("Product", font.HelveticaBold, 10)
	h.AddCell("Description", font.HelveticaBold, 10)
	h.AddCell("Price", font.HelveticaBold, 10)

	r := tbl.AddRow()
	r.AddCell("Widget", font.Helvetica, 10)
	r.AddCell("A wonderful widget that does amazing things", font.Helvetica, 10)
	r.AddCell("$9.99", font.Helvetica, 10)

	plan := tbl.PlanLayout(layout.LayoutArea{Width: 468, Height: 500})
	fmt.Println("Table fits:", plan.Status == layout.LayoutFull)

}
Output:
Table fits: true

func NewTable

func NewTable() *Table

NewTable creates a new empty table.

func (*Table) AddFooterRow

func (t *Table) AddFooterRow() *Row

AddFooterRow adds a row that will be repeated at the bottom of each page when the table breaks across pages.

func (*Table) AddHeaderRow

func (t *Table) AddHeaderRow() *Row

AddHeaderRow adds a row that will be repeated on each new page when the table breaks across pages.

func (*Table) AddRow

func (t *Table) AddRow() *Row

AddRow adds a new row to the table and returns it for adding cells.

func (*Table) BorderCollapse

func (t *Table) BorderCollapse() bool

BorderCollapse reports whether border-collapse is enabled.

func (*Table) Layout

func (t *Table) Layout(maxWidth float64) []Line

Layout implements the Element interface.

func (*Table) PlanLayout

func (t *Table) PlanLayout(area LayoutArea) LayoutPlan

PlanLayout implements Element. Tables split between rows — never inside a rowspan group — repeating header rows on each new page.

func (*Table) Rows added in v0.9.1

func (t *Table) Rows() []*Row

Rows returns the table's rows in order (header, body, and footer rows are all stored in this single slice). Provided for testing.

func (*Table) SetAutoColumnWidths

func (t *Table) SetAutoColumnWidths() *Table

SetAutoColumnWidths enables automatic column width calculation based on cell content. Columns are sized proportionally to their content's natural width, constrained to fit within the available space. Each column gets at least its MinWidth (longest word) and at most its MaxWidth (full content width without wrapping).

func (*Table) SetBorderCollapse

func (t *Table) SetBorderCollapse(enabled bool) *Table

SetBorderCollapse enables CSS-style border-collapse. When true, adjacent cell borders are merged so you don't get double borders. This removes the right border of each cell except the last column, and the bottom border of each cell except the last row.

func (*Table) SetCellSpacing

func (t *Table) SetCellSpacing(h, v float64) *Table

SetCellSpacing sets horizontal and vertical spacing between cells, corresponding to the CSS border-spacing property. Spacing is added between adjacent cells and at the table edges. Ignored when border-collapse is enabled.

func (*Table) SetColumnUnitWidths

func (t *Table) SetColumnUnitWidths(widths []UnitValue) *Table

SetColumnUnitWidths sets column widths using UnitValues, allowing a mix of point and percentage widths.

Example:

table.SetColumnUnitWidths([]UnitValue{Pct(30), Pct(70)})
table.SetColumnUnitWidths([]UnitValue{Pt(100), Pct(50), Pt(100)})

func (*Table) SetColumnWidths

func (t *Table) SetColumnWidths(widths []float64) *Table

SetColumnWidths sets explicit column widths in points. If not set, columns are distributed equally within the available width.

func (*Table) SetDirection added in v0.7.0

func (t *Table) SetDirection(d Direction) *Table

SetDirection sets the text direction for the table. When RTL, columns are rendered right-to-left: column 0 appears at the right edge of the table and the last column at the left edge. Cell content paragraphs also inherit the direction for bidi text reordering.

func (*Table) SetMinWidth

func (t *Table) SetMinWidth(pts float64) *Table

SetMinWidth sets the minimum total table width in points. When auto-sizing, if the content is narrower than this, columns are expanded proportionally to fill the minimum width.

func (*Table) SetMinWidthUnit

func (t *Table) SetMinWidthUnit(u UnitValue) *Table

SetMinWidthUnit sets the minimum table width as a UnitValue, resolved lazily at layout time. Use Pct(100) for width:100%.

type TextDecoration

type TextDecoration int

TextDecoration is a bitset of CSS text-decoration-line values. Multiple decorations can apply to the same run simultaneously (`text-decoration: underline overline`).

const (
	DecorationNone          TextDecoration = 0
	DecorationUnderline     TextDecoration = 1 << 0
	DecorationStrikethrough TextDecoration = 1 << 1
	DecorationOverline      TextDecoration = 1 << 2
)

type TextRun

type TextRun struct {
	Text            string
	Font            *font.Standard
	Embedded        *font.EmbeddedFont
	FontSize        float64
	Color           Color
	Decoration      TextDecoration
	DecorationColor *Color  // if non-nil, decoration uses this color instead of text Color
	DecorationStyle string  // "solid" (default), "dashed", "dotted", "double", "wavy"
	LetterSpacing   float64 // extra space between characters (points, from CSS letter-spacing)
	WordSpacing     float64 // extra space between words (points, from CSS word-spacing)
	BaselineShift   float64 // vertical offset in points (positive = up for super, negative = down for sub)
	LinkURI         string  // if non-empty, this run is part of a hyperlink
	// LinkDest is a named destination inside this document (the fragment
	// of an <a href="#id">, without the '#'). It is mutually exclusive
	// with LinkURI: a bare fragment is not a URI, and emitting it as a
	// /URI action produces a link that resolves to nothing in a viewer.
	LinkDest        string
	TextShadow      *TextShadow // if non-nil, draws a shadow behind the text
	BackgroundColor *Color      // if non-nil, a highlight rectangle is drawn behind the text
	// NoWrap marks this run as coming from a CSS white-space:nowrap context
	// (which is an inherited property, so it can be set on an inline element
	// rather than the block). The converter uses it to decide whether a
	// whole paragraph should be laid out nowrap; see Paragraph.SetNoWrap.
	NoWrap bool
	// InlineElement holds a layout element (e.g. ImageElement, SVGElement,
	// Div) that should flow inline within the paragraph. When set, text
	// fields are ignored and the element is measured and rendered as an
	// inline-block word during paragraph layout.
	InlineElement Element

	// IsLineBreak marks this run as a forced line break (from <br>).
	// When set, Text, Font, and other text fields are ignored. The run
	// is consumed by splitRunsAtBr to split a paragraph at the break
	// point. This field replaces the previous magic-string convention
	// of TextRun{Text: "\n"} with nil Font.
	IsLineBreak bool
}

TextRun is a styled span of text within a paragraph. A paragraph is composed of one or more runs, each with its own font, size, and color. Runs flow together: the text of consecutive runs is concatenated and word-wrapped as a unit.

When InlineElement is set, this run represents an inline element (image, SVG, or any display:inline-block element) rather than text. The element flows within the paragraph like a word, participating in word-wrapping and line-height calculations. Text, Font, and other text-specific fields are ignored for inline element runs.

func NewRun added in v0.6.0

func NewRun(text string, f *font.Standard, fontSize float64) TextRun

NewRun creates a TextRun with a standard font.

func NewRunEmbedded added in v0.6.0

func NewRunEmbedded(text string, ef *font.EmbeddedFont, fontSize float64) TextRun

NewRunEmbedded creates a TextRun with an embedded font.

func RunInline added in v0.6.0

func RunInline(el Element) TextRun

RunInline creates a TextRun that represents an inline element. The element will be measured and rendered as an inline-block word during paragraph layout, flowing with surrounding text.

func (TextRun) WithBackgroundColor added in v0.6.0

func (r TextRun) WithBackgroundColor(c Color) TextRun

WithBackgroundColor returns a copy of the run with a highlight background. A filled rectangle of the given color is drawn behind the text.

func (TextRun) WithColor

func (r TextRun) WithColor(c Color) TextRun

WithColor returns a copy of the run with the given color.

func (TextRun) WithDecoration added in v0.4.2

func (r TextRun) WithDecoration(d TextDecoration) TextRun

WithDecoration returns a copy of the run with the given decoration flags.

func (TextRun) WithLinkDest added in v0.11.0

func (r TextRun) WithLinkDest(destName string) TextRun

WithLinkDest returns a copy of the run marked as a link to a named destination within this document. Words from this run produce a clickable annotation that navigates to destName.

func (TextRun) WithLinkURI added in v0.4.2

func (r TextRun) WithLinkURI(uri string) TextRun

WithLinkURI returns a copy of the run marked as a hyperlink. Words from this run will produce a clickable annotation in the PDF.

func (TextRun) WithStrikethrough

func (r TextRun) WithStrikethrough() TextRun

WithStrikethrough returns a copy of the run with strikethrough decoration.

func (TextRun) WithUnderline

func (r TextRun) WithUnderline() TextRun

WithUnderline returns a copy of the run with underline decoration.

type TextShadow added in v0.6.0

type TextShadow struct {
	OffsetX float64 // horizontal offset (positive = right)
	OffsetY float64 // vertical offset (positive = down in CSS, converted to PDF up)
	Blur    float64 // blur radius (approximated via opacity)
	Color   Color   // shadow color
}

TextShadow represents a CSS text-shadow effect.

type TransformOp

type TransformOp struct {
	Type   string     // "rotate", "scale", "translate", "skewX", "skewY"
	Values [2]float64 // up to 2 parameters (e.g. scaleX, scaleY)
}

TransformOp represents a single CSS transform function.

type UnitType

type UnitType int

UnitType specifies how a UnitValue is interpreted.

const (
	UnitPoint   UnitType = iota // absolute value in PDF points
	UnitPercent                 // percentage of available width
	UnitCalc                    // expression resolved against available width at layout time
)

type UnitValue

type UnitValue struct {
	Value float64
	Unit  UnitType
	// Calc resolves the value against the available width. Only used
	// when Unit == UnitCalc; nil otherwise. Lets calc() expressions
	// containing percentages be resolved against the actual layout area
	// rather than an eagerly-captured container width.
	Calc func(available float64) float64
}

UnitValue represents a measurement that can be either an absolute point value, a percentage of available space, or a calc()-style expression resolved lazily at layout time.

func CalcUnit added in v0.8.0

func CalcUnit(fn func(available float64) float64) UnitValue

CalcUnit creates a UnitValue whose resolution is deferred to layout time. Pass a closure that, given the available width, returns points. Used for CSS calc()/min()/max()/clamp() expressions that contain percentage parts.

func Pct

func Pct(v float64) UnitValue

Pct creates a UnitValue as a percentage (0–100) of available space.

func Pt

func Pt(v float64) UnitValue

Pt creates a UnitValue in PDF points.

func (UnitValue) Resolve

func (u UnitValue) Resolve(available float64) float64

Resolve converts a UnitValue to points given the available width.

type VAlign

type VAlign int

VAlign specifies vertical alignment within a container (e.g. table cell).

const (
	VAlignTop VAlign = iota // default
	VAlignMiddle
	VAlignBottom
)

type Word

type Word struct {
	Text  string
	Width float64
	// Font info needed by the renderer to emit Tf/Tj operators.
	Font            *font.Standard
	Embedded        *font.EmbeddedFont
	FontSize        float64
	Color           Color
	Decoration      TextDecoration
	DecorationColor *Color // if non-nil, decoration uses this color
	DecorationStyle string // "solid", "dashed", "dotted", "double", "wavy"
	// SpaceAfter is the width of a space character in this word's font/size.
	// Used to compute the gap to the next word when fonts differ.
	SpaceAfter    float64
	LetterSpacing float64 // extra inter-character space (Tc operator)
	WordSpacing   float64 // extra inter-word space added to SpaceAfter
	BaselineShift float64 // vertical offset (positive = up, negative = down)

	TextShadow *TextShadow // if non-nil, draws a shadow behind the text

	// LineBreak forces a new line before this word during word-wrapping.
	// Used to honor explicit \n characters in paragraph text.
	LineBreak bool

	// OriginalText holds the pre-shaping Unicode text for this word when a
	// shaper (currently ShapeArabic) substituted glyph-form codepoints. The
	// renderer wraps such words in an ISO 32000-2 §14.9.4 /Span /ActualText
	// marked-content sequence so that copy/paste and accessibility tools
	// recover the original codepoints rather than the shaped Presentation
	// Forms-B substitutions. Empty when no shaping happened. Words split by
	// breakLongWords lose this field on subsequent chunks because there is
	// no per-chunk slice of the original text.
	OriginalText string

	// LinkURI is the hyperlink target for this word. If non-empty, the
	// renderer creates a link annotation covering this word's area.
	LinkURI string

	// LinkDest is the named destination inside this document that this
	// word links to. Mutually exclusive with LinkURI; carries the
	// fragment of an <a href="#id"> so the renderer can emit a /Dest
	// instead of a /URI action that would navigate nowhere.
	LinkDest string

	// BackgroundColor, if non-nil, draws a filled highlight rectangle
	// behind this word before rendering the text.
	BackgroundColor *Color

	// InlineBlock fields: when set, this Word represents an inline-block
	// element (e.g., a Div) that flows within a paragraph like a "big word".
	InlineBlock  Element // the layout element to render instead of text
	InlineWidth  float64 // pre-measured width of the inline block
	InlineHeight float64 // pre-measured height of the inline block

	// GIDs carries a shaper-produced glyph ID stream for complex scripts
	// whose output cannot be represented as Unicode codepoints. The
	// Devanagari shaper (layout/indic.go) emits GIDs here after running
	// the OpenType Indic shaping pipeline; the draw path emits these
	// GIDs as an Identity-H hex string via Tj instead of walking Text.
	//
	// When GIDs is non-nil, Text still holds the post-reordering logical
	// text (used for copy/paste fallbacks), and OriginalText holds the
	// pre-shaping Unicode for ActualText marked-content recovery. Most
	// words leave this field nil; only Devanagari (and future Indic)
	// words set it, so the existing rune-based path is undisturbed.
	GIDs []uint16
	// contains filtered or unexported fields
}

Word is a measured chunk of text (no spaces).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL