PDF API

Piko renders PDF output from PK templates using a fluent builder. The render pipeline supports metadata, watermarks, PDF/A conformance, accessibility tagging via TaggedPDF(), and custom page labels. It also supports additional CSS stylesheets and font-size and line-height overrides. The pipeline also supports native SVG-to-PDF vector rendering and post-processing transformers for encryption and signing. For the design rationale see about PDF. For task recipes see how to PDF generation. Source of truth: wdk/pdf/facade.go.

Service

FunctionReturns
pdf.GetDefaultService() (Service, error)Returns the bootstrap-configured service.
pdf.NewRenderBuilder(service) (*RenderBuilder, error)Constructs a render builder bound to the given service.
pdf.NewRenderBuilderFromDefault() (*RenderBuilder, error)Shortcut for the default service.

Builder

The fluent RenderBuilder composes a single render operation. Chain setters, then call Do(ctx) to execute.

Method groupMethods
Template bindingTemplate(path), Request(r), Props(propsStruct)
Output structurePage(cfg PageConfig), PageLabels(ranges ...PageLabelRange), FontSize(size float64), LineHeight(height float64)
StylesheetsStylesheet(css string) (callable multiple times)
MetadataMetadata(meta Metadata), ViewerPreferences(prefs ViewerPreferences)
WatermarksWatermark(text string), WatermarkConfig(cfg WatermarkConfig)
CompliancePdfA(level PdfALevel), TaggedPDF()
SVG renderingSVGWriter(writer SVGWriterPort, data SVGDataPort)
Post-processingTransformations(registry *TransformerRegistry, config TransformConfig)
ExecutionDo(ctx) (*Result, error)

Watermark(text) is the convenience form using default styling (60pt, light grey, 45 degrees). Use WatermarkConfig for full control. PdfA(PdfA2A) enables tagged-PDF accessibility output automatically. The builder has no Fonts setter - the service configures fonts at construction time, not per render.

Types

TypePurpose
ServiceOrchestrates the render pipeline.
ResultRendered output. Fields: Content []byte (the PDF bytes), PageCount int (number of pages), and LayoutDump string (debug-only human-readable serialisation of the layout box tree, empty when not requested).
ConfigFull render configuration.
MetadataPDF info dictionary (title, author, subject, keywords, creator, producer, creation and modification dates).
ViewerPreferencesControls reader display flags (full-screen mode, hide-menubar, page layout).
WatermarkConfigBuilder-level watermark settings (text, opacity, rotation, placement) used by WatermarkConfig(cfg).
PdfAConfigBuilder-level PDF/A target level.
PdfALevelEnum (PdfA2B, PdfA2U, PdfA2A).
PageLabelRangeCustom labelling for a range of pages.
PageLabelStyleEnum (LabelDecimal, LabelRomanUpper, LabelRomanLower, LabelAlphaUpper, LabelAlphaLower, LabelNone).
PageConfigPage dimensions and margins (alias of layouter_dto.PageConfig).
FontEntryFont embedding descriptor used at service construction (alias of layouter_dto.FontEntry).
PainterConfigLow-level painter tuning.
SVGWriterPortRenders SVG markup as native PDF vector commands.
SVGDataPortProvides raw SVG markup for a given source.
TransformerRegistryHolds available PDF post-processing transformers.
TransformerPortInterface implemented by post-processing transformers.
TransformerTypeEnum of transformer categories.
TransformConfigSpecifies which post-processing transformers to apply.

Constants

GroupValues
PDF/A levelPdfA2B (basic), PdfA2U (Unicode), PdfA2A (accessible, auto-enables tagged PDF)
Page label styleLabelDecimal, LabelRomanUpper, LabelRomanLower, LabelAlphaUpper, LabelAlphaLower, LabelNone
Page sizePageA4, PageA3, PageLetter
Transformer typeTransformerContent, TransformerCompliance, TransformerDelivery, TransformerSecurity, TransformerCompression
Compression algorithmCompressZstd

Post-processing transformers

Transformers run after the initial render pass. Register them through a TransformerRegistry, then attach the registry to the builder via Transformations(registry, config). Each transformer has a paired option struct that tunes its behaviour.

ConstructorPurpose
NewEncryptTransformer(opts ...EncryptOption) TransformerPortAES-256 CBC encryption of the output PDF. Pass WithEncryptRandomSource(r) to override the cryptographic randomness source. Production callers can omit options.
NewPadesSignTransformer() TransformerPortPAdES digital signature.

Option structs

Transformer options live in pdfwriter_dto, and the wdk/pdf facade aliases them. The fields below match the source structs exactly.

EncryptionOptions

FieldTypePurpose
AlgorithmstringEncryption algorithm: "aes-256", "aes-128", or "rc4-128".
OwnerPasswordstringOwner (permissions) password.
UserPasswordstringUser (open) password.
Permissionsuint32PDF permission flags bitmask (PDF spec table 22). Use the bitmask form instead of separate booleans.

PadesSignOptions

FieldTypePurpose
PrivateKeycrypto.SignerSigning key.
LevelstringPAdES conformance level: "b-b", "b-t", "b-lt", or "b-lta".
TimestampURLstringTime Stamping Authority URL (required for "b-t" and above).
ReasonstringStated reason for signing.
LocationstringStated location of signing.
ContactInfostringContact information for the signer.
CertificateChain[][]byteSigning certificate chain in DER encoding, ordered from end-entity to root.
OCSPResponses[][]bytePre-fetched OCSP responses for long-term validation ("b-lt" and above).
CRLs[][]bytePre-fetched CRLs for long-term validation ("b-lt" and above).

WatermarkOptions

FieldTypePurpose
TextstringWatermark text. Empty when using image-only watermarks.
ImageData[]byteRaw image bytes for an image watermark. Nil for text-only watermarks.
Pages[]intPage indices the watermark applies to. Empty means all pages.
FontSizefloat64Font size in points for text watermarks.
ColourRfloat64Red channel in [0, 1].
ColourGfloat64Green channel in [0, 1].
ColourBfloat64Blue channel in [0, 1].
Anglefloat64Rotation angle in degrees.
Opacityfloat64Opacity in [0, 1].

PdfAOptions

FieldTypePurpose
LevelstringPDF/A conformance level. Allowed values: "1b", "2b", "3b".

The string Level is the transformer-side configuration. The builder's PdfA(level PdfALevel) setter takes the typed PdfALevel constants (PdfA2B, PdfA2U, PdfA2A) instead.

PdfUAOptions

Empty struct. The PDF/UA transformer takes no configuration. Passing it enables PDF/UA enhancement.

LineariseOptions

Empty struct. The linearisation transformer takes no configuration.

ObjStmOptions

Empty struct. The object-stream compression transformer takes no configuration.

FlattenOptions

FieldTypePurpose
FormFieldsboolFlatten interactive form fields into static content.
AnnotationsboolFlatten annotations into page content.
TransparencyboolFlatten transparency groups.

RedactionOptions

FieldTypePurpose
TextPatterns[]stringRegular expression patterns to match and redact.
Regions[]RedactionRegionPage-specific rectangular regions to redact.
StripMetadataboolStrip document metadata (author, title, etc.).

CompressOptions

FieldTypePurpose
AlgorithmCompressAlgorithmCompression algorithm. Defaults to CompressZstd when empty.

RedactionRegion

FieldTypePurpose
PageintZero-based page index.
Xfloat64Left edge in points.
Yfloat64Bottom edge in points.
Widthfloat64Width in points.
Heightfloat64Height in points.

Registry

func NewTransformerRegistry() *TransformerRegistry

*TransformerRegistry is an alias for *pdfwriter_domain.PdfTransformerRegistry. It exposes four methods:

MethodPurpose
Register(transformer TransformerPort) errorAdds a transformer. Returns an error when the transformer is nil, has an empty Name(), or another transformer already holds the same name.
Get(name string) (TransformerPort, error)Looks up a transformer by name. Returns an error wrapping ErrTransformerNotFound when no transformer holds that name.
Has(name string) boolReports whether the registry holds a transformer with the given name.
GetNames() []stringReturns all registered transformer names in alphabetical order.

Transformer interface

TransformerPort is the interface implementations satisfy:

type TransformerPort interface {
    Name() string
    Type() pdfwriter_dto.TransformerType
    Priority() int
    Transform(ctx context.Context, pdf []byte, options any) ([]byte, error)
}
MethodPurpose
Name()Unique identifier (for example "watermark", "aes-256", "pades-b-b", "linearise").
Type()Category used for grouping and chain validation.
Priority()Execution order. Lower values run first. Recommended ranges: 100-199 for content, 200-299 for compliance, 300-399 for delivery, 400-499 for security.
Transform(ctx, pdf, options)Apply the transformation. TransformConfig.TransformerOptions[Name()] provides the options argument.

TransformConfig is the bundle passed to the builder through Transformations(registry, config). It has two fields:

FieldTypePurpose
EnabledTransformers[]stringNames of transformers to apply. The chain sorts them by priority; this list is a declaration of intent, not an ordering directive.
TransformerOptionsmap[string]anyMaps transformer names to their option structs. Each transformer casts the entry to its expected concrete type.

pdfwriter_dto.DefaultTransformConfig() returns a TransformConfig with no transformers enabled and an empty options map.

Rendering SVG inside a PDF

SVGWriterPort renders SVG content as native PDF vector commands. SVGDataPort provides raw SVG markup. Users who need custom SVG-to-PDF conversion implement one of these ports and plug it into the painter configuration.

Bootstrap

PDF does not expose a dedicated With* option. Piko constructs the default service from the PDF manifest produced by the project's scaffolded generator (cmd/generator/main.go) when a pdfs/ directory is present in the project. Custom transformers register through the TransformerRegistry:

registry := pdf.NewTransformerRegistry()
if err := registry.Register(pdf.NewEncryptTransformer()); err != nil {
    return err
}
if err := registry.Register(pdf.NewPadesSignTransformer()); err != nil {
    return err
}

Attach the registry and selection config to the builder via Transformations(registry, config). The config is a TransformConfig describing which transformers to enable and their options.

See also