Documentation
¶
Overview ¶
Package document provides the intermediate document model that bridges the high-level template API and the low-level PDF writer. It is Layer 2 of the gpdf architecture.
Document Tree ¶
A document is represented as a tree of nodes implementing the DocumentNode interface. Each node carries a NodeType, optional children, and a Style:
- Document — root node containing pages and metadata
- Page — a single page with size, margins, and content
- Box — a generic container with CSS-like box model (horizontal/vertical)
- Text — a leaf node containing styled text content
- Image — a leaf node containing an embedded image (JPEG/PNG)
- Table — tabular data with header, body, and footer sections
- List — ordered or unordered list items
- RichText — inline formatting context with multiple styled fragments
Styling ¶
The Style type holds the complete set of visual properties following CSS box model conventions: font family/size/weight, color, text alignment, margin, padding, and border. Styles are inherited from parent to child via InheritStyle.
Units ¶
Dimensions are expressed as Value with an associated Unit. The library supports pt, mm, cm, in, em, and percentage units. Constructor functions provide a convenient way to create values:
v := document.Mm(15) // 15 millimeters v := document.Pt(12) // 12 points v := document.Pct(50) // 50 percent
Standard page sizes are provided as Size values: A4, A3, Letter, Legal.
Page Breaks ¶
BreakPolicy controls page-break behavior (before, after, or inside a node). The layout engine in the layout sub-package uses these hints when paginating content.
Index ¶
- Constants
- Variables
- type BorderEdges
- type BorderSide
- type BorderStyle
- type Box
- type BoxStyle
- type BreakPolicy
- type BreakValue
- type CellNode
- type Direction
- type Document
- type DocumentMetadata
- type DocumentNode
- type Edges
- type FontStyle
- type FontWeight
- type Image
- type ImageFitMode
- type ImageFormat
- type ImageSource
- type List
- type ListItem
- type ListItemNode
- type ListType
- type NodeType
- type Page
- type Path
- type PathOp
- type PathSegment
- type Point
- type Position
- type PositionMode
- type PositionOrigin
- type Rectangle
- type ResolvedEdges
- type RichText
- type RichTextFragment
- type Size
- type Style
- type Table
- type TableCell
- type TableColumn
- type TableRow
- type TableStyle
- type Text
- type TextAlign
- type TextDecoration
- type Unit
- type Value
- type VerticalAlign
Constants ¶
const ( // PageNumberPlaceholder is a sentinel string embedded in text nodes to // mark where the current page number should appear. It is replaced after // pagination with the actual page number. PageNumberPlaceholder = "\x00GPDF_PAGE\x00" // TotalPagesPlaceholder is a sentinel string replaced after pagination // with the total number of pages in the document. TotalPagesPlaceholder = "\x00GPDF_TOTAL\x00" )
Variables ¶
var ( // A4 is the ISO A4 page size (210mm x 297mm). A4 = Size{Width: 595.28, Height: 841.89} // A3 is the ISO A3 page size (297mm x 420mm). A3 = Size{Width: 841.89, Height: 1190.55} // Letter is the US Letter page size (8.5" x 11"). Letter = Size{Width: 612, Height: 792} // Legal is the US Legal page size (8.5" x 14"). Legal = Size{Width: 612, Height: 1008} )
Predefined page sizes expressed in PDF points (1/72 inch).
var Auto = Value{Unit: UnitAuto}
Auto is a sentinel Value indicating that the dimension should be calculated automatically by the layout engine.
Functions ¶
This section is empty.
Types ¶
type BorderEdges ¶
type BorderEdges struct {
Top, Right, Bottom, Left BorderSide
}
BorderEdges defines border styling for each side of a box.
func UniformBorder ¶
func UniformBorder(width Value, style BorderStyle, color pdf.Color) BorderEdges
UniformBorder creates a BorderEdges with the same width, style, and color applied to all four sides.
type BorderSide ¶
type BorderSide struct {
Width Value
Style BorderStyle
Color pdf.Color
}
BorderSide defines the visual properties of a single border edge.
type BorderStyle ¶
type BorderStyle int
BorderStyle specifies the line style for a border edge.
const ( // BorderNone indicates no border is drawn. BorderNone BorderStyle = iota // BorderSolid draws a continuous solid line. BorderSolid // BorderDashed draws a dashed line. BorderDashed // BorderDotted draws a dotted line. BorderDotted )
type Box ¶
type Box struct {
// Content holds the child nodes rendered inside this box.
Content []DocumentNode
// BoxStyle controls the dimensions, spacing, and decoration of the box.
BoxStyle BoxStyle
// BreakPolicy controls page break behavior around and within this box.
BreakPolicy BreakPolicy
}
Box is the fundamental layout container, implementing the CSS-like box model with margins, padding, borders, and size constraints. Boxes stack their children vertically by default.
func (*Box) Children ¶
func (b *Box) Children() []DocumentNode
Children returns the box's content nodes.
type BoxStyle ¶
type BoxStyle struct {
Width Value
Height Value
MinWidth Value
MaxWidth Value
MinHeight Value
MaxHeight Value
Margin Edges
Padding Edges
Border BorderEdges
Background *pdf.Color
Direction Direction
Position Position
}
BoxStyle defines the dimensional and decorative properties of a Box.
type BreakPolicy ¶
type BreakPolicy struct {
BreakBefore BreakValue
BreakAfter BreakValue
BreakInside BreakValue
}
BreakPolicy controls how page breaks interact with a node. It allows authors to force or suppress breaks before, after, or within a node.
type BreakValue ¶
type BreakValue int
BreakValue specifies the behavior of a page break control point.
const ( // BreakAuto lets the layout engine decide whether to break. BreakAuto BreakValue = iota // BreakAvoid requests the engine to avoid a break at this point. BreakAvoid // BreakAlways forces a break at this point. BreakAlways // BreakPage forces a page break at this point. BreakPage )
type CellNode ¶
type CellNode struct {
Cell *TableCell
}
CellNode wraps a TableCell to implement the DocumentNode interface, allowing cells to participate in generic tree traversal.
func (*CellNode) Children ¶
func (cn *CellNode) Children() []DocumentNode
Children returns the content nodes inside this cell.
type Document ¶
type Document struct {
// Pages holds the pages in document order.
Pages []*Page
// Metadata holds document-level information such as title and author.
Metadata DocumentMetadata
// DefaultStyle provides default values for style properties that are
// not explicitly set on descendant nodes.
DefaultStyle Style
}
Document is the root node of the document tree. It holds an ordered list of pages, document-level metadata, and a default style inherited by all descendant nodes that do not override specific properties.
func (*Document) Children ¶
func (d *Document) Children() []DocumentNode
Children returns each page as a DocumentNode.
type DocumentMetadata ¶
type DocumentMetadata struct {
Title string
Author string
Subject string
Creator string
Producer string
}
DocumentMetadata carries descriptive information about the document, corresponding to the PDF Info dictionary fields.
type DocumentNode ¶
type DocumentNode interface {
// NodeType returns the kind of node (page, text, box, etc.).
NodeType() NodeType
// Children returns the direct child nodes, or nil for leaf nodes.
Children() []DocumentNode
// Style returns the visual style applied to this node.
Style() Style
}
DocumentNode is the interface implemented by all nodes in the document tree. Each node carries a type tag, an optional list of children, and a style that governs its visual presentation.
type Edges ¶
type Edges struct {
Top, Right, Bottom, Left Value
}
Edges represents four-sided dimension values, following the CSS box model convention of Top, Right, Bottom, Left.
func UniformEdges ¶
UniformEdges creates Edges with the same value applied to all four sides.
func (Edges) Resolve ¶
func (e Edges) Resolve(parentWidth, parentHeight, fontSize float64) ResolvedEdges
Resolve converts all edge values to points. Horizontal edges (Left, Right) are resolved against parentWidth; vertical edges (Top, Bottom) are resolved against parentHeight.
type FontStyle ¶
type FontStyle int
FontStyle selects between normal (upright) and italic typeface variants.
type FontWeight ¶
type FontWeight int
FontWeight represents the weight (boldness) of a font, using the standard CSS numeric scale where 400 is normal and 700 is bold.
const ( // WeightNormal is the standard font weight (CSS 400). WeightNormal FontWeight = 400 // WeightBold is the bold font weight (CSS 700). WeightBold FontWeight = 700 )
type Image ¶
type Image struct {
// Source holds the image data and metadata.
Source ImageSource
// ImgStyle controls spacing and decorative properties.
ImgStyle Style
// FitMode determines how the image is scaled within its bounds.
FitMode ImageFitMode
// DisplayWidth is the explicit display width set by template options.
DisplayWidth Value
// DisplayHeight is the explicit display height set by template options.
DisplayHeight Value
}
Image is a leaf document node that renders an image within the document layout. The FitMode controls how the image is scaled relative to its layout bounds.
func (*Image) Children ¶
func (img *Image) Children() []DocumentNode
Children returns nil because an image is a leaf node.
type ImageFitMode ¶
type ImageFitMode int
ImageFitMode controls how an image is scaled within its layout bounds.
const ( // FitContain scales the image to fit entirely within the bounds // while preserving aspect ratio. The image may be smaller than the // bounds in one dimension. FitContain ImageFitMode = iota // FitCover scales the image to cover the bounds completely while // preserving aspect ratio. Parts of the image may be clipped. FitCover // FitStretch scales the image to exactly fill the bounds, potentially // distorting the aspect ratio. FitStretch // FitOriginal uses the image's intrinsic pixel dimensions converted // to points (at 72 DPI). FitOriginal )
type ImageFormat ¶
type ImageFormat int
ImageFormat identifies the encoding of an image's raw data.
const ( // ImageJPEG indicates JPEG encoding. ImageJPEG ImageFormat = iota // ImagePNG indicates PNG encoding. ImagePNG )
type ImageSource ¶
type ImageSource struct {
// Data holds the raw image bytes (e.g., JPEG or PNG encoded).
Data []byte
// Format identifies the image encoding.
Format ImageFormat
// Width is the intrinsic pixel width.
Width int
// Height is the intrinsic pixel height.
Height int
}
ImageSource carries the raw image data along with its format and intrinsic pixel dimensions.
type List ¶
type List struct {
// Items holds the list items.
Items []ListItem
// ListType selects bullet or numbered style.
ListType ListType
// ListStyle controls the list's visual properties.
ListStyle Style
// BreakPolicy controls page break behavior around and within this list.
BreakPolicy BreakPolicy
// MarkerIndent is the width reserved for the bullet or number marker
// in points. If zero a default of 20pt is used.
MarkerIndent float64
}
List is a document node representing an ordered or unordered list.
func (*List) Children ¶
func (l *List) Children() []DocumentNode
Children returns a DocumentNode slice wrapping each ListItem.
type ListItem ¶
type ListItem struct {
// Content holds the child nodes rendered inside this item.
Content []DocumentNode
// ItemStyle controls the item's visual properties.
ItemStyle Style
}
ListItem represents a single item in a list.
type ListItemNode ¶
type ListItemNode struct {
Item *ListItem
// contains filtered or unexported fields
}
ListItemNode wraps a ListItem to implement the DocumentNode interface.
func (*ListItemNode) Children ¶
func (n *ListItemNode) Children() []DocumentNode
Children returns the item's content nodes.
func (*ListItemNode) NodeType ¶
func (n *ListItemNode) NodeType() NodeType
NodeType returns NodeListItem.
func (*ListItemNode) Style ¶
func (n *ListItemNode) Style() Style
Style returns the item's style, falling back to the list style.
type ListType ¶
type ListType int
ListType distinguishes ordered (numbered) from unordered (bulleted) lists.
type NodeType ¶
type NodeType int
NodeType enumerates the kinds of document nodes.
const ( // NodeDocument is the root node representing the entire document. NodeDocument NodeType = iota // NodePage represents a single page. NodePage // NodeBox is a generic container with CSS-like box model. NodeBox // NodeText is a leaf node containing text content. NodeText // NodeImage is a leaf node containing an image. NodeImage // NodeTable is a container for tabular data. NodeTable // NodeTableRow represents a single row within a table. NodeTableRow // NodeTableCell represents a single cell within a table row. NodeTableCell // NodeList is a container for ordered or unordered list items. NodeList // NodeListItem represents a single item in a list. NodeListItem // NodeRichText is an inline formatting context that places multiple // styled text fragments on a single line. NodeRichText )
type Page ¶
type Page struct {
// Size specifies the page dimensions (e.g., A4, Letter).
Size Size
// Margins defines the space between the page edge and the content area.
Margins Edges
// Content holds the document nodes rendered on this page.
Content []DocumentNode
// PageStyle provides default style properties for content on this page.
PageStyle Style
}
Page represents a single page within a document. It defines the physical page size, margins, and content nodes laid out on that page.
func (*Page) Children ¶
func (p *Page) Children() []DocumentNode
Children returns the page's content nodes.
type Path ¶
type Path struct {
Segments []PathSegment
}
Path is an ordered sequence of path segments that together describe a shape suitable for filling, stroking, or both.
type PathOp ¶
type PathOp int
PathOp identifies the type of a path drawing operation.
const ( // PathMoveTo moves the current point without drawing. PathMoveTo PathOp = iota // PathLineTo draws a straight line from the current point. PathLineTo // PathCurveTo draws a cubic Bezier curve using two control points. PathCurveTo // PathClose closes the current subpath with a straight line back // to its starting point. PathClose )
type PathSegment ¶
type PathSegment struct {
Op PathOp
// Points contains the operand points. The number of points depends
// on the operation:
// MoveTo: 1 (destination)
// LineTo: 1 (endpoint)
// CurveTo: 3 (control1, control2, endpoint)
// Close: 0
Points []Point
}
PathSegment is a single drawing instruction within a path.
type Point ¶
type Point struct {
X, Y float64
}
Point represents a position in 2D space, expressed in PDF points.
type Position ¶ added in v0.9.0
type Position struct {
// Mode selects the positioning strategy.
Mode PositionMode
// X is the horizontal offset from the origin.
X Value
// Y is the vertical offset from the origin.
Y Value
// Origin selects the reference point for X/Y coordinates.
Origin PositionOrigin
}
Position defines the placement of a node when using absolute positioning.
type PositionMode ¶ added in v0.9.0
type PositionMode int
PositionMode specifies how a node is positioned within its container.
const ( // PositionStatic is the default flow-based positioning. PositionStatic PositionMode = iota // PositionAbsolute places the node at fixed coordinates, // removed from the normal document flow. PositionAbsolute )
type PositionOrigin ¶ added in v0.9.0
type PositionOrigin int
PositionOrigin specifies the reference point for absolute coordinates.
const ( // OriginContentArea measures from the top-left of the content area // (inside page margins). This is the default. OriginContentArea PositionOrigin = iota // OriginPage measures from the top-left of the physical page // (0, 0 = top-left corner, ignoring margins). OriginPage )
type Rectangle ¶
type Rectangle struct {
X, Y, Width, Height float64
}
Rectangle represents an axis-aligned rectangle defined by its origin (top-left corner in layout coordinates) and dimensions.
type ResolvedEdges ¶
type ResolvedEdges struct {
Top, Right, Bottom, Left float64
}
ResolvedEdges holds four-sided dimensions that have been resolved to PDF points.
func (ResolvedEdges) Horizontal ¶
func (re ResolvedEdges) Horizontal() float64
Horizontal returns the sum of the left and right edges.
func (ResolvedEdges) Vertical ¶
func (re ResolvedEdges) Vertical() float64
Vertical returns the sum of the top and bottom edges.
type RichText ¶
type RichText struct {
// Fragments is the ordered list of inline text spans.
Fragments []RichTextFragment
// BlockStyle holds paragraph-level style (alignment, line height, indent).
BlockStyle Style
// BreakPolicy controls page-break behavior for this node.
BreakPolicy BreakPolicy
}
RichText is a block-level node that arranges multiple styled text fragments inline, allowing mixed fonts, sizes, and colors within a single paragraph. The BlockStyle governs paragraph-level properties such as TextAlign, LineHeight, and TextIndent.
func (*RichText) Children ¶
func (rt *RichText) Children() []DocumentNode
Children returns nil because RichText is a leaf-like node whose inline fragments are handled internally by the layout engine.
type RichTextFragment ¶
type RichTextFragment struct {
// Content is the text string for this fragment.
Content string
// FragmentStyle controls font, color, and decoration for this fragment.
FragmentStyle Style
}
RichTextFragment holds a single span of text with its own style. Multiple fragments are combined within a RichText node to produce inline mixed-style text on a single logical line.
type Size ¶
type Size struct {
Width, Height float64
}
Size represents a 2D dimension (width and height) in PDF points.
type Style ¶
type Style struct {
// Font properties
FontFamily string
FontSize float64 // in points
FontWeight FontWeight // e.g., WeightNormal (400), WeightBold (700)
FontStyle FontStyle // Normal or Italic
// Color properties
Color pdf.Color // text (foreground) color
Background *pdf.Color // background fill color; nil means transparent
// Text properties
TextAlign TextAlign // horizontal text alignment
LineHeight float64 // line height multiplier (e.g., 1.5 for 150%)
WordSpacing float64 // extra space added to each word gap in points (used by justify)
LetterSpacing float64 // extra space between characters in points (PDF Tc operator)
TextIndent Value // first-line indentation
TextDecoration TextDecoration // bitmask: underline, strikethrough, overline
VerticalAlign VerticalAlign // vertical alignment in table cells
// Box model
Margin Edges
Padding Edges
Border BorderEdges
}
Style holds the complete set of visual properties that can be applied to a document node. It follows the CSS box model conventions: font, color, text alignment, margins, padding, and borders.
func DefaultStyle ¶
func DefaultStyle() Style
DefaultStyle returns a Style with sensible defaults: 12pt black text, left-aligned with a 1.2 line height.
func InheritStyle ¶
InheritStyle produces a merged style where inheritable CSS properties are copied from parent to child when the child's value is unset (zero value). Non-inheritable properties (TextAlign, FontStyle, LetterSpacing, WordSpacing, TextDecoration, VerticalAlign, Background, Margin, Padding, Border) are always taken from the child unchanged.
Limitation: properties whose zero value is a valid setting (FontStyle, TextAlign, LetterSpacing, WordSpacing) cannot be distinguished from "unset" and are therefore treated as non-inheritable here. Callers that need explicit reset of these properties should set them on the child style directly.
type Table ¶
type Table struct {
// Columns defines the width of each column.
Columns []TableColumn
// Header contains rows that repeat at the top of each page when the
// table spans multiple pages.
Header []TableRow
// Body contains the main content rows.
Body []TableRow
// the table spans multiple pages.
Footer []TableRow
// TableStyle controls the table's visual properties.
TableStyle TableStyle
}
Table is a document node that arranges content in a grid of rows and columns. It supports separate header, body, and footer sections, as well as column width definitions and cell spanning.
func (*Table) Children ¶
func (t *Table) Children() []DocumentNode
Children collects all cells across header, body, and footer rows into a flat list of DocumentNode values. This is primarily used for tree traversal; the table layout engine uses the structured row/cell data directly.
type TableCell ¶
type TableCell struct {
// Content holds the child nodes rendered inside this cell.
Content []DocumentNode
// ColSpan is the number of columns this cell spans (minimum 1).
ColSpan int
// RowSpan is the number of rows this cell spans (minimum 1).
RowSpan int
// CellStyle controls the cell's visual properties.
CellStyle Style
}
TableCell represents a single cell in a table. It can span multiple columns and rows.
type TableColumn ¶
type TableColumn struct {
// Width specifies the column width. Use Auto for automatic sizing.
Width Value
}
TableColumn defines properties for a single table column.
type TableRow ¶
type TableRow struct {
// Cells holds the cells in this row.
Cells []TableCell
}
TableRow represents a horizontal row of cells within a table section.
type TableStyle ¶
type TableStyle struct {
BoxStyle
// BorderCollapse when true merges adjacent cell borders into a single
// border, similar to CSS border-collapse: collapse.
BorderCollapse bool
}
TableStyle extends BoxStyle with table-specific visual properties.
type Text ¶
type Text struct {
// Content is the text string to render.
Content string
// TextStyle controls font, color, alignment, and spacing.
TextStyle Style
}
Text is a leaf document node that holds a string of text content and the style used to render it (font, size, color, alignment, etc.).
func (*Text) Children ¶
func (t *Text) Children() []DocumentNode
Children returns nil because text is a leaf node.
type TextDecoration ¶
type TextDecoration uint8
TextDecoration is a bitmask specifying text decoration lines.
const ( // DecorationNone indicates no text decoration. DecorationNone TextDecoration = 0 // DecorationUnderline draws a line below the text baseline. DecorationUnderline TextDecoration = 1 // DecorationStrikethrough draws a line through the middle of the text. DecorationStrikethrough TextDecoration = 2 // DecorationOverline draws a line above the text. DecorationOverline TextDecoration = 4 )
type Unit ¶
type Unit int
Unit identifies the measurement system for a Value.
const ( // UnitPt is the PDF point (1/72 inch), the native PDF coordinate unit. UnitPt Unit = iota // UnitMm is the millimeter. UnitMm // UnitIn is the inch. UnitIn // UnitCm is the centimeter. UnitCm // UnitEm is relative to the current font size. UnitEm // UnitPct is a percentage relative to the parent dimension. UnitPct // UnitAuto indicates that the value should be calculated automatically. UnitAuto )
type Value ¶
Value is a dimension expressed as a numeric amount with an associated unit. Use the convenience constructors (Pt, Mm, In, Cm, Em, Pct) to create values.
func (Value) IsAuto ¶
IsAuto reports whether the value uses the Auto unit, indicating the dimension should be determined by the layout engine.
func (Value) Resolve ¶
Resolve converts a Value to PDF points using the given parent size (for percentage calculations) and font size (for em calculations).
Conversion factors:
- Pt: amount (identity)
- Mm: amount * 2.83465
- In: amount * 72
- Cm: amount * 28.3465
- Em: amount * fontSize
- Pct: amount / 100 * parentSize
- Auto: 0
type VerticalAlign ¶
type VerticalAlign int
VerticalAlign specifies vertical alignment within a container (e.g., table cell).
const ( // VAlignTop aligns content to the top (default). VAlignTop VerticalAlign = iota // VAlignMiddle centers content vertically. VAlignMiddle // VAlignBottom aligns content to the bottom. VAlignBottom )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package layout provides layout engines that calculate the position and size of document nodes within the available space.
|
Package layout provides layout engines that calculate the position and size of document nodes within the available space. |
|
Package render provides interfaces and implementations for drawing laid-out document content to an output target such as a PDF file.
|
Package render provides interfaces and implementations for drawing laid-out document content to an output target such as a PDF file. |