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
- Variables
- func DefaultTemplateFuncMap(defaultLocale, payloadLocale string) htmltmpl.FuncMap
- func DefaultTemplateFuncMapWithContext(ctx FuncContext) htmltmpl.FuncMap
- func FormatLocalizedTime(t time.Time, locale, style string) string
- func Render(outputPath string, options ...RenderOption) error
- func RenderContext(ctx context.Context, outputPath string, options ...RenderOption) error
- func RenderToBytes(input RenderInput) ([]byte, error)
- func RenderToBytesContext(ctx context.Context, input RenderInput) ([]byte, error)
- func RenderToFile(input RenderInput, outputPath string) error
- func RenderToFileContext(ctx context.Context, input RenderInput, outputPath string) error
- func RenderToWriter(input RenderInput, out io.Writer) error
- func RenderToWriterContext(ctx context.Context, input RenderInput, out io.Writer) error
- func RenderWithInput(input RenderInput) error
- func RenderWithInputContext(ctx context.Context, input RenderInput) error
- func SupportedCSSProperties() []string
- type AssetInput
- type Assets
- type BudgetError
- type CSSLayer
- type CSSLayerInput
- type CSSSupportDiagnostic
- type ConfinedFileResolver
- type DiagnosticCode
- type DiagnosticError
- type Flow
- type FontRegistration
- type FuncContext
- type FuncMapFactory
- type FuncMapFactoryWithContext
- type HTMLLayer
- type HTMLLayerInput
- type JSONSource
- type LimitError
- type Logger
- type PageMargins
- type PayloadConfig
- type RenderInput
- type RenderLimits
- type RenderOption
- func WithAssetBaseDir(path string) RenderOption
- func WithAssetInput(assetInput AssetInput) RenderOption
- func WithAssets(assets Assets) RenderOption
- func WithConfinedResourceRoot(root string) RenderOption
- func WithDefaultCurrencyCode(code string) RenderOption
- func WithDefaultLocale(locale string) RenderOption
- func WithDefaultMargins(margins PageMargins) RenderOption
- func WithFontRegistrations(registrations ...FontRegistration) RenderOption
- func WithFuncMapFactory(factory FuncMapFactory) RenderOption
- func WithFuncMapFactoryEx(factory FuncMapFactoryWithContext) RenderOption
- func WithI18nSource(source JSONSource) RenderOption
- func WithI18nTemplateMacros(enabled bool) RenderOption
- func WithLegacyPartialRendering(enabled bool) RenderOption
- func WithLogger(logger Logger) RenderOption
- func WithNow(now func() time.Time) RenderOption
- func WithPageFormat(format string) RenderOption
- func WithPageHeight(height float64) RenderOption
- func WithPageMarginsLeftRight(value float64) RenderOption
- func WithPageMarginsTopBottom(value float64) RenderOption
- func WithPageOrientation(orientation string) RenderOption
- func WithPageSize(width, height float64) RenderOption
- func WithPageWidth(width float64) RenderOption
- func WithRenderLimits(limits RenderLimits) RenderOption
- func WithSourceData(source any) RenderOption
- func WithTrustedFileAccess() RenderOption
- func WithWarningWriter(w io.Writer) RenderOptiondeprecated
- type ResourceResolver
- type Section
- type TextSource
- type TrustedFileResolver
Constants ¶
const ( DefaultLocale = "en" DefaultCurrencyCode = "EUR" DefaultPageFormat = "A4" PageOrientationPortrait = "portrait" PageOrientationLandscape = "landscape" )
const UnsupportedCSSPropertyCode = templateload.UnsupportedCSSPropertyCode
Variables ¶
var ErrLimitExceeded = limitmarker.ErrExceeded
ErrLimitExceeded identifies failures caused by a configured resource or rendering limit.
Functions ¶
func DefaultTemplateFuncMap ¶
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 ¶
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 ¶
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 BudgetError ¶
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 ¶
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.
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.
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 FontRegistration ¶
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 ¶
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 ¶
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
}
type JSONSource ¶
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 ¶
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 PageMargins ¶
PageMargins defines default page margins in PDF points.
type PayloadConfig ¶
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"`
}
type TextSource ¶
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
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.
Source Files
¶
- api_asset_inputs.go
- api_css.go
- api_diagnostics.go
- api_limits.go
- api_migration.go
- api_options.go
- api_render.go
- api_render_file.go
- api_render_types.go
- api_resources.go
- api_sources.go
- api_template_funcs.go
- api_template_types.go
- api_types.go
- assets_base.go
- assets_flow_defaults.go
- assets_fonts.go
- assets_fonts_confined.go
- assets_fonts_layout.go
- assets_i18n.go
- assets_images.go
- assets_layers.go
- assets_render_order.go
- assets_resolve.go
- assets_source_decode.go
- assets_validation.go
- doc.go
- payload_clone.go
- payload_json.go
- payload_transform.go
- payload_validation.go
- profile_legacy.go
- render_context.go
- render_errors.go
- render_output_budget.go
- render_page_dimensions.go
- render_pipeline.go
- render_policy.go
- render_prepare.go
- template_aggregate.go
- template_currency.go
- template_date.go
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
|