core

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 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 core contains all core interfaces and basic implementations.

Package core contains all core interfaces and basic implementations.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCannotMergeBytes = errors.New("cannot merge bytes")
	ErrCannotWriteFile  = errors.New("cannot write file")
)

Errors reported when working with a generated document.

Functions

This section is empty.

Types

type AlphaProvider

type AlphaProvider interface {
	// WithAlpha runs fn with the global drawing/fill alpha set to a (clamped to
	// [0, 1]), then restores alpha to 1.0 via defer. Panics in fn still restore.
	WithAlpha(a float64, fn func())
}

AlphaProvider is a narrow optional capability interface for providers that support per-operation alpha (translucency) via gofpdf's SetAlpha. The provider MUST save+restore alpha around the fn call (typically via defer) so the global alpha state cannot leak into subsequent native rendering.

Consumers detect support via the safe type-assertion idiom:

if ap, ok := provider.(core.AlphaProvider); ok && alpha != nil && *alpha < 1 {
    ap.WithAlpha(*alpha, func() { ... })
} else {
    // direct render — alpha == nil or 1.0 path
}

type AutomaticPageTopDiscarder added in v0.2.2

type AutomaticPageTopDiscarder interface {
	DiscardAtAutomaticPageTop() bool
}

AutomaticPageTopDiscarder marks flow spacing that should disappear when an unforced page break places it at the top of the next page. Forced breaks keep the spacing after the break.

type CharSpacingProvider

type CharSpacingProvider interface {
	// WithCharSpacing runs fn with the per-run character spacing temporarily
	// set to mm, restoring 0 via defer (panic-safe). mm < 0 should be clamped
	// to 0 by the implementation.
	WithCharSpacing(mm float64, fn func())
}

CharSpacingProvider is a narrow optional capability interface for providers that support per-run character spacing (CSS letter-spacing). Implementations MUST always restore character spacing to 0 via defer so state cannot leak into subsequent rendering.

Note: the current phpdave11/gofpdf fork does not expose SetCharSpacing — only SetWordSpacing. The internal paper provider therefore implements this interface as a no-op (fn is invoked without any spacing adjustment). The interface and type assertion path are still in place so a future fork swap or upstream change can light up the feature without further wiring changes.

Consumers detect support via the safe type-assertion idiom:

if csp, ok := provider.(core.CharSpacingProvider); ok && run.LetterSpacing > 0 {
    csp.WithCharSpacing(run.LetterSpacing, func() { ... })
} else {
    // direct render path
}

type Checkbox

type Checkbox interface {
	Add(label string, cell *entity.Cell, prop *props.Checkbox)
}

Checkbox is the abstraction which deals of how to add checkboxes inside PDF.

type Code

type Code interface {
	GenQr(code string) (*entity.Image, error)
	GenDataMatrix(code string) (*entity.Image, error)
	GenBar(code string, cell *entity.Cell, prop *props.Barcode) (*entity.Image, error)
}

Code is the abstraction which deals of how to add QrCodes or Barcode in a PDF.

type CodeProvider

type CodeProvider interface {
	AddMatrixCode(code string, cell *entity.Cell, prop *props.Rect)
	AddQrCode(code string, cell *entity.Cell, rect *props.Rect)
	AddBarCode(code string, cell *entity.Cell, prop *props.Barcode)
	GetDimensionsByMatrixCode(code string) (*entity.Dimensions, error)
	GetDimensionsByQrCode(code string) (*entity.Dimensions, error)
}

CodeProvider is the provider surface used by barcode and matrix-code components.

type Col

type Col interface {
	Node
	Add(components ...Component) Col
	GetSize() int
	GetHeight(provider Provider, cell *entity.Cell) float64
	WithStyle(style *props.Cell) Col
	Render(provider Provider, cell entity.Cell, createCell bool)
}

Col is the interface that wraps the basic methods of a col.

type Component

type Component interface {
	Node
	Render(provider Provider, cell *entity.Cell)
	GetHeight(provider Provider, cell *entity.Cell) float64
}

Component is the interface that wraps the basic methods of a component.

type Document

type Document interface {
	GetBytes() []byte
	GetBase64() string
	// Write streams the document to w without an intermediate copy beyond the already-generated buffer.
	Write(w io.Writer) (int64, error)
	Save(file string) error
	GetReport() *metrics.Report
	Merge(ctx context.Context, bytes []byte) error
}

Document is the interface that wraps the basic methods of a document.

type DocumentConfigProvider

type DocumentConfigProvider interface {
	SetProtection(protection *entity.Protection)
	SetCompression(compression bool)
	SetMetadata(metadata *entity.Metadata)
}

DocumentConfigProvider is the provider surface used to apply document-level options.

type DocumentProvider

type DocumentProvider interface {
	GenerateBytes() ([]byte, error)
}

DocumentProvider is the provider surface that finalizes generated PDF bytes.

type Font

type Font interface {
	SetFamily(family string)
	SetStyle(style fontstyle.Type)
	SetSize(size float64)
	SetFont(family string, style fontstyle.Type, size float64)
	GetFamily() string
	GetStyle() fontstyle.Type
	GetSize() float64
	GetFont() (string, fontstyle.Type, float64)
	GetHeight(family string, style fontstyle.Type, size float64) float64
	SetColor(color *props.Color)
	GetColor() *props.Color
}

Font is the abstraction which deals of how to set fontstyle configurations.

type GradientProvider

type GradientProvider interface {
	// DrawGradient rasterises the gradient and paints it behind the cell area.
	// widthMM and heightMM are the cell dimensions in mm.
	DrawGradient(cell *entity.Cell, g *props.Gradient, widthMM, heightMM float64)
}

GradientProvider is an optional capability interface for providers that can render CSS gradient backgrounds as rasterised PNG images embedded in the PDF.

Usage:

if gp, ok := provider.(core.GradientProvider); ok {
    gp.DrawGradient(cell, gradient, widthMM, heightMM)
}

type GridProvider

type GridProvider interface {
	CreateRow(height float64)
	CreateCol(width, height float64, config *entity.Config, prop *props.Cell)
}

GridProvider is the provider surface used to advance the PDF grid cursor and paint row/column cells.

type Image

type Image interface {
	Add(img *entity.Image, cell *entity.Cell, margins *entity.Margins, prop *props.Rect, extension extension.Type, flow bool) error
	GetImageDimensions(img *entity.Image, extension extension.Type) *entity.Dimensions
}

Image is the abstraction which deals of how to add images in a PDF.

type ImageProvider

type ImageProvider interface {
	GetDimensionsByImageByte(bytes []byte, extension extension.Type) (*entity.Dimensions, error)
	GetDimensionsByImage(file string) (*entity.Dimensions, error)
	AddImageFromFile(value string, cell *entity.Cell, prop *props.Rect)
	AddImageFromBytes(bytes []byte, cell *entity.Cell, prop *props.Rect, extension extension.Type)
	AddBackgroundImageFromBytes(bytes []byte, cell *entity.Cell, prop *props.Rect, extension extension.Type)
}

ImageProvider is the provider surface used by image and background-image components.

type KeepWithNext added in v0.2.2

type KeepWithNext interface {
	KeepWithNext() bool
}

KeepWithNext asks the page builder to move a row and its successor to the next page when the two would otherwise be separated by a page boundary.

type LateFontProvider

type LateFontProvider interface {
	// RegisterFont makes a TTF/OTF font available under the given family and
	// style for subsequent text rendering. Returns immediately; rendering
	// errors (malformed font data) are surfaced by the next text draw call.
	RegisterFont(family string, style fontstyle.Type, bytes []byte)
}

LateFontProvider is a narrow optional capability interface for providers that can register a font from raw TTF/OTF bytes AFTER initialization. Used by the HTML @font-face handler which only discovers font sources at translation time (after the provider has already started building the PDF).

Consumers detect support via the safe type-assertion idiom:

if lfp, ok := provider.(core.LateFontProvider); ok {
    lfp.RegisterFont(family, style, bytes)
}

type LayeredRow added in v0.2.2

type LayeredRow interface {
	// RenderLayer returns the paint layer for the row.
	RenderLayer() int
}

LayeredRow is an optional capability for rows that render out of the normal flow paint order. Negative layers paint behind the page's flow rows, positive layers in front; 0 (or not implementing the interface) is normal flow order. Used by CSS positioned rows carrying a z-index.

type Line

type Line interface {
	Add(cell *entity.Cell, prop *props.Line)
}

Line is the abstraction which deals of how to add lines inside PDF.

type LineProvider

type LineProvider interface {
	AddLine(cell *entity.Cell, prop *props.Line)
}

LineProvider is the provider surface used by line components.

type LinkProvider

type LinkProvider interface {
	// AddLink reserves a new internal link target ID. Returns the link ID.
	AddLink() int
	// SetLink registers the target's Y position (mm from page top) and
	// page number (1-based) for a previously reserved link ID.
	SetLink(linkID int, y float64, page int)
	// Link makes a rectangular area clickable, jumping to the named link ID.
	// x and y are in mm from the page's top-left; w and h are the bounding box.
	Link(x, y, w, h float64, linkID int)
}

LinkProvider is a narrow optional capability interface for providers that support PDF internal links (named destinations and click-to-jump).

The two-pass anchor flow:

  1. Translator pre-walks the DOM; for every `id="…"` element it calls AddLink() to reserve a link ID and stores name → id in a map.
  2. During render, anchorTarget components call SetLink(id, y, page) to register the destination at the correct coordinates.
  3. anchorSource components / RichRuns with LocalAnchor call Link(...) at their bounding box to make the area clickable.

Consumers detect support via the safe type-assertion idiom:

if lp, ok := provider.(core.LinkProvider); ok { ... }

type Math

type Math interface {
	GetInnerCenterCell(inner *entity.Dimensions, outer *entity.Dimensions) *entity.Cell
	Resize(inner *entity.Dimensions, outer *entity.Dimensions, percent float64, justReferenceWidth bool) *entity.Dimensions
}

Math is the abstraction which deals with useful calc.

type NamedLinkProvider added in v0.2.2

type NamedLinkProvider interface {
	LinkProvider
	// AddNamedLink reserves the internal link target called name, returning the
	// same link ID for repeated calls with the same name.
	AddNamedLink(name string) int
}

NamedLinkProvider is an optional extension of LinkProvider for providers that can reserve a link target under a document-level name.

Link IDs are provider-scoped. Under parallel page rendering each worker owns a separate document, so the worker that renders an anchor's target and the workers that render links to it reserve independent IDs. A name gives those reservations a shared identity, so they collapse into one link when the pages are spliced. Providers that do not implement this still work; their cross-worker links simply cannot be reconciled, which is why callers should prefer AddNamedLink whenever the destination has a name.

type NearBoundarySplitter added in v0.2.2

type NearBoundarySplitter interface {
	NearBoundaryThreshold() float64
}

NearBoundarySplitter lets a fitting row move selected content to the next page when too little space remains for that content's painted box.

type Node

type Node interface {
	SetConfig(config *entity.Config)
	GetStructure() *node.Node[Structure]
}

Node is the interface that wraps the basic methods of a node.

type OutlineProvider added in v0.2.0

type OutlineProvider interface {
	// Bookmark records an outline entry titled title at nesting depth level
	// (0 = top level) pointing at vertical position y, in mm measured from
	// the top of the page content area (margins are added by the provider).
	Bookmark(title string, level int, y float64)
}

OutlineProvider is a narrow optional capability interface for providers that support PDF document outlines (the bookmark sidebar in PDF viewers).

Components with an Outline prop call Bookmark during render; the entry is recorded on the current page at the given vertical position.

Consumers detect support via the safe type-assertion idiom:

if op, ok := provider.(core.OutlineProvider); ok { ... }

type Page

type Page interface {
	Node
	Add(rows ...Row) Page
	GetRows() []Row
	GetNumber() int
	SetNumber(number int, total int)
	Render(provider Provider, cell entity.Cell)
}

Page is the interface that wraps the basic methods of a page.

type PageBoundaryAllowance added in v0.2.2

type PageBoundaryAllowance interface {
	PageBoundaryAllowance() float64
}

PageBoundaryAllowance reserves trailing space that is not part of a row's measured content height when deciding whether to split near a page edge.

type PageBreakPreview added in v0.2.2

type PageBreakPreview interface {
	PageBreakPreview(provider Provider, width float64) Row
}

PageBreakPreview optionally paints a blank copy of a row on the current page when the row itself moves with the following content.

type PageBreaker

type PageBreaker interface {
	// IsPageBreak returns true when this row signals a hard page break.
	IsPageBreak() bool
}

PageBreaker is an optional interface that a Row can implement to signal paper.addRow() to force a page break before placing the row's content. The row itself is NOT placed on any page — it is consumed entirely by the page-break mechanic. Render() of a PageBreaker row is a no-op.

Usage: implement IsPageBreak() bool on a row type and return true. paper.addRow() detects this via type assertion and calls fillPageToAddNew().

type PageContextProvider added in v0.2.2

type PageContextProvider interface {
	// WithPageContext runs fn with the current/total page context installed,
	// restoring the previous context afterwards.
	WithPageContext(current, total int, fn func())
	// WithPageContextStrings is WithPageContext with named running strings
	// (e.g. the active chapter title) additionally in scope.
	WithPageContextStrings(current, total int, runningStrings map[string]string, fn func())
}

PageContextProvider is an optional capability for providers that expose the physical page context (current page index, total pages, and running strings such as CSS running headers) to components while they render.

Consumers detect support via the safe type-assertion idiom:

if pcp, ok := provider.(core.PageContextProvider); ok {
    pcp.WithPageContextStrings(current, total, runningStrings, fn)
}

type PageControl added in v0.2.2

type PageControl struct {
	Blank                     bool
	SuppressFooter            bool
	SuppressPageNumber        bool
	CountPageNumber           bool
	DecorFirstPageOnly        bool
	TopMargin                 *float64
	TopMarginFirstPageOnly    bool
	ContinuationTopMargin     *float64
	RenderOffsetX             *float64
	RenderOffsetY             *float64
	RenderOffsetFirstPageOnly bool
	ContinuationRenderOffsetX *float64
	ContinuationRenderOffsetY *float64
}

PageControl carries non-content pagination directives consumed by the page builder. It is intentionally small: HTML translation can emit a control row without depending on the concrete paper builder.

type PageController added in v0.2.2

type PageController interface {
	PageControl() PageControl
}

PageController marks a zero-content Row as a pagination control directive.

type PageProvider

type PageProvider interface {
	EnsurePage(pageNumber int)
}

PageProvider is an optional capability for providers that can ensure the physical output page matches Paper's logical page during rendering.

type Paper

type Paper interface {
	RegisterHeader(rows ...Row) error
	RegisterFooter(rows ...Row) error
	AddRows(rows ...Row)
	AddRow(rowHeight float64, cols ...Col) Row
	AddAutoRow(cols ...Col) Row
	AddHTML(ctx context.Context, htmlStr string) error
	// FitInCurrentPage reports whether a row of the given height fits in the remaining useful area of the current page.
	FitInCurrentPage(heightNewLine float64) bool
	GetCurrentConfig() *entity.Config
	AddPages(pages ...Page)
	GetStructure() *node.Node[Structure]
	Generate(ctx context.Context) (*Pdf, error)
}

Paper is the interface that wraps the basic methods of paper.

type Pdf

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

Pdf is a generated document: its bytes plus the timing report collected while building it.

func NewPDF

func NewPDF(bytes []byte, report *metrics.Report) *Pdf

NewPDF creates a concrete PDF document.

func (*Pdf) GetBase64

func (p *Pdf) GetBase64() string

GetBase64 returns the PDF bytes in base64.

func (*Pdf) GetBytes

func (p *Pdf) GetBytes() []byte

GetBytes returns the PDF bytes.

func (*Pdf) GetReport

func (p *Pdf) GetReport() *metrics.Report

GetReport returns the metrics.Report.

func (*Pdf) Merge

func (p *Pdf) Merge(ctx context.Context, bytes []byte) error

Merge merges the PDF with another PDF. It observes ctx between merged documents.

func (*Pdf) Save

func (p *Pdf) Save(file string) error

Save saves the PDF in a file. The file is created with the usual 0666 before umask, not the 0777 that os.ModePerm would grant.

func (*Pdf) Write

func (p *Pdf) Write(w io.Writer) (int64, error)

Write streams the document to w without an intermediate copy beyond the already-generated buffer.

type PositionProvider

type PositionProvider interface {
	SetCursor(x, y float64)
}

PositionProvider lets composite components (blockContainer, flexCellContent) reset the underlying pen to a known X/Y before invoking a sub-component's Render. Without this, cellwriter chain nodes that use GetXY() as the cell origin (perSideBorder, borderRadius) draw at the wrong position when the pen has drifted due to prior CellFormat/Ln calls.

type Provider

Provider is the abstraction of a document creator provider.

type RenderIssueProvider

type RenderIssueProvider interface {
	RenderIssues() []metrics.RenderIssue
}

RenderIssueProvider exposes best-effort render fallbacks recorded by a provider.

type RichTextMeasurer

type RichTextMeasurer interface {
	MeasureRichText(runs []props.RichRun, cell *entity.Cell, prop *props.RichText) float64
}

RichTextMeasurer is an optional provider capability for exact rich text height calculation. Components that only receive Provider can type-assert to this interface and still fall back to Provider.GetLinesQuantity when absent.

type RichTextProvider

type RichTextProvider interface {
	MeasureString(text string, prop *props.Text) float64
	AddTextAt(x, y float64, text string, prop *props.Text)
	AddRichText(runs []props.RichRun, cell *entity.Cell, prop *props.RichText)
}

RichTextProvider is a narrow capability interface for components that need inline-run measurement and placement (RichText, Table, HTMLList). It is separate from Provider to avoid triggering mock regeneration across the 13+ test files that mock Provider with strict EXPECT() assertions. The gofpdf *provider satisfies both Provider and RichTextProvider.

type Row

type Row interface {
	Node
	Add(cols ...Col) Row
	GetHeight(provider Provider, cell *entity.Cell) float64
	GetColumns() []Col
	WithStyle(style *props.Cell) Row
	Render(provider Provider, cell entity.Cell)
}

Row is the interface that wraps the basic methods of a row.

type ShapeProvider

type ShapeProvider interface {
	// DrawFilledCircle draws a filled circle inscribed in the given cell using
	// fill.FillColor (or BlackColor when nil). The cell's center and width
	// dimensions determine the circle's position and diameter.
	DrawFilledCircle(cell *entity.Cell, fill *props.Color)
}

ShapeProvider is a narrow optional capability interface for components that need to draw primitive geometric shapes (currently used by htmllist's DecimalCircle marker). Components detect support via a type assertion and fall back to text-only rendering when unavailable — see the same pattern used for RichTextProvider in pkg/components/htmllist/htmllist.go.

type Splittable

type Splittable interface {
	SplitAt(provider Provider, remainingHeight float64, width float64) (first, rest Row, didSplit bool)
}

Splittable is an optional interface that a Row can implement to allow paper.addRow() to split it across a page boundary during the build phase.

When addRow() determines the row is too tall for the remaining page space and the row implements Splittable, it calls SplitAt(remainingHeight):

  • didSplit==false: the row fits; proceed normally (no split needed)
  • didSplit==true, first!=nil: place first on the current page, then fillPageToAddNew() + addHeader(), then recursively addRow(rest)
  • didSplit==true, first==nil: atomic mode — push the whole row to the next page (break-inside: avoid)

width is the page content width the row will actually render at, so the row measures its children at the same width used for rendering (a stale or fallback width mis-sizes wrapped content and overflows the page).

SplitAt must be side-effect free on the original row.

type Structure

type Structure struct {
	Type    string
	Value   any
	Details map[string]any
}

Structure is the representation of the component tree structure.

type Text

type Text interface {
	Add(text string, cell *entity.Cell, textProp *props.Text)
	GetLinesQuantity(text string, textProp *props.Text, colWidth float64) int
}

Text is the abstraction which deals of how to add text inside PDF.

type TextProvider

type TextProvider interface {
	AddText(text string, cell *entity.Cell, prop *props.Text)
	AddCheckbox(label string, cell *entity.Cell, prop *props.Checkbox)
	GetFontHeight(prop *props.Font) float64
	GetLinesQuantity(text string, textProp *props.Text, colWidth float64) int
}

TextProvider is the provider surface used by text-like components.

type TransformProvider added in v0.2.2

type TransformProvider interface {
	// WithTransform applies ops around the origin point relative to cell's
	// top-left corner, renders fn, then restores the provider transform state.
	WithTransform(cell *entity.Cell, originX, originY float64, ops []props.TransformOp, fn func())
}

TransformProvider is an optional capability for providers that can wrap rendering in a temporary 2D transform context. Coordinates and translate distances are margin-relative millimetres, matching entity.Cell.

type WatermarkProvider added in v0.2.0

type WatermarkProvider interface {
	// AddWatermark draws prop.Text centered in cell, rotated by prop.Angle
	// around the cell center, with prop.Alpha opacity. The font size is
	// scaled down when the text would exceed the cell diagonal.
	AddWatermark(cell *entity.Cell, prop *props.Watermark)
}

WatermarkProvider is a narrow optional capability interface for providers that can stamp a translucent rotated text watermark onto the current page.

Consumers detect support via the safe type-assertion idiom:

if wp, ok := provider.(core.WatermarkProvider); ok { ... }

Directories

Path Synopsis
Package entity contains all core entities.
Package entity contains all core entities.

Jump to

Keyboard shortcuts

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