csspdf

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 31 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.

README

csspdf

A Go library for generating PDF files from:

  • HTML template fragments
  • CSS
  • flow JSON (section orchestration + payload transforms)
  • source data (JSON or Go object)
  • optional Go template functions

The reusable public package is:

  • github.com/otuschhoff/csspdf

Requirements and Dependency Policy

  • Go 1.26.6 or newer
  • No sibling repositories or local Go workspace are required
  • Dependencies are pinned in go.mod and go.sum

The PDF backend is the pinned github.com/otuschhoff/gofpdf fork dependency. The required APIs, UTF-8 fixes, and their regression tests are maintained in that repository; csspdf does not require a sibling checkout or local replace.

Supported release lines, compatibility rules, deprecations, provenance, and release checks are documented in API compatibility, asset provenance, and the release procedure. The complete documentation map is in docs/README.md. The project is distributed under the MIT License.

Status

This repository now separates:

  • Generic rendering engine: csspdf
  • Rendering internals: internal/pdfrender, internal/pdfdom, internal/templating, internal/flowrender
  • Layered CSS example: examples/layered

Quick Start

package main

import (
	"log"

	"github.com/otuschhoff/csspdf"
)

func main() {
	assets := csspdf.Assets{
		HTML: `{{define "document"}}<div>Hello {{.Source.Name}}</div>{{end}}`,
		CSS:  `@page { size: A4; margin: 20pt; }`,
		Flow: csspdf.Flow{MainFlow: []csspdf.Section{{
			Template:    "document",
			Transformer: "generic",
			Payload:     csspdf.PayloadConfig{IncludeSource: true},
		}}},
		SourceData: map[string]any{"Name": "Docflow", "locale": "en"},
	}

	err := csspdf.RenderToFile(csspdf.RenderInput{
		Assets:              assets,
		DefaultLocale:       "en",
		DefaultCurrencyCode: "EUR",
	}, "output.pdf")
	if err != nil {
		log.Fatal(err)
	}
}

Public API Overview

Primary package:

  • csspdf

Core methods:

  • Render(outputPath, options...): convenience API that builds RenderInput internally
  • RenderWithInput(input): full-struct API for advanced control
  • RenderToFile(input, outputPath)
  • RenderToWriter(input, writer)
  • RenderToBytes(input)

Input models:

  • RenderInput
  • Assets
  • AssetInput
  • TextSource
  • JSONSource

I18n source input:

  • RenderInput.I18nSource also uses JSONSource, so translations can come from object, raw/text JSON, file path, or io/fs.

Template functions:

  • Legacy hook: FuncMapFactory(defaultLocale, payloadLocale)
  • Context-aware hook: FuncMapFactoryEx(FuncContext) with deterministic Now function
  • Reusable default helpers: DefaultTemplateFuncMap(defaultLocale, payloadLocale)
  • Context-aware default helpers: DefaultTemplateFuncMapWithContext(FuncContext)

Date formatting helpers available in templates:

  • formatLocalizedDate value style [localeOverride]
  • formatLocalizedDateOrNow value style [localeOverride]

Supported styles:

  • written-month (month name only)
  • local (locale-default full date)
  • short (numeric short date)
  • datetime (date + time)
  • layout:<go time layout> (custom layout)

Examples:

{{formatLocalizedDate .Source.Invoice.Date "local"}}
{{formatLocalizedDate .Source.Invoice.Date "local" "de"}}
{{formatLocalizedDate .Source.Invoice.Date "written-month"}}
{{formatLocalizedDate .Source.Invoice.Date "short"}}
{{formatLocalizedDate .Source.Invoice.Date "datetime"}}
{{formatLocalizedDate .Source.Invoice.Date "layout:2006-01-02"}}
{{formatLocalizedDateOrNow .Source.DocDate "local"}}

Typical output examples:

  • de + local => 31. Juli 2026
  • en + local => July 31 2026
  • de + written-month => Juli
  • en + written-month => July

Optional i18n macro execution:

  • Enable with WithI18nTemplateMacros(true).
  • When enabled, i18n string values are treated as Go templates and can use the same helper functions as document templates.
  • i18n templates can reference values from data.json via .Source, for example:
{
	"invoiceIntro": {
		"en": "Services in {{formatLocalizedDateOrNow .Source.Invoice.Date \"written-month\"}}"
	}
}

Asset Input Modes

TextSource supports:

  • Raw []byte
  • Text string
  • FilePath
  • io/fs (FS + FSPath)

JSONSource supports:

  • Object (Go struct/map/slice)
  • Raw []byte
  • Text string
  • FilePath
  • io/fs (FS + FSPath)

This avoids mandatory caller-side JSON serde when using the library in Go apps.

Confined Rendering

For service workloads, confine file-backed resources and set explicit budgets:

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := os.MkdirAll(".build/output", 0o755); err != nil {
	log.Fatal(err)
}
err := csspdf.RenderContext(ctx, ".build/output/document.pdf",
	csspdf.WithConfinedResourceRoot("/srv/csspdf/jobs/job-123"),
	csspdf.WithRenderLimits(csspdf.RenderLimits{
		SourceBytes:         4 << 20,
		TemplateOutputBytes: 8 << 20,
		ImageBytes:          8 << 20,
		ImagePixels:         12_000_000,
		OutputBytes:         32 << 20,
		Nodes:               25_000,
		Depth:               128,
		Rows:                10_000,
		Pages:               250,
	}),
)

Zero limit fields use safe library defaults. Budget violations return *csspdf.BudgetError; file output remains atomic. Templates and custom Go functions remain trusted code, and hard resource ceilings require process or container isolation. See the security contract.

Layered CSS Usage

You can compose CSS in ordered layers with AssetInput.CSSLayers. Later layers override earlier mapped declarations.

csspdf intentionally implements a documented CSS subset rather than a browser cascade. Use csspdf.SupportedCSSProperties() for the executable property matrix and csspdf.AnalyzeCSSSupport(cssText) to detect ignored properties (CSS001) before rendering. Rules of equal or different selector shapes use source order; selector specificity and !important are not interpreted.

assetInput := csspdf.AssetInput{
	HTML:       csspdf.TextSource{FilePath: "examples/layered/doc.html"},
	Flow:       csspdf.JSONSource{FilePath: "examples/layered/flow.json"},
	SourceData: csspdf.JSONSource{FilePath: "examples/layered/data.json"},
	CSSLayers: []csspdf.CSSLayerInput{
		{Name: "corporate-base", Source: csspdf.TextSource{FilePath: "examples/layered/styles/corporate/base.css"}},
		{Name: "document", Source: csspdf.TextSource{FilePath: "examples/layered/styles/document/doc.css"}},
		{Name: "customer-override", Source: csspdf.TextSource{FilePath: "examples/layered/styles/overrides/customer.css"}, Optional: true},
	},
}

if err := os.MkdirAll(".build/output", 0o755); err != nil {
	log.Fatal(err)
}
err := csspdf.Render(".build/output/layered.pdf",
	csspdf.WithAssetInput(assetInput),
	csspdf.WithDefaultLocale("en"),
	csspdf.WithDefaultCurrencyCode("EUR"),
	csspdf.WithFuncMapFactoryEx(csspdf.DefaultTemplateFuncMapWithContext),
)
if err != nil {
	log.Fatal(err)
}

Run the included end-to-end layered profile example:

go run ./cmd/csspdf gen-example layered -o .build/output/layered.pdf

Render the 20-case office and business document gallery:

go run ./cmd/csspdf gen-example office-suite -o .build/output/office-suite

The gallery includes memos, letters, receipts, quotes, orders, invoices, reports, contracts, a landscape catalog, a high-volume stress document, and three asserted failure cases. See the office-suite guide.

Notes:

  • If both CSSLayers and legacy Assets.CSS are set, legacy CSS is applied as an implicit final layer.
  • csspdf uses mapped-property style application, not full browser cascade semantics.
  • HTML and CSS support a deliberate document-rendering subset. Do not assume browser-equivalent selector, cascade, layout, scripting, or network behavior.

Migration helper example:

legacyInput := csspdf.AssetInput{
	HTML: csspdf.TextSource{FilePath: "templates/doc.html"},
	CSS:  csspdf.TextSource{FilePath: "templates/doc.css"},
	Flow: csspdf.JSONSource{FilePath: "templates/flow.json"},
}

layeredInput := csspdf.MigrateAssetInputLegacyCSSToSingleLayer(legacyInput, "legacy")

Rollout checks:

./scripts/check-layered-rollout.sh

The rollout script:

  • runs focused tests
  • renders legacy and layered examples
  • reports PDF sizes
  • prints a layered CSS duplication metric

Layered HTML Shell Usage

You can compose HTML templates in ordered layers with AssetInput.HTMLLayers. Layers are parsed first, then legacy AssetInput.HTML is parsed last as an implicit final layer, so document templates can override shared block defaults.

assetInput := csspdf.AssetInput{
	HTML: csspdf.TextSource{FilePath: "templates/invoice.content.html"},
	HTMLLayers: []csspdf.HTMLLayerInput{
		{
			Name: "shared-shell",
			Source: csspdf.TextSource{FilePath: "templates/default.shell.html"},
		},
	},
	CSS:        csspdf.TextSource{FilePath: "templates/doc.css"},
	Flow:       csspdf.JSONSource{FilePath: "templates/flow.json"},
	SourceData: csspdf.JSONSource{FilePath: "templates/data.json"},
}

Shared shell example (default.shell.html):

{{define "doc"}}
<div id="page">
	{{block "default-letterhead" .}}<div>ACME Corp</div>{{end}}
	{{block "document-content" .}}<div>Default body</div>{{end}}
	{{block "default-footer" .}}<div>Default footer</div>{{end}}
</div>
{{end}}

{{define "page-number"}}<div>{{.page.pageNumber}} / {{.page.pageNumberTotal}}</div>{{end}}

Document content example (invoice.content.html):

{{define "document-content"}}<div>Invoice {{.Source.Invoice.ID}}</div>{{end}}
{{define "default-footer"}}<div>Invoice-specific footer</div>{{end}}

Notes:

  • HTMLLayers are optional; existing single-file HTML templates keep working unchanged.
  • If a wrapper references missing nested templates (for example document-content), render fails with a template error.
  • This composition model works with CSSLayers, so shared markup and shared styles can both be centralized.

Flow JSON Validation

Flow validation now checks:

  • Required sections/templates
  • Supported transformers (currently generic)
  • Payload path syntax
  • Runtime expression syntax

Supported runtime expressions:

  • flow.tableWidth
  • flow.remainingWidth:
  • page.number
  • page.total

Warnings and Diagnostics

RenderInput supports warning sinks via:

  • Logger (preferred)
  • WarningWriter (deprecated; removed in v0.3.0, see docs/architecture/api-compatibility.md)

The warning sink intentionally remains a minimal Warnf compatibility interface. Typed render failures use DiagnosticError; applications that need structured logs should inspect those errors with errors.As and adapt warning messages at their boundary rather than parsing error strings.

All configured resource and processing limit failures match csspdf.ErrLimitExceeded through wrapping. Use errors.Is(err, csspdf.ErrLimitExceeded) for the general category and errors.As with BudgetError or LimitError when concrete limit details are required. File-source errors preserve their underlying causes, including fs.ErrNotExist and fs.ErrPermission.

Rendering is strict by default. Missing templates, missing map values, missing images, invalid numeric span attributes, and element-rendering failures return errors instead of producing an incomplete PDF. Applications that temporarily require the previous behavior can set RenderInput.AllowPartialRender or use WithLegacyPartialRendering(true); recoverable failures are then sent to the warning sink while rendering continues. This legacy path is deprecated and scheduled for removal in v0.3.0.

RenderToFile renders before touching the destination and replaces it through a temporary file in the destination directory. Existing file permissions are preserved; new files are owner-only (0600). RenderToWriter cannot roll back bytes already accepted by an arbitrary writer. See docs/guides/migration-v0.2.md for the complete output contract.

Input Normalization

JSON numbers decoded into dynamic values use json.Number, preserving their source representation and integers above $2^{53}$. Custom template functions should use json.Number.String, Int64, or Float64 according to whether the value is an identifier, integer, or quantity. Generic numeric helpers accept both json.Number and native Go numeric values.

Flow JSON rejects unknown fields. Runtime and static payload targets cannot overlap, use prefix-conflicting paths, or overwrite the reserved roots Source, Payload, page, locale, and i18n.

Without an explicit i18n source, formatting uses self-contained separators: German uses decimal comma and thousands point; other locales use decimal point and thousands comma. AssetBaseDir/i18n.json remains an explicit profile default when an asset base directory is configured.

Currency formatting rounds the complete value once using the precision of the currency: JPY uses zero decimals, BHD and KWD use three, and other currencies use two. Rounded negative zero is emitted without a minus sign. Float inputs retain IEEE 754 semantics; applications requiring exact financial arithmetic should calculate exact minor units before passing display values to csspdf.

Layout Guarantees

Consecutive flow sections share a persistent normal-flow cursor and therefore do not overlap. Absolute elements and page-number overlays are page-local and do not alter that cursor.

Page dimensions and margins must define a finite, positive content box. Normal-flow tables paginate between rows and repeat leading thead rows on each page. Colspan occupancy is shared by width inference, row measurement, and rendering. A table row or image that cannot fit on an empty content box returns an overflow error rather than rendering beyond the page. Long text continues across pages without rewrapping already rendered lines.

See the layout contract for detailed overflow and compatibility behavior.

Security and Trust Model

The current release is intended for trusted local authoring. Treat HTML/CSS templates, flow definitions, asset paths, font registrations, and custom Go template functions as trusted configuration. They are not sandboxed.

Do not expose the renderer directly to tenant- or user-supplied templates or asset paths. File sources and image/font lookup can access the host filesystem, including configured absolute paths and compatibility search locations. The renderer does not currently enforce input-size, page-count, image-size, or execution-time limits. Use process isolation and application-level limits when rendering data from less-trusted sources. See SECURITY.md for the complete current boundary.

Deterministic Rendering Support

RenderInput.Now can inject a custom clock. When it is non-nil, the returned time also fixes the PDF creation and modification metadata. The renderer emits resource catalogs in stable order, so repeated renders are byte-identical when templates, data, resources, options, and custom functions are themselves deterministic.

When FuncMapFactoryEx is used, the function context receives Now. With no clock configured, metadata uses the current time and only semantic output is expected to be stable; byte identity is not part of the default contract.

Example Profile

Layered CSS concept assets live in:

  • examples/layered

This keeps csspdf generic while demonstrating layered style composition.

Testing

Run the complete local quality gate:

./scripts/check-quality.sh

The gate checks module tidiness, dependency checksums, formatting, builds, static analysis, root-module tests, package coverage floors, and reachable vulnerabilities. The vulnerability tool is pinned; set RUN_VULN_CHECK=false only for a fast local iteration after an unchanged successful scan. The initial scan and clean-checkout evidence are recorded in docs/history/phase0-baseline.md.

Release-readiness evidence and troubleshooting guidance are recorded in docs/maintenance/release-readiness.md and docs/guides/troubleshooting.md.

Run the changed-code maintainability ratchet with:

go install github.com/fzipp/gocyclo/cmd/gocyclo@v0.6.0
./scripts/check-maintainability.sh

Run the measured performance corpus with:

./scripts/benchmark-phase5.sh

Reference results, workload definitions, the regression budget, and the determinism contract are recorded in docs/maintenance/performance.md.

Tasks

Run tasks with xc <task>. The task definitions below are xc-compatible.

build

Build the CLI binary into .build/bin/. Repository-local binaries, rendered examples, and persistent profiles belong under the ignored .build/ tree; self-cleaning test and coverage files remain in the operating-system temp directory.

mkdir -p .build/bin
go build -o .build/bin/csspdf ./cmd/csspdf
render-sample

Build and render the layered sample document.

mkdir -p .build/bin
go build -o .build/bin/csspdf ./cmd/csspdf
./.build/bin/csspdf gen-example layered -o .build/output/layered.pdf
test

Run the same test suites used by CI.

go test ./... -count=1

Supported Components

  • csspdf is the supported library API.
  • cmd/csspdf is the supported repository tool, with gen-example, dom-parse, and pdfdump commands.
  • The csspdf pdfdump command is supported for bounded inspection; it is not a PDF conformance validator.
  • examples/layered contains reference assets, not stable Go APIs.
  • Generated binaries and output files are unsupported artifacts and are ignored by version control.

Documentation

Overview

Package csspdf provides a generic, flow-driven PDF rendering library.

It renders PDF documents from:

  • HTML template fragments
  • optional layered HTML shells
  • CSS
  • flow JSON (section orchestration + payload transforms)
  • source data (JSON or native Go objects)
  • optional Go template functions

The package supports file, writer, and in-memory byte outputs.

For migration from legacy single-CSS inputs to layered CSS, helper functions are provided:

  • LegacyCSSSourceAsLayer
  • MigrateAssetInputLegacyCSSToSingleLayer

Index

Constants

View Source
const (
	DefaultLocale       = "en"
	DefaultCurrencyCode = "EUR"
	DefaultPageFormat   = "A4"

	PageOrientationPortrait  = "portrait"
	PageOrientationLandscape = "landscape"
)
View Source
const UnsupportedCSSPropertyCode = templateload.UnsupportedCSSPropertyCode

Variables

View Source
var ErrLimitExceeded = limitmarker.ErrExceeded

ErrLimitExceeded identifies failures caused by a configured resource or rendering limit.

Functions

func DefaultTemplateFuncMap

func DefaultTemplateFuncMap(defaultLocale, payloadLocale string) htmltmpl.FuncMap

DefaultTemplateFuncMap returns a reusable set of generic template helper functions that can be embedded into profile-specific function maps.

func DefaultTemplateFuncMapWithContext

func DefaultTemplateFuncMapWithContext(ctx FuncContext) htmltmpl.FuncMap

DefaultTemplateFuncMapWithContext returns the same generic helper set as DefaultTemplateFuncMap but uses FuncContext to support deterministic clocks.

func FormatLocalizedTime

func FormatLocalizedTime(t time.Time, locale, style string) string

FormatLocalizedTime formats a time value using locale-aware styles.

Supported styles:

  • "written-month" (or "month", "month-name"): month name only
  • "local" (or "locale", "default"): locale-default full date
  • "short": short numeric date format
  • "datetime": locale-default date + time
  • "layout:<go time layout>": custom Go layout using localized month/day names

func Render

func Render(outputPath string, options ...RenderOption) error

Render builds a RenderInput internally from defaults + options and renders to outputPath.

func RenderContext

func RenderContext(ctx context.Context, outputPath string, options ...RenderOption) error

RenderContext builds a RenderInput from options and renders with ctx.

func RenderToBytes

func RenderToBytes(input RenderInput) ([]byte, error)

RenderToBytes renders and returns a complete PDF byte slice.

func RenderToBytesContext

func RenderToBytesContext(ctx context.Context, input RenderInput) ([]byte, error)

RenderToBytesContext renders and returns a complete bounded PDF byte slice.

func RenderToFile

func RenderToFile(input RenderInput, outputPath string) error

RenderToFile renders and atomically writes a PDF to the given file path.

func RenderToFileContext

func RenderToFileContext(ctx context.Context, input RenderInput, outputPath string) error

RenderToFileContext renders and atomically writes a PDF with cancellation.

func RenderToWriter

func RenderToWriter(input RenderInput, out io.Writer) error

RenderToWriter renders and writes a PDF to an io.Writer.

func RenderToWriterContext

func RenderToWriterContext(ctx context.Context, input RenderInput, out io.Writer) error

RenderToWriterContext renders a PDF to out with cancellation and budgets.

func RenderWithInput

func RenderWithInput(input RenderInput) error

RenderWithInput renders using a fully specified RenderInput.

func RenderWithInputContext

func RenderWithInputContext(ctx context.Context, input RenderInput) error

RenderWithInputContext renders using a fully specified input and context.

func SupportedCSSProperties

func SupportedCSSProperties() []string

SupportedCSSProperties returns the stable mapped CSS property set.

Types

type AssetInput

type AssetInput struct {
	HTML       TextSource
	HTMLLayers []HTMLLayerInput
	CSS        TextSource
	CSSLayers  []CSSLayerInput
	Flow       JSONSource
	SourceData JSONSource
}

func MigrateAssetInputLegacyCSSToSingleLayer

func MigrateAssetInputLegacyCSSToSingleLayer(in AssetInput, layerName string) AssetInput

MigrateAssetInputLegacyCSSToSingleLayer converts AssetInput.CSS into one CSSLayers entry and clears AssetInput.CSS. If CSS is not set, input is returned unchanged.

func (AssetInput) ResolveAssets

func (in AssetInput) ResolveAssets() (Assets, error)

func (AssetInput) ResolveWithBaseDir

func (in AssetInput) ResolveWithBaseDir(baseDir string) (Assets, error)

ResolveWithBaseDir resolves assets from baseDir defaults and allows per-asset overrides from the receiver.

Defaults relative to baseDir:

  • doc.html
  • doc.css
  • flow.json
  • data.json

type Assets

type Assets struct {
	HTML       string
	HTMLLayers []HTMLLayer
	CSS        string
	CSSLayers  []CSSLayer
	Flow       Flow
	SourceData map[string]any
}

func (Assets) Validate

func (a Assets) Validate() error

type BudgetError

type BudgetError struct {
	Stage  string
	Limit  int64
	Actual int64
}

BudgetError reports an operational render limit violation.

func (*BudgetError) Error

func (e *BudgetError) Error() string

func (*BudgetError) Is

func (e *BudgetError) Is(target error) bool

type CSSLayer

type CSSLayer struct {
	Name     string
	CSS      string
	Optional bool
}

CSSLayer is a resolved stylesheet layer. Layers are applied in order and then legacy Assets.CSS is applied last.

type CSSLayerInput

type CSSLayerInput struct {
	Name     string
	Source   TextSource
	Optional bool
}

AssetInput resolves all render assets from flexible sources.

func LegacyCSSSourceAsLayer

func LegacyCSSSourceAsLayer(source TextSource, layerName string) CSSLayerInput

LegacyCSSSourceAsLayer converts a legacy CSS source into a single CSS layer input suitable for AssetInput.CSSLayers migration.

func (CSSLayerInput) Resolve

func (l CSSLayerInput) Resolve(index int) (CSSLayer, bool, error)

Resolve resolves the layer source into a concrete CSSLayer.

type CSSSupportDiagnostic

type CSSSupportDiagnostic = templateload.CSSSupportDiagnostic

CSSSupportDiagnostic describes a syntactically valid CSS declaration that the renderer intentionally ignores.

func AnalyzeCSSSupport

func AnalyzeCSSSupport(cssText string) ([]CSSSupportDiagnostic, error)

AnalyzeCSSSupport reports syntactically valid declarations outside the renderer's supported CSS subset.

type ConfinedFileResolver

type ConfinedFileResolver struct {
	Root string
}

ConfinedFileResolver resolves only regular files beneath Root. os.Root keeps symlink resolution and filesystem operations inside the configured root.

func (ConfinedFileResolver) ReadDir

func (r ConfinedFileResolver) ReadDir(ctx context.Context, name string) ([]fs.DirEntry, error)

func (ConfinedFileResolver) ReadFile

func (r ConfinedFileResolver) ReadFile(ctx context.Context, name string, maxBytes int64) ([]byte, error)

type DiagnosticCode

type DiagnosticCode string

DiagnosticCode is a stable machine-readable render failure category.

const (
	DiagnosticInvalidInput DiagnosticCode = "DF001"
	DiagnosticAsset        DiagnosticCode = "DF002"
	DiagnosticTemplate     DiagnosticCode = "DF003"
	DiagnosticLayout       DiagnosticCode = "DF004"
	DiagnosticOutput       DiagnosticCode = "DF005"
	DiagnosticCanceled     DiagnosticCode = "DF006"
	DiagnosticLimit        DiagnosticCode = "DF007"
)

type DiagnosticError

type DiagnosticError struct {
	Code    DiagnosticCode
	Stage   string
	Section string
	Layer   string
	Page    int
	Err     error
}

DiagnosticError adds stable provenance while preserving the original cause.

func (*DiagnosticError) Error

func (e *DiagnosticError) Error() string

func (*DiagnosticError) Unwrap

func (e *DiagnosticError) Unwrap() error

type Flow

type Flow struct {
	MainFlow   []Section `json:"mainFlow"`
	PageNumber Section   `json:"pageNumber"`
}

func (Flow) Validate

func (f Flow) Validate() error

type FontRegistration

type FontRegistration struct {
	Family  string
	Style   string
	Sources []string
}

FontRegistration declares one font family/style with ordered candidate file paths. The first existing path will be registered.

type FuncContext

type FuncContext struct {
	DefaultLocale       string
	PayloadLocale       string
	DefaultCurrencyCode string
	Now                 func() time.Time
}

FuncContext provides deterministic context to template function factories.

type FuncMapFactory

type FuncMapFactory func(defaultLocale, payloadLocale string) htmltmpl.FuncMap

FuncMapFactory is the legacy template function factory signature.

type FuncMapFactoryWithContext

type FuncMapFactoryWithContext func(ctx FuncContext) htmltmpl.FuncMap

FuncMapFactoryWithContext builds template functions using contextual runtime values including a clock hook.

type HTMLLayer

type HTMLLayer struct {
	Name     string
	HTML     string
	Optional bool
}

HTMLLayer is a resolved template layer. Layers are parsed in order and then legacy Assets.HTML is parsed last, allowing legacy HTML to override shared block defaults.

type HTMLLayerInput

type HTMLLayerInput struct {
	Name     string
	Source   TextSource
	Optional bool
}

func (HTMLLayerInput) Resolve

func (l HTMLLayerInput) Resolve(index int) (HTMLLayer, bool, error)

Resolve resolves the layer source into a concrete HTMLLayer.

type JSONSource

type JSONSource struct {
	Object   any
	Raw      []byte
	Text     string
	FilePath string
	FS       fs.FS
	FSPath   string
}

JSONSource resolves JSON payloads from a Go object, raw JSON bytes/string, a file path, or an io/fs path.

func (JSONSource) DecodeInto

func (s JSONSource) DecodeInto(target any, label string) error

func (JSONSource) IsSet

func (s JSONSource) IsSet() bool

type LimitError

type LimitError struct {
	Resource string
	Limit    int64
	Actual   int64
}

LimitError reports a configured resource budget violation.

func (*LimitError) Error

func (e *LimitError) Error() string

func (*LimitError) Is

func (e *LimitError) Is(target error) bool

type Logger

type Logger interface {
	Warnf(format string, args ...any)
}

Logger receives non-fatal render warnings.

type PageMargins

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

PageMargins defines default page margins in PDF points.

type PayloadConfig

type PayloadConfig struct {
	IncludeSource bool              `json:"includeSource"`
	Runtime       map[string]string `json:"runtime"`
	I18nVars      map[string]string `json:"i18nVars"`
	Static        map[string]any    `json:"static"`
	LocalePath    string            `json:"localePath"`
}

type RenderInput

type RenderInput struct {
	OutputPath string
	// AssetBaseDir is the profile directory. Automatic font discovery checks
	// fonts below this directory, then its parent and grandparent, in that order.
	AssetBaseDir             string
	EnableI18nTemplateMacros bool
	Assets                   Assets
	AssetInput               *AssetInput
	SourceData               any
	I18nSource               JSONSource
	FontRegistrations        []FontRegistration
	PageWidth                float64
	PageHeight               float64
	PageFormat               string
	PageOrientation          string
	DefaultLocale            string
	DefaultCurrencyCode      string
	DefaultMargins           PageMargins
	// Now supplies template time and, when non-nil, fixes PDF creation and
	// modification metadata for byte-reproducible rendering.
	Now              func() time.Time
	FuncMapFactoryEx FuncMapFactoryWithContext
	FuncMapFactory   FuncMapFactory
	Logger           Logger
	ResourceResolver ResourceResolver
	Limits           RenderLimits
	// AllowPartialRender preserves the legacy behavior of logging recoverable
	// template and element errors while emitting a potentially incomplete PDF.
	// Deprecated: use strict rendering, the default. Scheduled for removal in
	// v0.3.0.
	AllowPartialRender bool
	// Deprecated: use Logger. Scheduled for removal in v0.3.0.
	WarningWriter io.Writer
}

RenderInput contains all data and options needed to render a flow-driven PDF.

type RenderLimits

type RenderLimits struct {
	SourceBytes         int64
	TemplateOutputBytes int64
	ImageBytes          int64
	ImagePixels         int64
	OutputBytes         int64
	Nodes               int
	Depth               int
	Rows                int
	Pages               int
}

RenderLimits bounds resource use during one render. Zero values select the documented defaults; negative values are invalid.

func DefaultRenderLimits

func DefaultRenderLimits() RenderLimits

DefaultRenderLimits returns an independent copy of the default render budgets.

type RenderOption

type RenderOption func(*RenderInput) error

RenderOption customizes the default RenderInput used by Render.

func WithAssetBaseDir

func WithAssetBaseDir(path string) RenderOption

WithAssetBaseDir enables base-directory-driven defaults for assets, i18n, fonts, and images.

func WithAssetInput

func WithAssetInput(assetInput AssetInput) RenderOption

WithAssetInput sets flexible asset sources.

func WithAssets

func WithAssets(assets Assets) RenderOption

WithAssets sets fully resolved assets.

func WithConfinedResourceRoot

func WithConfinedResourceRoot(root string) RenderOption

WithConfinedResourceRoot confines base-directory defaults, images, fonts, and explicit relative file sources to root.

func WithDefaultCurrencyCode

func WithDefaultCurrencyCode(code string) RenderOption

WithDefaultCurrencyCode sets fallback currency code.

func WithDefaultLocale

func WithDefaultLocale(locale string) RenderOption

WithDefaultLocale sets fallback locale.

func WithDefaultMargins

func WithDefaultMargins(margins PageMargins) RenderOption

WithDefaultMargins overrides default page margins.

func WithFontRegistrations

func WithFontRegistrations(registrations ...FontRegistration) RenderOption

WithFontRegistrations sets explicit font registrations.

func WithFuncMapFactory

func WithFuncMapFactory(factory FuncMapFactory) RenderOption

WithFuncMapFactory sets legacy template function factory.

func WithFuncMapFactoryEx

func WithFuncMapFactoryEx(factory FuncMapFactoryWithContext) RenderOption

WithFuncMapFactoryEx sets context-aware template function factory.

func WithI18nSource

func WithI18nSource(source JSONSource) RenderOption

WithI18nSource sets explicit i18n source.

func WithI18nTemplateMacros

func WithI18nTemplateMacros(enabled bool) RenderOption

WithI18nTemplateMacros enables execution of template macros inside i18n translation values.

func WithLegacyPartialRendering

func WithLegacyPartialRendering(enabled bool) RenderOption

WithLegacyPartialRendering allows recoverable template and element failures to be logged while emitting a potentially incomplete PDF. Strict rendering is the default. Deprecated: use strict rendering, the default. Scheduled for removal in v0.3.0.

func WithLogger

func WithLogger(logger Logger) RenderOption

WithLogger sets non-fatal warning sink.

func WithNow

func WithNow(now func() time.Time) RenderOption

WithNow injects deterministic time source for template functions.

func WithPageFormat

func WithPageFormat(format string) RenderOption

WithPageFormat sets a named page format like A4, A3, A5, letter, or legal.

func WithPageHeight

func WithPageHeight(height float64) RenderOption

WithPageHeight overrides page height.

func WithPageMarginsLeftRight

func WithPageMarginsLeftRight(value float64) RenderOption

WithPageMarginsLeftRight sets both left and right default page margins.

func WithPageMarginsTopBottom

func WithPageMarginsTopBottom(value float64) RenderOption

WithPageMarginsTopBottom sets both top and bottom default page margins.

func WithPageOrientation

func WithPageOrientation(orientation string) RenderOption

WithPageOrientation sets page orientation (portrait or landscape).

func WithPageSize

func WithPageSize(width, height float64) RenderOption

WithPageSize overrides both page width and height.

func WithPageWidth

func WithPageWidth(width float64) RenderOption

WithPageWidth overrides page width.

func WithRenderLimits

func WithRenderLimits(limits RenderLimits) RenderOption

WithRenderLimits configures per-render operational budgets.

func WithSourceData

func WithSourceData(source any) RenderOption

WithSourceData overrides source data used for flow payload source context.

func WithTrustedFileAccess

func WithTrustedFileAccess() RenderOption

WithTrustedFileAccess explicitly enables unrestricted host-file resources.

func WithWarningWriter deprecated

func WithWarningWriter(w io.Writer) RenderOption

WithWarningWriter sets a plain-text warning sink.

Deprecated: use WithLogger. Scheduled for removal in v0.3.0.

type ResourceResolver

type ResourceResolver interface {
	ReadFile(ctx context.Context, name string, maxBytes int64) ([]byte, error)
	ReadDir(ctx context.Context, name string) ([]fs.DirEntry, error)
}

ResourceResolver controls filesystem access for render resources.

type Section

type Section struct {
	Template    string        `json:"template"`
	Transformer string        `json:"transformer"`
	Payload     PayloadConfig `json:"payload"`
}

func (Section) Validate

func (s Section) Validate() error

type TextSource

type TextSource struct {
	Raw      []byte
	Text     string
	FilePath string
	FS       fs.FS
	FSPath   string
}

TextSource resolves textual content from in-memory bytes/text, a file path, or an io/fs path.

func (TextSource) IsSet

func (s TextSource) IsSet() bool

func (TextSource) Resolve

func (s TextSource) Resolve(label string) (string, error)

type TrustedFileResolver

type TrustedFileResolver struct{}

TrustedFileResolver preserves unrestricted host-file access for trusted local authoring. It must not be used as a sandbox for tenant-controlled paths.

func (TrustedFileResolver) ReadDir

func (TrustedFileResolver) ReadDir(ctx context.Context, name string) ([]fs.DirEntry, error)

func (TrustedFileResolver) ReadFile

func (TrustedFileResolver) ReadFile(ctx context.Context, name string, maxBytes int64) ([]byte, error)

Directories

Path Synopsis
cmd
csspdf command
internal
format
Package format provides locale-aware formatting for numbers, currency, and dates.
Package format provides locale-aware formatting for numbers, currency, and dates.
i18n
Package i18n provides locale-aware translation lookups.
Package i18n provides locale-aware translation lookups.
limit
Package limit defines the shared marker for configured limit failures.
Package limit defines the shared marker for configured limit failures.
scripts
errorwrapcheck command

Jump to

Keyboard shortcuts

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