docflowpdf

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 30 Imported by: 0 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 docflowpdf 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)

Jump to

Keyboard shortcuts

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