Documentation
¶
Overview ¶
Package document is the top-level API for building PDF files.
A Document coordinates page creation, layout-engine integration, font and image embedding, headers/footers, watermarks, bookmarks, named destinations, page labels, metadata, encryption, digital signatures, and standards compliance (PDF/A, PDF/UA).
Typical usage:
doc := document.NewDocument(document.PageSizeA4) doc.Add(paragraph) doc.WriteTo(writer)
For HTML-to-PDF conversion, use Document.AddHTML which delegates to the github.com/carlos7ags/folio/html converter and feeds the resulting layout elements into the document.
Package document provides the top-level API for creating and writing PDF documents.
Index ¶
- Variables
- type Annotation
- type DestType
- type Destination
- type Document
- func (d *Document) Add(e layout.Element)
- func (d *Document) AddAbsolute(e layout.Element, x, y, width float64)
- func (d *Document) AddAbsoluteOnPage(e layout.Element, x, y, width float64, pageIndex int)
- func (d *Document) AddAbsoluteRight(e layout.Element, rightOffset, y, width float64)
- func (d *Document) AddAbsoluteWithOpts(e layout.Element, x, y, width float64, opts layout.AbsoluteOpts)
- func (d *Document) AddConvertResult(result *foliohtml.ConvertResult) error
- func (d *Document) AddHTML(htmlStr string, opts *foliohtml.Options) error
- func (d *Document) AddHTMLTemplate(tmplStr string, data any, opts *foliohtml.Options) error
- func (d *Document) AddHTMLTemplateFuncs(tmplStr string, funcs template.FuncMap, data any, opts *foliohtml.Options) error
- func (d *Document) AddHTMLWithContext(ctx context.Context, htmlStr string, opts *foliohtml.Options) error
- func (d *Document) AddNamedDest(dest NamedDest)
- func (d *Document) AddOutline(title string, dest Destination) *Outline
- func (d *Document) AddPage() *Page
- func (d *Document) AttachFile(a FileAttachment)
- func (d *Document) Page(index int) (*Page, error)
- func (d *Document) PageCount() int
- func (d *Document) PageSize() PageSize
- func (d *Document) RemovePage(index int) error
- func (d *Document) Save(path string) error
- func (d *Document) SaveWithOptions(path string, opts WriteOptions) error
- func (d *Document) SetAcroForm(form interface{ ... })
- func (d *Document) SetActualText(enabled bool)
- func (d *Document) SetAutoBookmarks(enabled bool)
- func (d *Document) SetDebugMediaBox(color [3]float64, lineWidth float64)
- func (d *Document) SetEncryption(cfg EncryptionConfig)
- func (d *Document) SetFileID(id []byte)
- func (d *Document) SetFirstMarginBoxes(boxes map[string]layout.MarginBox)
- func (d *Document) SetFirstMargins(m layout.Margins)
- func (d *Document) SetFooter(fn PageDecorator)
- func (d *Document) SetFooterElement(fn ElementDecorator)
- func (d *Document) SetFooterText(text string, f *font.Standard, size float64, align layout.Align)
- func (d *Document) SetHeader(fn PageDecorator)
- func (d *Document) SetHeaderElement(fn ElementDecorator)
- func (d *Document) SetHeaderText(text string, f *font.Standard, size float64, align layout.Align)
- func (d *Document) SetLeftMarginBoxes(boxes map[string]layout.MarginBox)
- func (d *Document) SetLeftMargins(m layout.Margins)
- func (d *Document) SetMarginBoxes(boxes map[string]layout.MarginBox)
- func (d *Document) SetMargins(m layout.Margins)
- func (d *Document) SetPageLabels(ranges ...PageLabelRange)
- func (d *Document) SetPageSize(ps PageSize)
- func (d *Document) SetPdfA(config PdfAConfig)
- func (d *Document) SetRightMarginBoxes(boxes map[string]layout.MarginBox)
- func (d *Document) SetRightMargins(m layout.Margins)
- func (d *Document) SetTagged(enabled bool)
- func (d *Document) SetViewerPreferences(vp ViewerPreferences)
- func (d *Document) SetWatermark(text string)
- func (d *Document) SetWatermarkConfig(cfg WatermarkConfig)
- func (d *Document) ToBytes() ([]byte, error)
- func (d *Document) ToBytesWithOptions(opts WriteOptions) ([]byte, error)
- func (d *Document) ValidatePdfA() error
- func (d *Document) WriteTo(w io.Writer) (int64, error)
- func (d *Document) WriteToWithContext(ctx context.Context, w io.Writer, opts WriteOptions) (int64, error)
- func (d *Document) WriteToWithOptions(w io.Writer, opts WriteOptions) (int64, error)
- type ElementDecorator
- type EncryptionAlgorithm
- type EncryptionConfig
- type FileAttachment
- type ImportPageOpts
- type IndirectObject
- type Info
- type LabelStyle
- type MarkupType
- type NamedDest
- type Outline
- type Page
- func (p *Page) AddHighlight(rect [4]float64, color [3]float64, quadPoints [][8]float64)
- func (p *Page) AddImage(img *folioimage.Image, x, y, width, height float64)
- func (p *Page) AddInternalLink(rect [4]float64, destName string)
- func (p *Page) AddLine(x1, y1, x2, y2, width float64, color [3]float64)
- func (p *Page) AddLink(rect [4]float64, uri string)
- func (p *Page) AddPageLink(rect [4]float64, pageIndex int)
- func (p *Page) AddRect(x, y, w, h, strokeWidth float64, color [3]float64)
- func (p *Page) AddRectFilled(x, y, w, h float64, color [3]float64)
- func (p *Page) AddSquiggly(rect [4]float64, color [3]float64, quadPoints [][8]float64)
- func (p *Page) AddStrikeOut(rect [4]float64, color [3]float64, quadPoints [][8]float64)
- func (p *Page) AddText(text string, f *font.Standard, size, x, y float64)
- func (p *Page) AddTextAnnotation(rect [4]float64, text, icon string)
- func (p *Page) AddTextAnnotationOpen(rect [4]float64, text, icon string)
- func (p *Page) AddTextEmbedded(text string, ef *font.EmbeddedFont, size, x, y float64)
- func (p *Page) AddTextMarkup(markupType MarkupType, rect [4]float64, color [3]float64, ...)
- func (p *Page) AddUnderline(rect [4]float64, color [3]float64, quadPoints [][8]float64)
- func (p *Page) ContentStream() *content.Stream
- func (p *Page) ImportPage(contentStream []byte, resources *core.PdfDictionary, width, height float64)
- func (p *Page) ImportPageWithOpts(contentStream []byte, resources *core.PdfDictionary, width, height float64, ...)
- func (p *Page) SetArtBox(rect [4]float64) *Page
- func (p *Page) SetBleedBox(rect [4]float64) *Page
- func (p *Page) SetCropBox(rect [4]float64) *Page
- func (p *Page) SetDebugMediaBox(color [3]float64, lineWidth float64) *Page
- func (p *Page) SetOpacity(alpha float64) string
- func (p *Page) SetOpacityFillStroke(fillAlpha, strokeAlpha float64) string
- func (p *Page) SetRotate(degrees int)
- func (p *Page) SetSize(ps PageSize) *Page
- func (p *Page) SetTrimBox(rect [4]float64) *Page
- type PageContext
- type PageDecorator
- type PageLabelRange
- type PageLayout
- type PageMode
- type PageSize
- type PdfAConfig
- type PdfALevel
- type StructTag
- type ViewerPreferences
- type WatermarkConfig
- type WriteOptions
- type Writer
- func (w *Writer) AddObject(obj core.PdfObject) *core.PdfIndirectReference
- func (w *Writer) GenerateFileID() error
- func (w *Writer) SetEncryption(enc *core.Encryptor)
- func (w *Writer) SetFileID(id []byte)
- func (w *Writer) SetInfo(ref *core.PdfIndirectReference)
- func (w *Writer) SetRoot(ref *core.PdfIndirectReference)
- func (w *Writer) WriteTo(out io.Writer) (int64, error)
- func (w *Writer) WriteToWithOptions(out io.Writer, opts WriteOptions) (int64, error)
- type XMPProperty
- type XMPPropertyBlock
- type XMPSchema
- type XMPSchemaProperty
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ISO A series PageSizeA0 = PageSize{Width: 2383.94, Height: 3370.39} PageSizeA1 = PageSize{Width: 1683.78, Height: 2383.94} PageSizeA2 = PageSize{Width: 1190.55, Height: 1683.78} PageSizeA3 = PageSize{Width: 841.89, Height: 1190.55} PageSizeA4 = PageSize{Width: 595.28, Height: 841.89} PageSizeA5 = PageSize{Width: 419.53, Height: 595.28} PageSizeA6 = PageSize{Width: 297.64, Height: 419.53} // ISO B series PageSizeB4 = PageSize{Width: 708.66, Height: 1000.63} PageSizeB5 = PageSize{Width: 498.90, Height: 708.66} // North American sizes PageSizeLetter = PageSize{Width: 612, Height: 792} PageSizeLegal = PageSize{Width: 612, Height: 1008} PageSizeTabloid = PageSize{Width: 792, Height: 1224} PageSizeLedger = PageSize{Width: 1224, Height: 792} PageSizeExecutive = PageSize{Width: 522, Height: 756} )
Standard page sizes (dimensions in PDF points, 1 point = 1/72 inch).
Functions ¶
This section is empty.
Types ¶
type Annotation ¶
type Annotation struct {
// contains filtered or unexported fields
}
Annotation represents a PDF annotation on a page.
type DestType ¶
type DestType int
DestType is the type of PDF destination.
const ( // DestFit displays the page with its contents magnified just enough // to fit the entire page within the window (ISO 32000 §12.3.2.2). DestFit DestType = iota // DestXYZ positions the page at (left, top) with the given zoom. // Zero values mean "keep current" (ISO 32000 §12.3.2.2). DestXYZ )
type Destination ¶
type Destination struct {
PageIndex int // zero-based page index
Type DestType
Left float64 // for XYZ: left coordinate (0 = use current)
Top float64 // for XYZ: top coordinate (0 = use current)
Zoom float64 // for XYZ: zoom factor (0 = use current)
}
Destination describes where a bookmark links to.
func FitDest ¶
func FitDest(pageIndex int) Destination
FitDest creates a Fit destination for the given page index.
func XYZDest ¶
func XYZDest(pageIndex int, left, top, zoom float64) Destination
XYZDest creates an XYZ destination for the given page, position, and zoom. Pass 0 for left, top, or zoom to keep the current value.
type Document ¶
type Document struct {
Info Info // document metadata (Title, Author, etc.)
// contains filtered or unexported fields
}
Document is the top-level API for building a PDF.
Example (Simple) ¶
package main
import (
"fmt"
"os"
"github.com/carlos7ags/folio/document"
"github.com/carlos7ags/folio/font"
"github.com/carlos7ags/folio/layout"
)
func main() {
doc := document.NewDocument(document.PageSizeLetter)
doc.Info.Title = "Hello World"
doc.Info.Author = "Folio"
doc.Add(layout.NewHeading("Hello, Folio!", layout.H1))
doc.Add(layout.NewParagraph(
"This is a paragraph of text created with the Folio PDF library.",
font.Helvetica, 12,
))
if err := doc.Save("hello.pdf"); err != nil {
fmt.Println("error:", err)
return
}
_ = os.Remove("hello.pdf")
fmt.Println("Created hello.pdf")
}
Output: Created hello.pdf
Example (Table) ¶
package main
import (
"fmt"
"os"
"github.com/carlos7ags/folio/document"
"github.com/carlos7ags/folio/font"
"github.com/carlos7ags/folio/layout"
)
func main() {
doc := document.NewDocument(document.PageSizeA4)
doc.Info.Title = "Invoice"
doc.Add(layout.NewHeading("Invoice #1234", layout.H1))
tbl := layout.NewTable().SetAutoColumnWidths()
h := tbl.AddHeaderRow()
h.AddCell("Item", font.HelveticaBold, 10)
h.AddCell("Qty", font.HelveticaBold, 10)
h.AddCell("Price", font.HelveticaBold, 10)
r1 := tbl.AddRow()
r1.AddCell("Widget", font.Helvetica, 10)
r1.AddCell("5", font.Helvetica, 10)
r1.AddCell("$250.00", font.Helvetica, 10)
doc.Add(tbl)
_ = doc.Save("invoice.pdf")
_ = os.Remove("invoice.pdf")
fmt.Println("Created invoice")
}
Output: Created invoice
Example (TaggedPdfA) ¶
package main
import (
"fmt"
"os"
"github.com/carlos7ags/folio/document"
)
func main() {
doc := document.NewDocument(document.PageSizeLetter)
doc.Info.Title = "Accessible Report"
doc.Info.Author = "Folio"
doc.SetTagged(true)
doc.SetPdfA(document.PdfAConfig{Level: document.PdfA2B})
doc.AddPage() // blank page — PDF/A requires embedded fonts for text
_ = doc.Save("accessible.pdf")
_ = os.Remove("accessible.pdf")
fmt.Println("Created accessible PDF/A")
}
Output: Created accessible PDF/A
func NewDocument ¶
NewDocument creates a new PDF document with the given page size. /ActualText emission for shaped Arabic words is enabled by default; call SetActualText(false) on the returned document to opt out.
func (*Document) Add ¶
Add appends a layout element (e.g. Paragraph) to the document. Elements are laid out automatically with word wrapping and page breaks when WriteTo/Save is called.
func (*Document) AddAbsolute ¶
AddAbsolute places a layout element at fixed (x, y) coordinates on the last page produced by the layout engine. The element does not participate in normal vertical flow. Coordinates are in PDF points from the bottom-left. Width sets the layout width for word-wrapping; 0 uses full content width.
func (*Document) AddAbsoluteOnPage ¶
AddAbsoluteOnPage places a layout element at (x, y) on a specific layout page (0-indexed). If the page doesn't exist, the element is ignored.
func (*Document) AddAbsoluteRight ¶
AddAbsoluteRight places a layout element whose right edge is at (pageWidth - rightOffset) on the last page. The X coordinate is adjusted after layout to account for the element's actual width.
func (*Document) AddAbsoluteWithOpts ¶
func (d *Document) AddAbsoluteWithOpts(e layout.Element, x, y, width float64, opts layout.AbsoluteOpts)
AddAbsoluteWithOpts places an element with full positioning control.
func (*Document) AddConvertResult ¶ added in v0.9.1
func (d *Document) AddConvertResult(result *foliohtml.ConvertResult) error
AddConvertResult feeds a raw html.ConvertResult into the document: elements, absolutes, @page geometry/margins, margin boxes, and metadata (existing non-empty Info fields are kept). AddHTML is exactly ConvertFull followed by AddConvertResult; call this directly only to inspect or modify the result first. Adding result.Elements by hand instead drops result.Absolutes and the @page configuration.
func (*Document) AddHTML ¶
AddHTML parses an HTML string and adds the resulting layout elements to the document. It also extracts metadata from <title> and <meta> tags and applies them to the document's Info fields (Title, Author, Subject, Keywords, Creator). Existing non-empty Info fields are not overwritten.
If the HTML contains @page CSS rules, the page size and margins are applied to the document.
opts may be nil for default settings. It is equivalent to AddHTMLWithContext with a background context.
func (*Document) AddHTMLTemplate ¶ added in v0.6.0
AddHTMLTemplate executes a Go html/template with the given data and adds the resulting HTML to the document. This is a convenience for the common workflow of rendering a template with dynamic data to produce a PDF — e.g., invoices, reports, or letters.
The template string is parsed with html/template.New and executed with data. The result is passed to Document.AddHTML. Template functions, CSS <style> blocks, and all HTML features supported by [AddHTML] work as expected.
doc.AddHTMLTemplate(`
<h1>Invoice #{{.Number}}</h1>
<table>
{{range .Items}}
<tr><td>{{.Name}}</td><td>{{.Price}}</td></tr>
{{end}}
</table>
`, invoiceData, nil)
func (*Document) AddHTMLTemplateFuncs ¶ added in v0.6.0
func (d *Document) AddHTMLTemplateFuncs(tmplStr string, funcs template.FuncMap, data any, opts *foliohtml.Options) error
AddHTMLTemplateFuncs is like [AddHTMLTemplate] but accepts custom template functions via a template.FuncMap.
func (*Document) AddHTMLWithContext ¶ added in v0.9.0
func (d *Document) AddHTMLWithContext(ctx context.Context, htmlStr string, opts *foliohtml.Options) error
AddHTMLWithContext is the context-aware variant of AddHTML. It threads ctx through the HTML conversion, checking it at element boundaries during the tree walk and returning ctx.Err() if the context is done, so a runaway conversion can be bounded by a deadline.
func (*Document) AddNamedDest ¶
AddNamedDest registers a named destination within the document. Named destinations can be used as targets for internal links.
func (*Document) AddOutline ¶
func (d *Document) AddOutline(title string, dest Destination) *Outline
AddOutline adds a top-level bookmark to the document.
func (*Document) AttachFile ¶ added in v0.5.0
func (d *Document) AttachFile(a FileAttachment)
AttachFile schedules a file to be embedded in the document. The document must be configured with PDF/A-3B (PdfAConfig{Level: PdfA3B}); all other PDF/A levels forbid file attachments and will return an error on Save/WriteTo.
func (*Document) Page ¶
Page returns the page at the given zero-based index. Returns an error if the index is out of range.
func (*Document) PageSize ¶ added in v0.9.1
PageSize returns the current page dimensions, including any size derived from an @page rule.
func (*Document) RemovePage ¶
RemovePage removes the page at the given zero-based index. Returns an error if the index is out of range.
func (*Document) Save ¶
Save writes the document to a file at the given path using the historical default writer options.
func (*Document) SaveWithOptions ¶ added in v0.7.0
func (d *Document) SaveWithOptions(path string, opts WriteOptions) error
SaveWithOptions writes the document to a file at the given path, passing the supplied WriteOptions through to the writer.
The most common reason to use this entry point is to opt into the optimized output mode:
doc.SaveWithOptions("out.pdf", document.WriteOptions{
UseXRefStream: true,
UseObjectStreams: true,
})
func (*Document) SetAcroForm ¶
func (d *Document) SetAcroForm(form interface { Build(func(core.PdfObject) *core.PdfIndirectReference, []*core.PdfIndirectReference) (*core.PdfIndirectReference, map[int][]*core.PdfIndirectReference) })
SetAcroForm attaches an interactive form to the document. The form object must implement the Build method (typically *forms.AcroForm).
func (*Document) SetActualText ¶ added in v0.7.0
SetActualText controls whether the document wraps shaped Arabic words in ISO 32000-2 §14.9.4 /Span /ActualText marked-content sequences. When enabled (the default), copy/paste and accessibility consumers recover the original Unicode codepoints rather than the Arabic Presentation Forms-B substitutions emitted by the shaper. Disabling shaves a few dozen bytes per shaped Arabic word and is appropriate for size-sensitive documents that do not need text round-tripping.
func (*Document) SetAutoBookmarks ¶
SetAutoBookmarks enables automatic bookmark/outline generation from layout headings (H1-H6). When enabled, each Heading element in the document flow produces a bookmark entry. Headings are nested by level: H2 under H1, H3 under H2, etc.
func (*Document) SetDebugMediaBox ¶ added in v0.10.0
SetDebugMediaBox strokes a rectangle around every page's MediaBox for visual layout debugging. A page with its own Page.SetDebugMediaBox keeps that per-page setting instead. color is [R, G, B] in [0, 1]. Panics if lineWidth is negative.
func (*Document) SetEncryption ¶
func (d *Document) SetEncryption(cfg EncryptionConfig)
SetEncryption enables encryption on the document. The configuration specifies the algorithm, passwords, and permissions.
doc.SetEncryption(document.EncryptionConfig{
Algorithm: document.EncryptAES256,
UserPassword: "secret",
OwnerPassword: "admin",
Permissions: core.PermPrint | core.PermExtract,
})
func (*Document) SetFileID ¶ added in v0.9.0
SetFileID sets the file identifier written to the trailer /ID array (ISO 32000-1 §14.4). When set it overrides both the random identifier PDF/A output would otherwise generate and the content digest WriteOptions.Deterministic would derive, giving callers full control of the /ID for reproducible or externally-tracked output. A non-PDF/A document that would otherwise carry no /ID gains one. The identifier is conventionally 16 bytes; other lengths are written verbatim. Passing nil or an empty slice clears any previously set identifier.
func (*Document) SetFirstMarginBoxes ¶
SetFirstMarginBoxes sets margin box content for the first page only.
func (*Document) SetFirstMargins ¶
SetFirstMargins sets margins for the first page only (@page :first).
func (*Document) SetFooter ¶
func (d *Document) SetFooter(fn PageDecorator)
SetFooter sets a decorator that draws on every page (e.g. page numbers). The decorator runs after layout, so PageContext.TotalPages is accurate.
func (*Document) SetFooterElement ¶ added in v0.6.0
func (d *Document) SetFooterElement(fn ElementDecorator)
SetFooterElement sets an element-based footer that automatically reserves space at the bottom of each page.
doc.SetFooterElement(func(ctx document.PageContext) layout.Element {
text := fmt.Sprintf("Page %d of %d", ctx.PageIndex+1, ctx.TotalPages)
return layout.NewParagraph(text, font.Helvetica, 9).
SetAlign(layout.AlignCenter)
})
func (*Document) SetFooterText ¶ added in v0.6.0
SetFooterText is a convenience that sets a simple text footer on every page. See SetHeaderText for placeholder support.
func (*Document) SetHeader ¶
func (d *Document) SetHeader(fn PageDecorator)
SetHeader sets a decorator that draws on every page (e.g. title, logo). The decorator runs after layout, so PageContext.TotalPages is accurate.
func (*Document) SetHeaderElement ¶ added in v0.6.0
func (d *Document) SetHeaderElement(fn ElementDecorator)
SetHeaderElement sets an element-based header that automatically reserves space. The element is measured once to determine its height, and the top margin is increased accordingly so content never overlaps the header.
The decorator is called for each page with the page context. Return nil to skip a page. For per-page variation, use ctx.PageIndex.
doc.SetHeaderElement(func(ctx document.PageContext) layout.Element {
return layout.NewParagraph("My Report", font.HelveticaBold, 12)
})
func (*Document) SetHeaderText ¶ added in v0.6.0
SetHeaderText is a convenience that sets a simple text header on every page. The text is drawn with the given font, size, and alignment. The header automatically reserves space so content doesn't overlap.
The text may contain {page} and {pages} placeholders that are replaced with the current page number and total page count.
func (*Document) SetLeftMarginBoxes ¶ added in v0.9.1
SetLeftMarginBoxes sets margin box content for left (even-numbered) pages (@page :left).
func (*Document) SetLeftMargins ¶
SetLeftMargins sets margins for left (even) pages (@page :left).
func (*Document) SetMarginBoxes ¶
SetMarginBoxes sets default margin box content for all pages.
func (*Document) SetMargins ¶
SetMargins sets the page margins used by the layout engine (in PDF points). Default is 72pt (1 inch) on all sides.
func (*Document) SetPageLabels ¶
func (d *Document) SetPageLabels(ranges ...PageLabelRange)
SetPageLabels configures page label ranges for the document. Each range applies from its PageIndex until the next range starts.
Example — front matter in Roman numerals, body in decimal:
doc.SetPageLabels(
document.PageLabelRange{PageIndex: 0, Style: document.LabelRomanLower, Start: 1},
document.PageLabelRange{PageIndex: 4, Style: document.LabelDecimal, Start: 1},
)
func (*Document) SetPageSize ¶ added in v0.9.1
SetPageSize overrides the page dimensions set by NewDocument. AddHTML and AddConvertResult also set this from @page rules, so call it after them to force a size.
func (*Document) SetPdfA ¶
func (d *Document) SetPdfA(config PdfAConfig)
SetPdfA enables PDF/A conformance on the document. This enforces: font embedding, XMP metadata, output intent, and disables encryption. For level A, tagging is enabled automatically. Full validation (Title, fonts, transparency) happens at WriteTo time or via Document.ValidatePdfA.
func (*Document) SetRightMarginBoxes ¶ added in v0.9.1
SetRightMarginBoxes sets margin box content for right (odd-numbered) pages (@page :right).
func (*Document) SetRightMargins ¶
SetRightMargins sets margins for right (odd) pages (@page :right).
func (*Document) SetTagged ¶
SetTagged enables tagged PDF output (PDF/UA foundation). When enabled, the document includes a structure tree with semantic tags (P, H1-H6, Table, Figure, etc.) and marked content operators in the content streams. This enables screen readers, text extraction, and accessibility compliance (Section 508, EN 301 549).
func (*Document) SetViewerPreferences ¶
func (d *Document) SetViewerPreferences(vp ViewerPreferences)
SetViewerPreferences configures how viewers display the document.
func (*Document) SetWatermark ¶
SetWatermark sets a diagonal text watermark rendered behind content on every page. Uses default styling: 60pt light gray Helvetica at 45 degrees, 0.3 opacity.
func (*Document) SetWatermarkConfig ¶
func (d *Document) SetWatermarkConfig(cfg WatermarkConfig)
SetWatermarkConfig sets a watermark with full control over styling. Zero-value fields are replaced with defaults: FontSize=60, Color=(0.85,0.85,0.85), Angle=45, Opacity=0.3.
func (*Document) ToBytes ¶ added in v0.6.1
ToBytes serializes the complete PDF document and returns the raw bytes. This is a convenience wrapper around Document.WriteTo for use cases like HTTP responses, base64 encoding, or in-memory processing.
pdf, err := doc.ToBytes()
// serve as HTTP response:
w.Header().Set("Content-Type", "application/pdf")
w.Write(pdf)
func (*Document) ToBytesWithOptions ¶ added in v0.7.0
func (d *Document) ToBytesWithOptions(opts WriteOptions) ([]byte, error)
ToBytesWithOptions is the option-aware variant of Document.ToBytes.
func (*Document) ValidatePdfA ¶ added in v0.6.0
ValidatePdfA checks PDF/A requirements against the current document state. This can be called before WriteTo to catch issues early (missing Title, non-embedded fonts, forbidden transparency). Returns nil if PDF/A is not enabled or all checks pass.
func (*Document) WriteTo ¶
WriteTo serializes the complete PDF document to w using the historical default writer options.
func (*Document) WriteToWithContext ¶ added in v0.9.0
func (d *Document) WriteToWithContext(ctx context.Context, w io.Writer, opts WriteOptions) (int64, error)
WriteToWithContext is the context-aware variant of WriteToWithOptions. It checks ctx at page boundaries during layout and at object boundaries during serialization, returning ctx.Err() (context.Canceled or context.DeadlineExceeded) if the context is done. This lets callers bound a render with a real deadline rather than abandoning a goroutine that keeps working. On cancellation no bytes are guaranteed to have been written; treat the output as incomplete.
func (*Document) WriteToWithOptions ¶ added in v0.7.0
WriteToWithOptions serializes the complete PDF document to w, passing the supplied WriteOptions through to the underlying Writer. The zero value reproduces Document.WriteTo. It is equivalent to WriteToWithContext with a background context.
type ElementDecorator ¶ added in v0.6.0
type ElementDecorator func(ctx PageContext) layout.Element
ElementDecorator is a callback that returns a layout element for each page. Unlike PageDecorator (which draws at absolute coordinates and does not reserve space), ElementDecorator automatically measures the element's height and increases the corresponding margin (top for headers, bottom for footers) so content never overlaps the header/footer.
Use ElementDecorator (via SetHeaderElement/SetFooterElement) when you want the layout engine to account for the header/footer height. Use PageDecorator (via SetHeader/SetFooter) when you need full control over absolute positioning.
The returned element is laid out and rendered on each page. Return nil to skip a particular page.
type EncryptionAlgorithm ¶
type EncryptionAlgorithm int
EncryptionAlgorithm selects the encryption scheme.
const ( // EncryptRC4128 uses RC4 with a 128-bit key (PDF 1.4+, widely compatible). EncryptRC4128 EncryptionAlgorithm = iota // EncryptAES128 uses AES-128-CBC (PDF 1.6+, recommended minimum). EncryptAES128 // EncryptAES256 uses AES-256-CBC (PDF 2.0, strongest). EncryptAES256 )
type EncryptionConfig ¶
type EncryptionConfig struct {
Algorithm EncryptionAlgorithm
UserPassword string // password to open the document (may be empty)
OwnerPassword string // password for full access (defaults to UserPassword)
Permissions core.Permission // granted permissions when opened with user password
}
EncryptionConfig holds the settings for document encryption.
type FileAttachment ¶ added in v0.5.0
type FileAttachment struct {
// FileName is the name as it will appear in the PDF (e.g. "factur-x.xml").
// Used for both /F (ASCII) and /UF (Unicode) entries in the filespec dictionary.
FileName string
// MIMEType is the MIME type of the file (e.g. "application/xml").
// The '/' character will be encoded as '#2F' per PDF name syntax rules.
MIMEType string
// Description is an optional human-readable description of the file.
Description string
// AFRelationship is the PDF/A-3 association relationship key (ISO 19005-3 §6.4).
// Valid values: "Alternative", "Source", "Data", "Supplement", "Unspecified".
// Defaults to "Unspecified" if empty.
// Use "Alternative" for ZUGFeRD/Factur-X where the XML is the machine-readable
// equivalent of the PDF content.
AFRelationship string
// Data is the raw file content to embed.
Data []byte
// CreationDate is the file's creation timestamp. If zero, the document's
// Info.CreationDate is used; if that is also zero, the current time is used.
CreationDate time.Time
}
FileAttachment describes a file to be embedded in the PDF. PDF/A-3B is the only PDF/A level that permits file attachments (ISO 19005-3 §6.4).
type ImportPageOpts ¶ added in v0.5.2
type ImportPageOpts struct {
// X and Y position the imported page's lower-left corner.
// Default: (0, 0) — aligned with the target page origin.
X, Y float64
// ScaleX and ScaleY scale the imported page. Default: 1.0 (no scaling).
// Use equal values to preserve aspect ratio.
ScaleX, ScaleY float64
// Rotation rotates the imported page in degrees (counterclockwise).
// Common values: 0, 90, 180, 270.
Rotation float64
}
ImportPageOpts configures how an imported page is placed.
type IndirectObject ¶
IndirectObject pairs a PdfObject with its object/generation numbers for writing as an indirect object definition.
type Info ¶
type Info struct {
Title string
Author string
Subject string
Keywords string
Creator string // application that created the original content
Producer string // application that produced the PDF
CreationDate time.Time
ModDate time.Time
// Language is the default natural language of all text in the
// document, expressed as a BCP 47 / RFC 3066 language tag
// (e.g. "en-US", "es", "fr-CA"). When non-empty it is written
// to the document catalog as /Lang (ISO 32000-2 §14.9.2) and
// declared in the XMP dc:language property. PDF/A Level A
// (accessibility-conformance) requires this entry.
Language string
}
Info holds document metadata written to the PDF trailer's /Info dictionary (ISO 32000 §14.3.3).
type LabelStyle ¶
type LabelStyle string
LabelStyle specifies the numbering style for page labels.
const ( // LabelDecimal uses decimal numbering (1, 2, 3, ...). LabelDecimal LabelStyle = "D" // LabelRomanUpper uses uppercase Roman numerals (I, II, III, ...). LabelRomanUpper LabelStyle = "R" // LabelRomanLower uses lowercase Roman numerals (i, ii, iii, ...). LabelRomanLower LabelStyle = "r" // LabelAlphaUpper uses uppercase alphabetic labels (A, B, C, ...). LabelAlphaUpper LabelStyle = "A" // LabelAlphaLower uses lowercase alphabetic labels (a, b, c, ...). LabelAlphaLower LabelStyle = "a" // LabelNone disables numbering, showing only the prefix. LabelNone LabelStyle = "" )
type MarkupType ¶
type MarkupType int
MarkupType identifies the kind of text markup annotation.
const ( // MarkupHighlight represents a yellow highlight annotation. MarkupHighlight MarkupType = iota // MarkupUnderline represents a red underline annotation. MarkupUnderline // MarkupSquiggly represents a wavy underline annotation. MarkupSquiggly // MarkupStrikeOut represents a strikethrough annotation. MarkupStrikeOut )
type NamedDest ¶
type NamedDest struct {
Name string // destination name
PageIndex int // 0-based page index
// Fit type: "Fit" (fit page), "FitH" (fit width at y), "XYZ" (position + zoom)
FitType string
Top float64 // y position for FitH/XYZ
Left float64 // x position for XYZ
Zoom float64 // zoom level for XYZ (0 = unchanged)
}
NamedDest is a named destination within the document.
type Outline ¶
type Outline struct {
Title string
Dest Destination
Children []Outline
// Closed marks the entry's subtree as collapsed by default in PDF
// viewers. Encoded by buildOutlineTree as a negative /Count per
// ISO 32000 §12.3.3 — the absolute value still reflects the number
// of descendants, but the sign tells the viewer to start collapsed.
Closed bool
}
Outline represents a bookmark entry in the PDF outline tree. Outlines can be nested (children form sub-bookmarks).
type Page ¶
type Page struct {
// contains filtered or unexported fields
}
Page represents a single page in a document. It tracks font resources, image resources, and content stream operations.
func (*Page) AddHighlight ¶
AddHighlight adds a highlight annotation over a text region. rect defines the bounding box. color is [R, G, B] in [0, 1] (e.g. [1, 1, 0] for yellow). quadPoints defines the exact text regions as quadrilaterals — each quad is 8 floats: [x1,y1, x2,y2, x3,y3, x4,y4] (bottom-left origin, counterclockwise). If quadPoints is nil, a single quad matching rect is used.
func (*Page) AddImage ¶
func (p *Page) AddImage(img *folioimage.Image, x, y, width, height float64)
AddImage draws an image at (x, y) with the given width and height in PDF points. If width or height is 0, it is calculated from the other dimension preserving the aspect ratio. If both are 0, the image is placed at its natural size (1 pixel = 1 point). Panics if img is nil or width/height is negative.
func (*Page) AddInternalLink ¶
AddInternalLink adds a clickable link to a named destination within the document.
func (*Page) AddLine ¶ added in v0.5.2
AddLine draws a straight line from (x1, y1) to (x2, y2) with the given stroke width and RGB color. Coordinates are in PDF points with origin at bottom-left.
func (*Page) AddLink ¶
AddLink adds a clickable link annotation to the page. rect is [x1, y1, x2, y2] in PDF points (bottom-left origin). uri is the URL to open when clicked.
func (*Page) AddPageLink ¶
AddPageLink adds a clickable link to a specific page in the document (0-based index).
func (*Page) AddRect ¶ added in v0.5.2
AddRect draws a rectangle outline at (x, y) with the given width, height, stroke width, and RGB color. Use AddRectFilled for filled rectangles.
func (*Page) AddRectFilled ¶ added in v0.5.2
AddRectFilled draws a filled rectangle at (x, y) with the given width, height, and RGB fill color.
func (*Page) AddSquiggly ¶
AddSquiggly adds a squiggly underline annotation over a text region.
func (*Page) AddStrikeOut ¶
AddStrikeOut adds a strikeout annotation over a text region.
func (*Page) AddText ¶
AddText draws text at the given (x, y) position using a standard font. Coordinates are in PDF points with origin at bottom-left. Panics if f is nil or size is negative.
func (*Page) AddTextAnnotation ¶
AddTextAnnotation adds a sticky note (text annotation) at the given position. The note appears as an icon that reveals the text when clicked. rect is [x1, y1, x2, y2] defining the icon position. icon is one of: "Comment", "Note", "Help", "Insert", "Key", "NewParagraph", "Paragraph" (empty string defaults to "Note").
func (*Page) AddTextAnnotationOpen ¶
AddTextAnnotationOpen adds a sticky note that is initially open (popup visible).
func (*Page) AddTextEmbedded ¶
func (p *Page) AddTextEmbedded(text string, ef *font.EmbeddedFont, size, x, y float64)
AddTextEmbedded draws text at the given (x, y) position using an embedded font. The text is encoded as glyph IDs for CIDFont rendering. Panics if ef is nil or size is negative.
func (*Page) AddTextMarkup ¶
func (p *Page) AddTextMarkup(markupType MarkupType, rect [4]float64, color [3]float64, quadPoints [][8]float64)
AddTextMarkup adds a text markup annotation of the given type. This is a generic version of AddHighlight/AddUnderline/AddSquiggly/AddStrikeOut.
func (*Page) AddUnderline ¶
AddUnderline adds an underline annotation over a text region.
func (*Page) ContentStream ¶
ContentStream returns the raw content stream builder for advanced usage. Returns nil if no content has been added.
func (*Page) ImportPage ¶ added in v0.5.2
func (p *Page) ImportPage(contentStream []byte, resources *core.PdfDictionary, width, height float64)
ImportPage imports the content of an existing PDF page as a background. The source page is wrapped as a Form XObject and drawn behind any content added via AddText, AddImage, etc. The imported page's fonts, images, and other resources are included automatically.
This is used for template workflows: load a pre-designed PDF, add dynamic data on top, and save as a new document.
The pageData and pageResources parameters come from reader.PageInfo:
page, _ := r.Page(0) data, _ := page.ContentStream() res, _ := page.Resources() p.ImportPage(data, res, page.Width, page.Height)
func (*Page) ImportPageWithOpts ¶ added in v0.5.2
func (p *Page) ImportPageWithOpts(contentStream []byte, resources *core.PdfDictionary, width, height float64, opts *ImportPageOpts)
ImportPageWithOpts imports a page with explicit positioning, scaling, and rotation options. If opts is nil, the page is placed at the origin at its original size (same as ImportPage).
func (*Page) SetArtBox ¶
SetArtBox sets the meaningful content area of the page. Defaults to CropBox.
func (*Page) SetBleedBox ¶
SetBleedBox sets the bleed region for production (area to which page content should extend for trimming). Defaults to CropBox.
func (*Page) SetCropBox ¶
SetCropBox sets the visible region of the page. Content outside this box is clipped by the viewer. If not set, defaults to MediaBox. rect is [x1, y1, x2, y2] in PDF points.
func (*Page) SetDebugMediaBox ¶ added in v0.10.0
SetDebugMediaBox strokes a rectangle around this page's MediaBox — the exact page geometry PDF viewers use — for visual layout debugging. Overrides any document-wide SetDebugMediaBox for this page. color is [R, G, B] in [0, 1]. Panics if lineWidth is negative.
func (*Page) SetOpacity ¶
SetOpacity sets the fill and stroke opacity for subsequent drawing operations. alpha is in [0, 1] where 0 = fully transparent and 1 = fully opaque. Returns the ExtGState resource name (e.g. "GS1") so you can also call stream.SetExtGState(name) directly.
func (*Page) SetOpacityFillStroke ¶
SetOpacityFillStroke sets separate fill and stroke opacity. fillAlpha controls non-stroke operations (text fill, shape fill). strokeAlpha controls stroke operations (outlines, borders). Values are clamped to [0, 1]. NaN is treated as 1.0 (fully opaque).
func (*Page) SetRotate ¶
SetRotate sets the page rotation in degrees. Must be a multiple of 90. Common values: 0 (default), 90 (landscape), 180 (upside down), 270. Panics if degrees is not a multiple of 90.
func (*Page) SetSize ¶
SetSize overrides the page size for this page, allowing mixed page sizes within a document (e.g., a landscape insert in a portrait document). Pass a PageSize value; use standard sizes like PageSizeA4 or PageSizeLetter, or define a custom PageSize{Width, Height}.
func (*Page) SetTrimBox ¶
SetTrimBox sets the intended finished page dimensions after trimming. Defaults to CropBox. Important for print production.
type PageContext ¶
type PageContext struct {
PageIndex int // 0-based page index
TotalPages int // total number of pages in the document
}
PageContext provides page information to header/footer decorators.
type PageDecorator ¶
type PageDecorator func(ctx PageContext, page *Page)
PageDecorator is a callback that draws content on every page. It receives the page context and a Page to draw on. Decorators run after layout, so TotalPages is accurate.
type PageLabelRange ¶
type PageLabelRange struct {
PageIndex int // 0-based page index where this range starts
Style LabelStyle // numbering style
Prefix string // prefix before the number (e.g. "A-")
Start int // starting number (default 1)
}
PageLabelRange defines a page label range starting at a given page index. All pages from PageIndex until the next range use this label style.
type PageLayout ¶
type PageLayout string
PageLayout controls how pages are displayed when the document is opened.
const ( // LayoutSinglePage displays one page at a time. LayoutSinglePage PageLayout = "SinglePage" // LayoutOneColumn displays pages in a single continuous scrolling column. LayoutOneColumn PageLayout = "OneColumn" // LayoutTwoColumnLeft displays pages in two columns with odd pages on the left. LayoutTwoColumnLeft PageLayout = "TwoColumnLeft" // LayoutTwoColumnRight displays pages in two columns with odd pages on the right. LayoutTwoColumnRight PageLayout = "TwoColumnRight" // LayoutTwoPageLeft displays two pages at a time with odd pages on the left. LayoutTwoPageLeft PageLayout = "TwoPageLeft" // LayoutTwoPageRight displays two pages at a time with odd pages on the right. LayoutTwoPageRight PageLayout = "TwoPageRight" )
type PageMode ¶
type PageMode string
PageMode controls what panel is visible when the document is opened.
const ( // ModeNone shows no panel when the document is opened (default). ModeNone PageMode = "UseNone" // ModeOutlines shows the bookmarks panel when the document is opened. ModeOutlines PageMode = "UseOutlines" // ModeThumbs shows the page thumbnails panel when the document is opened. ModeThumbs PageMode = "UseThumbs" // ModeFullScreen opens the document in full-screen mode. ModeFullScreen PageMode = "FullScreen" // ModeOC shows the optional content panel when the document is opened. ModeOC PageMode = "UseOC" // ModeAttach shows the attachments panel when the document is opened. ModeAttach PageMode = "UseAttachments" )
type PdfAConfig ¶
type PdfAConfig struct {
Level PdfALevel
// ICCProfile is the ICC color profile data for the output intent.
// If nil, a minimal sRGB profile description is used.
ICCProfile []byte
// OutputCondition is the output condition identifier
// (e.g. "sRGB IEC61966-2.1"). Defaults to "sRGB IEC61966-2.1".
OutputCondition string
// XMPSchemas is an optional list of additional schema entries to declare
// inside the single pdfaExtension:schemas <rdf:Bag>. Each entry is injected
// as an <rdf:li rdf:parseType="Resource"> block alongside the built-in
// pdfaf schema entry. Use this to declare custom namespaces such as the
// Factur-X fx: schema required by ZUGFeRD validators.
// There must be exactly one pdfaExtension:schemas block in the XMP stream —
// this field merges into that block rather than adding a second one.
XMPSchemas []XMPSchema
// XMPProperties is an optional list of rdf:Description blocks carrying
// actual property values (e.g. fx:DocumentType, fx:Version). Each entry
// is injected verbatim as a separate rdf:Description inside rdf:RDF,
// after the pdfaExtension:schemas block. The Namespace and Prefix fields
// are used to build the xmlns attribute; Properties holds the values.
XMPProperties []XMPPropertyBlock
}
PdfAConfig holds PDF/A conformance settings.
type PdfALevel ¶
type PdfALevel int
PdfALevel specifies the PDF/A conformance level.
const ( // PdfA2B is PDF/A-2b (ISO 19005-2:2011, Level B). // Based on PDF 1.7. Allows transparency. Requires font embedding, // XMP metadata, and an output intent with ICC profile. PdfA2B PdfALevel = iota // PdfA2U is PDF/A-2u (Level U). Adds Unicode mapping requirement. PdfA2U // PdfA2A is PDF/A-2a (Level A). Adds structure tagging requirement. PdfA2A // PdfA3B is PDF/A-3b (ISO 19005-3:2012, Level B). Like A-2b but // allows associated file attachments (§6.4). PdfA3B // PdfA1B is PDF/A-1b (ISO 19005-1:2005, Level B). // Based on PDF 1.4. Forbids transparency. Requires font embedding, // XMP metadata, and an output intent with ICC profile. PdfA1B // PdfA1A is PDF/A-1a (Level A). Like 1b but adds structure tagging. PdfA1A // PdfA3A is PDF/A-3a (ISO 19005-3:2012, Level A). Adds structure // tagging on top of A-3b; inherits attachment support from part 3. PdfA3A // PdfA4 is PDF/A-4 (ISO 19005-4:2020). Based on PDF 2.0. Has no // conformance level letter; XMP carries pdfaid:rev = "2020" // (§6.5). Forbids embedded files unless the level is PdfA4F or // PdfA4E. PdfA4 // PdfA4F is PDF/A-4f (ISO 19005-4:2020). Like PdfA4 but permits // embedded files. Successor to PDF/A-3 for invoice/data carriers. PdfA4F // PdfA4E is PDF/A-4e (ISO 19005-4:2020). Engineering profile; // permits 3D, RichMedia, and embedded files. Successor to PDF/E-1. PdfA4E )
New PdfALevel constants must be appended to this block. The numeric values are part of the C ABI surface (see export/folio.h FOLIO_PDFA_*).
type StructTag ¶
type StructTag string
StructTag is a standard PDF structure type (ISO 32000 §14.8.4).
const ( // TagDocument is the root structure element for the entire document. TagDocument StructTag = "Document" // TagPart represents a large division of a document. TagPart StructTag = "Part" // TagSection represents a section within a document part. TagSection StructTag = "Sect" // TagH1 represents a level-1 heading. TagH1 StructTag = "H1" // TagH2 represents a level-2 heading. TagH2 StructTag = "H2" // TagH3 represents a level-3 heading. TagH3 StructTag = "H3" // TagH4 represents a level-4 heading. TagH4 StructTag = "H4" // TagH5 represents a level-5 heading. TagH5 StructTag = "H5" // TagH6 represents a level-6 heading. TagH6 StructTag = "H6" // TagP represents a paragraph. TagP StructTag = "P" // TagSpan represents an inline span of text. TagSpan StructTag = "Span" // TagTable represents a table. TagTable StructTag = "Table" // TagTR represents a table row. TagTR StructTag = "TR" // TagTH represents a table header cell. TagTH StructTag = "TH" // TagTD represents a table data cell. TagTD StructTag = "TD" // TagTHead represents a table header row group. TagTHead StructTag = "THead" // TagTBody represents a table body row group. TagTBody StructTag = "TBody" // TagL represents a list. TagL StructTag = "L" // TagLI represents a list item. TagLI StructTag = "LI" // TagLbl represents a list label (bullet or number). TagLbl StructTag = "Lbl" // TagLBody represents the body content of a list item. TagLBody StructTag = "LBody" // TagFigure represents an image or illustration. TagFigure StructTag = "Figure" // TagCaption represents a caption for a figure or table. TagCaption StructTag = "Caption" // TagLink represents a hyperlink. TagLink StructTag = "Link" // TagBlockQuote represents a block quotation. TagBlockQuote StructTag = "BlockQuote" // TagDiv represents a generic block-level grouping element. TagDiv StructTag = "Div" )
type ViewerPreferences ¶
type ViewerPreferences struct {
// How pages are arranged.
PageLayout PageLayout
// What panel is visible on open.
PageMode PageMode
// Hide viewer UI elements.
HideToolbar bool
HideMenubar bool
HideWindowUI bool
// Fit the window to the first page.
FitWindow bool
// Center the window on screen.
CenterWindow bool
// Display the document title (vs filename) in the title bar.
DisplayDocTitle bool
// Page to display on open (0-based). -1 = not set.
OpenPage int
// Zoom on open: "Fit", "FitH", "FitV", "FitB", or a percentage (e.g. 100).
// Empty string = viewer default.
OpenZoom string
}
ViewerPreferences controls how the PDF viewer displays the document.
type WatermarkConfig ¶
type WatermarkConfig struct {
Text string // the watermark text (required)
FontSize float64 // font size in points (default 60)
ColorR float64 // red component 0-1 (default 0.85)
ColorG float64 // green component 0-1 (default 0.85)
ColorB float64 // blue component 0-1 (default 0.85)
Angle float64 // rotation angle in degrees (default 45)
Opacity float64 // fill opacity 0-1 (default 0.3)
}
WatermarkConfig holds parameters for a diagonal text watermark rendered behind content on every page.
type WriteOptions ¶ added in v0.7.0
type WriteOptions struct {
// UseXRefStream replaces the traditional xref table and trailer with
// a cross-reference stream object (ISO 32000-1 §7.5.8). The stream
// dictionary carries the same /Root, /Info, /Encrypt, and /ID fields
// the trailer would have, with /Type /XRef and Flate-compressed
// entries. PDF readers from PDF 1.5 onward support this format.
UseXRefStream bool
// UseObjectStreams packs eligible indirect objects into compressed
// object streams (ISO 32000-1 §7.5.7). It implies UseXRefStream
// because compressed-object xref entries (type 2) require an xref
// stream to express. Phase 1 of the optimizer does not implement
// this option; setting it returns an error from WriteToWithOptions.
UseObjectStreams bool
// ObjectStreamCapacity caps the number of objects packed into a
// single /ObjStm. Zero means "use the writer default". Ignored
// unless UseObjectStreams is set.
ObjectStreamCapacity int
// OrphanSweep removes indirect objects unreachable from the
// document roots before serialization. The reachable set is
// computed by walking PdfIndirectReference values out of /Root,
// /Info, and /Encrypt (ISO 32000-1 §7.5.4 requires every "in use"
// xref entry to point at an object the document actually consumes;
// §7.7.2 names the document catalog as the reachability entry
// point). Surviving objects are renumbered contiguously starting
// at 1. The sweep is lossless: it never alters object content, only
// drops orphans and rewrites object numbers.
//
// Currently refused on encrypted documents because the per-object
// encryption key derives from the object number (§7.6.3.3); a safe
// interaction with the standard security handler has not yet been
// implemented.
OrphanSweep bool
// RecompressStreams re-Flate-compresses eligible stream payloads
// at zlib.BestCompression and commits the rewrite only when it
// produces a strictly smaller payload (size-regression guarded).
// Eligibility (per ISO 32000-1 §7.4):
//
// - Streams with no /Filter — payload is raw bytes; Flate is
// applied and /Filter /FlateDecode is set.
// - Streams whose /Filter is exactly /FlateDecode — payload is
// inflated, re-deflated at higher effort, and committed only
// on shrink. Useful when the original producer used a lower
// zlib level than BestCompression.
//
// Streams whose filter chain contains /DCTDecode (§7.4.8),
// /JPXDecode (§7.4.9), /CCITTFaxDecode (§7.4.7), or /JBIG2Decode
// (§7.4.8) are skipped — those payloads are already specialized-
// compressed and Flate would inflate them. Multi-filter chains
// other than the eligible cases above are also skipped. FlateDecode
// streams that carry a /DecodeParms entry (most commonly a PNG or
// TIFF predictor per §7.4.4.4) are skipped because the inflated
// payload is predictor-filtered bytes, not plaintext, and a safe
// re-deflate would require re-applying the predictor inversion.
//
// Currently refused on encrypted documents: rewriting payload
// bytes after the encryption walk would emit ciphertext that
// decrypts to the wrong plaintext, and rewriting before the
// walk requires the encryption code to revisit each rewritten
// stream — both deferred until needed.
//
// Lossless and safe to combine with UseXRefStream,
// UseObjectStreams, and OrphanSweep.
RecompressStreams bool
// DeduplicateObjects merges byte-identical indirect objects so the
// serialized output stores each unique payload exactly once. For
// every group of indirect objects whose canonical serialization
// (per ISO 32000-1 §7.3) produces the same bytes, the first slot
// is retained and every PdfIndirectReference targeting any of the
// other slots is rewritten to point at the survivor. Surviving
// objects are renumbered contiguously.
//
// The pass is most valuable on documents that re-use resources:
// imported pages sharing fonts or color spaces, repeated logos
// embedded as separate XObjects, identical ToUnicode CMaps
// (§9.10.3) across font dictionaries, and per-page content streams
// produced by templated workflows.
//
// Catalog, /Info, and /Encrypt indirect objects are excluded from
// dedup — they are reachability roots that the trailer slots refer
// to by pointer, and merging them would require relocating the
// trailer-side bookkeeping. They are unique in practice anyway.
//
// Currently refused on encrypted documents for the same reason as
// OrphanSweep: per-object encryption keys derive from the object
// number (§7.6.3.3) and renumbering after dedup would invalidate
// every key.
DeduplicateObjects bool
// CleanContentStreams removes redundant operators from page content
// streams (ISO 32000-1 §7.8): empty `q ... Q` graphics-state
// save/restore pairs that contain only whitespace, and identity
// `1 0 0 1 0 0 cm` matrix concatenations. The cleanup operates on
// the raw byte payload of each stream referenced from a Page
// dictionary's /Contents entry; the size-regression guard reverts
// any rewrite that fails to shrink.
//
// Currently refused on encrypted documents because rewriting
// payload bytes after the encryption walk would emit ciphertext
// that decrypts to the wrong plaintext.
CleanContentStreams bool
// Deterministic makes the writer produce byte-identical output for
// identical input documents. It derives the trailer /ID from a digest
// of the serialized object set instead of random bytes — matching the
// content-based file-identifier scheme ISO 32000-1 §14.4 describes —
// and routes every metadata timestamp that would otherwise default to
// the wall clock (XMP CreateDate/ModifyDate, embedded-file dates)
// through Document.Info.CreationDate, falling back to the zero time
// rather than time.Now when CreationDate is unset. Setting
// Document.Info.CreationDate (and ModDate) is therefore recommended so
// the recorded dates are meaningful rather than the year-zero default.
//
// An explicit Document.SetFileID overrides the derived /ID. A non-PDF/A
// document that would otherwise carry no /ID gains one. Encrypted
// documents are excluded: the standard security handler mints a random
// file identifier and derives the encryption key from it (§7.6.3.3), so
// their output is never byte-stable; the /ID is left to the handler.
Deterministic bool
// CompressionLevel selects the zlib level for streams the writer
// compresses at serialization time (zlib constants; e.g.
// zlib.BestSpeed). Zero value keeps the default, zlib.BestCompression.
// Does not affect RecompressStreams, which is BestCompression by
// definition. Determinism is preserved at any fixed level.
CompressionLevel int
}
WriteOptions controls optional behavior of the PDF writer. The zero value reproduces the historical default: a traditional cross-reference table (ISO 32000-1 §7.5.4) and a separate trailer dictionary (§7.5.5), with no object-stream packing.
Future fields will be added behind backward-compatible defaults; this struct is the single extension point for writer behavior.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer serializes a collection of indirect objects into a valid PDF file. It handles the PDF file structure: header, object definitions, cross-reference table, trailer, and EOF marker.
func (*Writer) AddObject ¶
func (w *Writer) AddObject(obj core.PdfObject) *core.PdfIndirectReference
AddObject registers an object to be written. Returns the indirect reference that can be used to refer to this object elsewhere.
func (*Writer) GenerateFileID ¶ added in v0.5.0
GenerateFileID creates a random 16-byte file identifier and sets it. Returns an error if the random source fails.
func (*Writer) SetEncryption ¶
SetEncryption configures encryption for the PDF output. The encrypt dictionary is added as an indirect object; its object number is recorded so the encryption walk skips it.
func (*Writer) SetFileID ¶ added in v0.5.0
SetFileID sets a 16-byte file identifier written to the trailer /ID array. PDF/A (all parts) requires /ID unconditionally (ISO 19005 §6.1.3). If not called, no /ID is written unless encryption is active.
func (*Writer) SetInfo ¶
func (w *Writer) SetInfo(ref *core.PdfIndirectReference)
SetInfo sets the document info reference for the trailer /Info entry.
func (*Writer) SetRoot ¶
func (w *Writer) SetRoot(ref *core.PdfIndirectReference)
SetRoot sets the document catalog reference for the trailer /Root entry.
func (*Writer) WriteTo ¶
WriteTo writes the complete PDF file to the given writer using the historical default options: a traditional cross-reference table (ISO 32000-1 §7.5.4) and a separate trailer dictionary (§7.5.5).
To opt into the optional cross-reference stream format (§7.5.8) or future writer behavior, use Writer.WriteToWithOptions.
func (*Writer) WriteToWithOptions ¶ added in v0.7.0
WriteToWithOptions is the option-aware variant of WriteTo. WriteTo is kept as a thin wrapper that calls this function with a zero-value options struct, so existing callers continue to receive the historical default output.
type XMPProperty ¶ added in v0.5.0
XMPProperty is a single name/value pair within an XMPPropertyBlock.
type XMPPropertyBlock ¶ added in v0.5.0
type XMPPropertyBlock struct {
// Namespace is the full namespace URI used in the xmlns attribute.
Namespace string
// Prefix is the XML namespace prefix used for the property elements.
Prefix string
// Properties is a list of (name, value) pairs to emit as child elements.
Properties []XMPProperty
}
XMPPropertyBlock carries actual XMP property values under a given namespace.
type XMPSchema ¶ added in v0.5.0
type XMPSchema struct {
// Schema is the human-readable schema name.
Schema string
// NamespaceURI is the full namespace URI (e.g. "urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#").
NamespaceURI string
// Prefix is the XML namespace prefix (e.g. "fx").
Prefix string
// Properties lists each property declared in this schema.
Properties []XMPSchemaProperty
}
XMPSchema describes one schema entry to add to the pdfaExtension:schemas bag.