Documentation
¶
Overview ¶
Package pdf renders HTML documents to PDF using Chromium.
Package pdf renders HTML documents to PDF using Chromium.
Index ¶
- Constants
- func CheckChromiumAvailable() error
- func KillRunningBrowsers()
- func SetDocumentInfo(data []byte, meta DocumentMetadata, ts time.Time) ([]byte, error)
- func StripCoverHeaderFooter(data []byte) ([]byte, error)
- func WarnIfCJKFontsMissing(htmlContent string, logger interface{ ... })
- type Browser
- type DocumentMetadata
- type Generator
- type GeneratorOption
- func WithAssetRoot(dir string) GeneratorOption
- func WithBrowser(b *Browser) GeneratorOption
- func WithCoverPage(cover bool) GeneratorOption
- func WithDocumentOutline(enable bool) GeneratorOption
- func WithFooterTemplate(tmpl string) GeneratorOption
- func WithHeaderFooter(enable bool) GeneratorOption
- func WithHeaderTemplate(tmpl string) GeneratorOption
- func WithMarginStrings(left, right, top, bottom string) GeneratorOption
- func WithMargins(left, right, top, bottom float64) GeneratorOption
- func WithMetadata(m DocumentMetadata) GeneratorOption
- func WithPageSize(width, height float64) GeneratorOption
- func WithPrintBackground(print bool) GeneratorOption
- func WithTOCPageCache(enable bool) GeneratorOption
- func WithTaggedPDF(enable bool) GeneratorOption
- func WithTimeout(d time.Duration) GeneratorOption
- type PDFRenderer
Constants ¶
const AssetURLPrefix = "/__mdpress_assets/"
AssetURLPrefix is the URL path under which the PDF generator's local server exposes the files of the directory given to WithAssetRoot. A local image rewritten to AssetURLPrefix + "<path relative to that directory>" is loaded by Chrome straight from disk, instead of being base64-encoded into the document (4/3 the size, and once per reference).
const TOCPageCacheSubdir = "pdf-toc-pages"
TOCPageCacheSubdir is the directory under the mdpress cache root that holds remembered TOC page numbers. `mdpress cache clear` deletes it by this name.
Variables ¶
This section is empty.
Functions ¶
func CheckChromiumAvailable ¶
func CheckChromiumAvailable() error
CheckChromiumAvailable reports whether Chrome or Chromium is installed.
func KillRunningBrowsers ¶ added in v0.8.2
func KillRunningBrowsers()
KillRunningBrowsers SIGKILLs every Chrome process this package started and has not yet reaped. Call it immediately before os.Exit on a path that skips deferred cleanup; it is a no-op when no render is in flight.
func SetDocumentInfo ¶ added in v0.8.0
SetDocumentInfo rewrites the /Info dictionary of an in-memory PDF so it carries mdPress's document metadata and a deterministic timestamp.
The rewrite is done in place whenever the new dictionary fits inside the bytes the old one occupied — that keeps every cross-reference offset valid and, because the replaced bytes included Chrome's wall-clock timestamps, makes the output reproducible. When the new dictionary is larger the old object is emptied and a replacement is appended as a standard incremental update.
Any PDF this function cannot confidently parse is returned unchanged along with an error, so a failure degrades to "metadata not set" rather than a corrupt file.
func StripCoverHeaderFooter ¶ added in v0.8.2
StripCoverHeaderFooter removes the print header and footer Chrome drew on page one of data, which is only correct when page one is a cover.
The document is returned unchanged, with an error explaining why, whenever the running head cannot be identified beyond doubt.
func WarnIfCJKFontsMissing ¶ added in v0.3.1
WarnIfCJKFontsMissing checks whether the HTML content contains CJK characters and warns the user if no CJK fonts are installed on the system. This is a best-effort check — it logs a warning but does not block PDF generation.
Types ¶
type Browser ¶ added in v0.9.0
type Browser struct {
// contains filtered or unexported fields
}
Browser is a running headless Chrome that several Generate calls can share.
Starting Chrome costs about a second and a few hundred megabytes; a build that prints more than one PDF (one per language, or a PDF plus a print edition) otherwise pays that for every document. Start one Browser for the build, pass it to each Generator with WithBrowser, and Close it at the end:
b, err := pdf.StartBrowser(ctx, timeout)
if err != nil { ... }
defer b.Close()
g := pdf.NewGenerator(pdf.WithBrowser(b), ...)
err = g.Generate(ctx, html, out)
Each Generate opens its own tab, so calls may run concurrently. Canceling a Generate call's context closes only its tab; the browser lives until Close or until the context passed to StartBrowser is canceled.
func StartBrowser ¶ added in v0.9.0
StartBrowser launches Chrome and waits up to startTimeout for it to accept DevTools commands. Canceling ctx kills the browser.
func (*Browser) Close ¶ added in v0.9.0
func (b *Browser) Close()
Close shuts the browser down and removes its runtime directories. It is safe to call more than once.
func (*Browser) NewTab ¶ added in v0.10.0
func (b *Browser) NewTab(ctx context.Context, startTimeout time.Duration) (context.Context, func(), error)
NewTab opens a new tab in the browser for callers other than the PDF generator (the build-time Mermaid renderer). It waits at most startTimeout for the tab to be ready. Canceling ctx closes the tab, not the browser; so does calling the returned close function, which is safe to call more than once.
type DocumentMetadata ¶ added in v0.8.0
type DocumentMetadata struct {
Title string
Author string
Subject string
Keywords string
Creator string
}
DocumentMetadata is the document information mdPress records in a PDF's /Info dictionary. Empty fields are left out of the dictionary entirely.
func (DocumentMetadata) IsZero ¶ added in v0.8.0
func (m DocumentMetadata) IsZero() bool
IsZero reports whether no metadata field is set.
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator converts HTML into PDF files.
func NewGenerator ¶
func NewGenerator(opts ...GeneratorOption) *Generator
NewGenerator creates a PDF generator. By default, it generates a document outline (clickable bookmarks) and tagged PDF.
type GeneratorOption ¶
type GeneratorOption func(*Generator)
GeneratorOption customizes a PDF generator.
func WithAssetRoot ¶ added in v0.9.0
func WithAssetRoot(dir string) GeneratorOption
WithAssetRoot lets the document refer to local files under dir as AssetURLPrefix + "<relative path>" (see utils.ImageProcessingOptions. LocalURLPrefix). Only images, fonts and stylesheets are served, and never from outside dir.
func WithBrowser ¶ added in v0.9.0
func WithBrowser(b *Browser) GeneratorOption
WithBrowser makes the generator print in b instead of starting its own Chrome for every call. The caller owns b and must Close it.
func WithCoverPage ¶ added in v0.8.2
func WithCoverPage(cover bool) GeneratorOption
WithCoverPage declares that page one is a cover — artwork printed to the edge of the sheet — so the print header and footer are taken back off it after printing. Chrome draws them from the PrintToPDF parameters rather than from the page box, so nothing in the document can keep them off the cover; see StripCoverHeaderFooter.
func WithDocumentOutline ¶
func WithDocumentOutline(enable bool) GeneratorOption
WithDocumentOutline toggles PDF bookmark/outline generation from heading hierarchy. Enabled by default. Requires Chrome 128+ for full support.
func WithFooterTemplate ¶ added in v0.4.0
func WithFooterTemplate(tmpl string) GeneratorOption
WithFooterTemplate sets a custom HTML footer template for PDF pages. The template is rendered by Chrome's PrintToPDF and supports CSS styling. Chrome provides special classes: "pageNumber", "totalPages", "date", "title", "url".
func WithHeaderFooter ¶
func WithHeaderFooter(enable bool) GeneratorOption
WithHeaderFooter toggles header and footer rendering.
func WithHeaderTemplate ¶ added in v0.7.14
func WithHeaderTemplate(tmpl string) GeneratorOption
WithHeaderTemplate sets a custom HTML header template for PDF pages. The template is rendered by Chrome's PrintToPDF and supports CSS styling. Chrome provides special classes: "pageNumber", "totalPages", "date", "title", "url".
func WithMarginStrings ¶ added in v0.4.0
func WithMarginStrings(left, right, top, bottom string) GeneratorOption
WithMarginStrings sets page margins from string values (e.g., "20mm", "1in"). Uses default values if parsing fails.
func WithMargins ¶
func WithMargins(left, right, top, bottom float64) GeneratorOption
WithMargins sets page margins in millimeters.
func WithMetadata ¶ added in v0.8.0
func WithMetadata(m DocumentMetadata) GeneratorOption
WithMetadata sets the document information written into the PDF's /Info dictionary. Without it the PDF keeps whatever Chrome produced, which names headless Chrome as the creator and carries no author or subject.
func WithPageSize ¶
func WithPageSize(width, height float64) GeneratorOption
WithPageSize sets the page size in millimeters.
func WithPrintBackground ¶
func WithPrintBackground(print bool) GeneratorOption
WithPrintBackground toggles background printing.
func WithTOCPageCache ¶ added in v0.9.0
func WithTOCPageCache(enable bool) GeneratorOption
WithTOCPageCache enables or disables remembering the table of contents' page numbers between builds of the same output file, which lets an unchanged layout skip the second print pass. Enabled by default; it is also off whenever the mdpress cache is disabled.
func WithTaggedPDF ¶
func WithTaggedPDF(enable bool) GeneratorOption
WithTaggedPDF toggles tagged (accessible) PDF generation. Enabled by default. Tagged PDFs include structural metadata for screen readers.
func WithTimeout ¶
func WithTimeout(d time.Duration) GeneratorOption
WithTimeout sets the operation timeout.
type PDFRenderer ¶
type PDFRenderer interface {
Generate(ctx context.Context, htmlContent string, outputPath string) error
GenerateFromFile(ctx context.Context, htmlFilePath string, outputPath string) error
}
PDFRenderer abstracts PDF generation so tests can use a mock.
Both methods take a context because rendering a book-sized document keeps Chrome busy for minutes. Without one, Ctrl+C could not reach the render in progress: the CLI's signal handler canceled a context nothing in here was watching, so an interrupted build sat on a frozen progress line until Chrome had finished the whole book anyway.