Documentation
¶
Overview ¶
Package prettyconverter transforms MDX source files into print-ready PDFs via headless Chrome.
It is both a composable Go library and a CLI tool. The library exposes a pipeline with step-by-step methods (ParseDir, ValidateDoc, ComposeHTML, Render) and 18 functional options for full customization.
Quick start (library) ¶
pdf, err := prettyconverter.New(
prettyconverter.WithSourceDir("./docs"),
prettyconverter.WithOutputFile("output.pdf"),
prettyconverter.WithTitle("My Book"),
)
if err != nil {
log.Fatal(err)
}
if err := pdf.Build(context.Background()); err != nil {
log.Fatal(err)
}
Quick start (CLI) ¶
go install github.com/sazardev/go-pretty-converter/cmd/pretty-converter@latest pretty-converter build --source ./docs --out out.pdf
MDX files require frontmatter with an `id` field in [X.Y.Z] format (e.g. `[1.0.0]`). Documents are sorted by ID, not filename. Variables in {{key}} syntax are substituted before parsing.
Built-in custom components: <DeepDive>, <Warning>, <Axiom>. Additional components can be registered via WithComponent().
Trust model ¶
MDX is parsed with raw HTML passthrough enabled, and component transpilation does not escape inner content. Only build PDFs from MDX you trust — see SECURITY.md for details. Network access during rendering is blocked by default (see WithNetworkAccess).
Index ¶
- func ComposeHTML(docs []*mdx.Document, opts ComposeOptions) (string, error)
- type ComposeOptions
- type Option
- func WithAuthor(author string) Option
- func WithCSS(css string) Option
- func WithCalibreExecPath(path string) Option
- func WithChromeExecPath(path string) Option
- func WithComponent(name string, handler mdx.ComponentHandler) Option
- func WithConfig(cfg *config.Config) Option
- func WithConfigCSSAndTemplate(cfg *config.Config) Option
- func WithCoverImage(imagePath string) Option
- func WithEpubLanguage(lang string) Option
- func WithFormats(formats ...OutputFormat) Option
- func WithFullConfig(cfg *config.Config) Option
- func WithGenerateDocumentOutline(enabled bool) Option
- func WithGenerateTaggedPDF(enabled bool) Option
- func WithHeaderTitle(title string) Option
- func WithNetworkAccess(enabled bool) Option
- func WithOutputFile(path string) Option
- func WithPaperSize(width, height float64) Option
- func WithRenderMargins(top, bottom, left, right float64) Option
- func WithSharedBrowser(browserCtx context.Context) Option
- func WithSourceDir(dir string) Option
- func WithSubtitle(subtitle string) Option
- func WithTemplate(html string) Option
- func WithTheme(t theme.Theme) Option
- func WithThemeName(name string, opts theme.Options) Option
- func WithTimeout(d time.Duration) Option
- func WithTitle(title string) Option
- func WithValidator(v mdx.Validator) Option
- func WithVars(vars map[string]string) Option
- func WithVerbose(v bool) Option
- type OutputFormat
- type PDF
- func (p *PDF) Build(ctx context.Context) error
- func (p *PDF) ComposeHTML(docs []*mdx.Document) (string, error)
- func (p *PDF) Formats() []OutputFormat
- func (p *PDF) LastAudit() *render.AuditReport
- func (p *PDF) NeedsCalibre() bool
- func (p *PDF) NeedsChrome() bool
- func (p *PDF) ParseDir() ([]*mdx.Document, error)
- func (p *PDF) Render(html string) error
- func (p *PDF) RenderEpub(docs []*mdx.Document, outputPath string) error
- func (p *PDF) RenderKindle(ctx context.Context, docs []*mdx.Document, outputPath string) error
- func (p *PDF) RenderWithContext(ctx context.Context, html string) error
- func (p *PDF) Validate(ctx context.Context) ([]mdx.ValidationError, error)
- func (p *PDF) ValidateAll(docs []*mdx.Document) []mdx.ValidationError
- func (p *PDF) ValidateDoc(doc *mdx.Document) []mdx.ValidationError
- func (p *PDF) Warnings() []string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ComposeHTML ¶
func ComposeHTML(docs []*mdx.Document, opts ComposeOptions) (string, error)
Types ¶
type ComposeOptions ¶
func DefaultComposeOptions ¶
func DefaultComposeOptions() ComposeOptions
type Option ¶
type Option func(*PDF)
func WithAuthor ¶
func WithCalibreExecPath ¶
WithCalibreExecPath pins the FormatKindle pipeline to a specific Calibre ebook-convert executable instead of resolving one from PATH. Leave unset (or pass "") to resolve ebook-convert from PATH at build time — see the kindle package for the full resolution order.
func WithChromeExecPath ¶
WithChromeExecPath pins rendering to a specific Chrome/Chromium binary instead of chromedp's default system discovery. Leave unset (or pass "") to keep the default behavior. See the chromemgr package for resolving this automatically, including downloading a browser when none is installed.
func WithComponent ¶
func WithComponent(name string, handler mdx.ComponentHandler) Option
func WithConfig ¶
func WithConfigCSSAndTemplate ¶
WithConfigCSSAndTemplate resolves cfg.Theme (with cfg.ThemeOptions customization) and then loads CSS/template content from cfg.CSS/ cfg.Template, which — being explicit file overrides — take priority over the theme and replace its CSS/template outright. Read/resolve failures are recorded as warnings and flushed to stderr by New() once all options have been applied, so ordering relative to WithVerbose does not matter.
func WithCoverImage ¶
WithCoverImage replaces the theme's text cover with a full-bleed page built from imagePath (.png/.jpg/.jpeg). That cover page is sized to the image's own pixel dimensions exactly — a square image gets a square cover page — while every other page keeps its configured paper size. The theme's own text cover (title/subtitle/metadata) is suppressed regardless of theme/section settings and regardless of the order options are applied in — see New(), which enforces this once after every Option has run.
func WithEpubLanguage ¶
func WithFormats ¶
func WithFormats(formats ...OutputFormat) Option
func WithFullConfig ¶
WithFullConfig applies every field of cfg: source/output/title/subtitle /author (via WithConfig), CSS/template/theme (via WithConfigCSSAndTemplate), variable substitution (cfg.Vars), and render settings (cfg.Render: timeout, paper size, margins, header title). Unlike WithConfig and WithConfigCSSAndTemplate, which only cover a subset of Config, this is the single option needed to fully apply a loaded go-pretty-converter.yml.
func WithGenerateDocumentOutline ¶
WithGenerateDocumentOutline toggles whether PDF bookmarks/outline are built from the document's headings. Measured cost is near-zero even on very large documents (~50ms on a 3,000-doc/3,533-page book — see BENCHMARKS.md) — disabling it barely moves render time; it exists mainly for the (rare) case where in-PDF navigation bookmarks aren't wanted at all, not as a speed lever. For an actual speedup on large documents, see WithGenerateTaggedPDF or the CLI's --fast flag.
func WithGenerateTaggedPDF ¶
WithGenerateTaggedPDF toggles PDF accessibility tagging (PDF/UA). Tagging is real post-print work (~15-18% of render time on a 3,000-doc book — see BENCHMARKS.md), though page numbers/header cost even more; disable for a real speedup when accessibility metadata isn't needed.
func WithHeaderTitle ¶
WithHeaderTitle sets the PDF page header text. If never called, New() defaults it to the document title (WithTitle/composeOpts.Title).
func WithNetworkAccess ¶
WithNetworkAccess controls whether headless Chrome may make outbound network requests while rendering. It defaults to false: the composed HTML is a self-contained data URI, so network access is blocked to prevent SSRF/exfiltration from untrusted MDX content (e.g. a malicious <img> or <script> tag). Enable it only if your documents intentionally reference remote images, fonts, or other resources by URL.
func WithOutputFile ¶
func WithPaperSize ¶
func WithRenderMargins ¶
func WithSharedBrowser ¶
WithSharedBrowser makes subsequent Build calls render PDFs on the given Chrome allocator instead of booting a fresh Chrome process each time. The allocator must come from render.NewBrowser, stay alive across all Build calls, and be canceled by the caller once done. Each Build opens its own tab on the allocator, so concurrent Build calls share one Chrome process safely. This amortizes the per-launch Chrome startup cost across many renders — most useful when a process renders many documents (docsgen's per-theme PDFs, a batch job, a test harness).
func WithSourceDir ¶
func WithSubtitle ¶
func WithTemplate ¶
func WithTheme ¶
WithTheme applies a raw builtin/synthetic Theme's CSS as-is, with no customization (colors/fonts/sections/density) and no section toggles applied. It shares composeOpts.CSS with WithCSS and WithThemeName — whichever of these options is applied last wins, since New() applies options in the order they're passed. Most callers should prefer WithThemeName, which resolves section toggles (cover/TOC/page numbers/header) into composeOpts/renderOpts too.
func WithThemeName ¶
WithThemeName resolves a theme by name — a builtin ("default", "corporate", ...), a custom theme discovered in ./themes/ or the global themes directory, or a direct path to a .theme.yml/.css file — applies opts customization (colors, fonts, density, network fonts), and wires the resulting section toggles (cover, TOC, page numbers, header) into composeOpts/renderOpts. The theme is resolved through both the PDF and the EPUB pipelines, so a later EPUB build (Build with FormatEPUB or RenderEpub) carries the same theme, not the default stylesheet.
func WithTimeout ¶
func WithValidator ¶
func WithVerbose ¶
type OutputFormat ¶
type OutputFormat string
const ( FormatPDF OutputFormat = "pdf" FormatEPUB OutputFormat = "epub" FormatKindle OutputFormat = "kindle" )
func ParseFormats ¶
func ParseFormats(s string) ([]OutputFormat, error)
type PDF ¶
type PDF struct {
// contains filtered or unexported fields
}
func (*PDF) Formats ¶
func (p *PDF) Formats() []OutputFormat
func (*PDF) LastAudit ¶
func (p *PDF) LastAudit() *render.AuditReport
LastAudit returns the visual/structural audit report from the most recent Build or Render call, or nil if neither has run yet. See render.AuditReport and render/audit.go for what it checks.
func (*PDF) NeedsCalibre ¶
NeedsCalibre reports whether FormatKindle is among the configured formats, meaning Build will need Calibre's ebook-convert on PATH (or pinned via WithCalibreExecPath).
func (*PDF) NeedsChrome ¶
func (*PDF) RenderKindle ¶
RenderKindle converts docs into a Kindle-ready file at outputPath, reusing the same EPUB options (theme, metadata, cover) as RenderEpub but piping the result through Calibre's ebook-convert. See the kindle package for the conversion pipeline and Calibre resolution order.
func (*PDF) RenderWithContext ¶
RenderWithContext is Render with the browser rooted in ctx instead of context.Background(): canceling ctx (client disconnect, SIGINT wired to context cancellation) tears down the in-flight Chrome render rather than running to completion or to opts.Timeout regardless. opts.Timeout still applies as an upper bound layered on top of ctx.
func (*PDF) ValidateAll ¶
func (p *PDF) ValidateAll(docs []*mdx.Document) []mdx.ValidationError
func (*PDF) ValidateDoc ¶
func (p *PDF) ValidateDoc(doc *mdx.Document) []mdx.ValidationError
func (*PDF) Warnings ¶
Warnings returns the non-fatal configuration warnings recorded by New — e.g. an unresolvable theme name or an unreadable --css/--template file — each of which caused that option to fall back rather than apply. They are also printed to stderr by New itself; this accessor exists for callers that want to detect the condition programmatically instead.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package analyze statically inspects already-parsed MDX documents for content patterns that render poorly (or break outright) across the project's output formats — PDF, EPUB, and Kindle.
|
Package analyze statically inspects already-parsed MDX documents for content patterns that render poorly (or break outright) across the project's output formats — PDF, EPUB, and Kindle. |
|
Package chromemgr resolves a working Chrome/Chromium executable for headless rendering without requiring the user to install one by hand.
|
Package chromemgr resolves a working Chrome/Chromium executable for headless rendering without requiring the user to install one by hand. |
|
cmd
|
|
|
pretty-converter
command
|
|
|
Package epub converts parsed MDX documents into a single EPUB 3 file — no headless Chrome involved, unlike the PDF pipeline in render.
|
Package epub converts parsed MDX documents into a single EPUB 3 file — no headless Chrome involved, unlike the PDF pipeline in render. |
|
Package format converts raw, unstructured .txt files into clean, structured .mdx files (proper [X.Y.Z] frontmatter, Markdown headings, lists, and fenced code blocks) ready for the existing mdx/compose/build pipeline.
|
Package format converts raw, unstructured .txt files into clean, structured .mdx files (proper [X.Y.Z] frontmatter, Markdown headings, lists, and fenced code blocks) ready for the existing mdx/compose/build pipeline. |
|
Package kindle converts parsed MDX documents into a Kindle-ready ebook file (MOBI/AZW3).
|
Package kindle converts parsed MDX documents into a Kindle-ready ebook file (MOBI/AZW3). |
|
scripts
|
|
|
benchmark
command
Command benchmark runs an automated performance verification of go-pretty-converter across multiple book sizes.
|
Command benchmark runs an automated performance verification of go-pretty-converter across multiple book sizes. |
|
bump
command
|
|
|
docsgen
command
|
|
|
Package theme implements go-pretty-converter's theme engine: a set of professional built-in themes plus a customization layer (colors, fonts, section toggles, density) that composes on top of them via CSS custom properties, and a YAML format for user-defined custom themes.
|
Package theme implements go-pretty-converter's theme engine: a set of professional built-in themes plus a customization layer (colors, fonts, section toggles, density) that composes on top of them via CSS custom properties, and a YAML format for user-defined custom themes. |