AutoPDF

module
v2.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: Apache-2.0

README ΒΆ

πŸ“„ AutoPDF

AutoPDF Logo

A powerful tool that creates PDFs from LaTeX or Typst templates using Go's templating syntax with advanced features.

  • ⚑ Simple. Neat. Fast. Powerful. ⚑
  • Perfect for creating professional, customizable PDF documents
  • Leverages the most powerful PDF document generator, $\LaTeX$, or the fast modern one, Typst
  • Advanced templating with complex variables and for loops
  • Persistent CLI settings and configuration management
  • Built with DDD, SOLID principles, and GoF design patterns

Like, Share, Subscribe, and Hit the Bell Icon!

Please do mention the software usage in your projects, products, etc.

Built with ❀️ by BuddhiLW. Using Bonzai 🌳.

Showcase

AutoPDF Showcase

Install

go install github.com/BuddhiLW/AutoPDF/v2/cmd/autopdf@latest

Building on AutoPDF with Claude Code

AutoPDF ships skills that teach a coding agent how to integrate it, so a project adopting AutoPDF does not have to feed it documentation by hand:

/plugin marketplace add BuddhiLW/AutoPDF
/plugin install autopdf@autopdf
Skill Covers
autopdf Install, CLI, YAML config, choosing an integration path
autopdf-embed Go library: api.Engine, testing without LaTeX, logging, v1β†’v2
autopdf-templates delim[[ ]] syntax, nested values, loops, escaping
autopdf-preview Component documents, preview sessions, SSE/WebSocket/HTTP2
autopdf-plato Slides from Markdown/Org, Beamer, adding a render target

They load on demand, so a project that only generates PDFs never pays for the preview documentation. See skills/ to vendor them into a single project instead.

Features

πŸš€ Core Features
  • LaTeX and Typst PDF Generation: Professional document creation
  • Template Processing: Go template syntax with custom delimiters
  • YAML Configuration: Flexible and readable configuration
  • Multiple Backends: LaTeX (pdflatex, xelatex, lualatex) and Typst, selected per document
  • PDF Conversion: Convert PDFs to images (PNG, JPEG, etc.)
πŸ”§ Advanced Features
  • Complex Variables: Nested objects, arrays, and mixed data types
  • For Loops: Range loops over arrays and objects
  • Component Documents: Immutable semantic trees compiled into deterministic LaTeX fragments
  • Live Preview Pipeline: Revisioned, cancellable previews that send changed pages only
  • Persistent Settings: CLI settings that survive across sessions
  • Structured Logging: Detailed logging with zap integration
  • Configuration Management: Export/import configurations
πŸ—οΈ Architecture
  • Domain-Driven Design (DDD): Clear domain boundaries
  • SOLID Principles: Maintainable and extensible code
  • Backend Registry: Engines, template extensions and auxiliary files are declared once per backend; adding a backend is one registration, and every backend passes the same compiler contract suite
  • GoF Design Patterns: Factory, Builder, Strategy, Command
  • Clean Architecture: Separation of concerns
  • Test-Driven Development: Comprehensive test coverage

Usage

Basic Usage
# Simple document generation
autopdf build template.tex config.yaml

# With cleaning
autopdf build template.tex config.yaml clean

# With conversion
autopdf build template.tex config.yaml --convert png,jpeg
Advanced Usage
# Complex variables with nested structures
autopdf build advanced_document.tex complex_config.yaml

# For loops with dynamic content
autopdf build loops_document.tex loops_config.yaml

# Persistent settings
autopdf verbose 3
autopdf clean on
autopdf debug switch
Go Library

Use pkg/api.Engine when embedding AutoPDF. It provides a context-aware, concurrency-safe contract without requiring imports from AutoPDF internals.

engine, err := api.NewEngine()
if err != nil {
    return err
}

result, err := engine.Generate(ctx, api.Request{
    TemplatePath: "document.tex",
    OutputPath:   "output.pdf",
    Variables: map[string]string{
        "title": "Embedded AutoPDF",
    },
})
if err != nil {
    return err
}

fmt.Printf("generated %d bytes\n", len(result.PDF))

Custom renderers, caching layers, and test fakes can implement api.Generator and be installed with api.WithGenerator. See Embedding AutoPDF for extension, logging, cancellation, and migration guidance.

From Clojure

clients/clojure drives the autopdf binary through its command line, so nothing is rebuilt and no bindings are needed. One .cljc runs on JVM Clojure, ClojureWasm and clojurust, and each renders the same PDF:

(require '[autopdf.client :as autopdf])

(autopdf/build {:template "invoice.tex"
                :dir      "examples"
                :output   "invoice.pdf"
                :vars     {:number "2026-042"
                           :issuer "BuddhiLW"
                           :date   "2026-09-25"
                           :client {:name "ACME Ltd." :address "1 Main St."}
                           :items  [{:description "Consulting" :amount 1200}]
                           :total  1200}})
;; => {:ok {:pdf "examples/invoice.pdf"}}   or {:error {:exit n :err "..."}}

The render is planned as a value, then run through a ProgramRunner port, so tests hand in a stub and never need LaTeX.

Component documents and live previews

For structured editors, api.DocumentEngine turns a renderer-independent document.DocumentSpec into cached fragments and a deterministic LaTeX projection. Production generation still returns the existing api.Result, so adopters can add components without replacing their current PDF boundary.

Interactive sessions keep TeX auxiliary state warm, cancel superseded builds, use focused \\includeonly builds for section components, fingerprint rendered pages, and rasterize or transmit only changed pages. The optional HTTP adapter adds monotonic revisions and replayable events for browser clients over either server-sent events or WebSocket.

Streaming transports

The preview adapter serves one event feed through several wire formats, so a client picks the transport that suits it without changing replay semantics:

api, _ := rest.NewPreviewAPI(rest.PreviewAPIOptions{
    Engine:          engine,
    CompilerFactory: factory,
})

router := chi.NewRouter()
rest.RegisterPreviewRoutes(router, api)

// HTTP/2 over TLS and cleartext (h2c), with timeouts that do not
// truncate long-lived streams.
server, _ := rest.NewServer(rest.ServerOptions{Addr: ":8080", Handler: router})
server.ListenAndServe()
Route Transport
GET /sessions/{id}/events Server-sent events, Last-Event-ID replay
GET /sessions/{id}/ws WebSocket, ?after= replay

Both share the same cursor, history ring, and ordering. Revision submission is bounded per session and answers 429 when the queue is saturated, so a fast client receives backpressure instead of accumulating server-side work.

Presentations from Markdown or Org

A beamer render target compiles a DocumentSpec into a PDF deck. Pair it with plato, which parses Markdown and Org into that spec, and one source produces both a Reveal deck and a Beamer PDF:

plato spec talk.org -o talk.json
autopdf deck talk.json talk.pdf assets=./public theme=metropolis

Rebuilding on every save:

autopdf deck watch talk.json talk.pdf \
  watch=talk.org command="plato spec talk.org -o talk.json"

AutoPDF never parses the source itself β€” command is a shell hook, so any front end that emits a DocumentSpec works the same way. A render target supplies its own catalog and an api.ManifestProjector; adding one is a new package rather than a change to pkg/api.

Typst backend

Typst is a second document backend next to LaTeX. The same CLI, pkg/api.Engine, parallel strategy and preview sessions compile it; only the template language changes.

Selecting it. Set engine: typst in the config, or leave engine out and use a .typ template: an explicit engine wins, otherwise the template's extension picks the backend, otherwise LaTeX (pdflatex). In Go, set api.Request.Engine (LaTeXEngine is deprecated and read only when Engine is empty):

result, err := engine.Generate(ctx, api.Request{
    TemplatePath: "report.typ",
    OutputPath:   "report.pdf",
    Engine:       "typst", // optional: the .typ extension already selects typst
    Variables:    map[string]string{"title": "Typst Report"},
})

Config (test/model_typst/):

template: "./main.typ"
output: "./out/output"
engine: "typst"
variables:
  title: "AutoPDF Typst Report"
  author: "Ada #1 _Lovelace_ [draft]"
  items:
    - name: "Templates"
      note: "delim actions render; Typst brackets stay put"
autopdf build test/model_typst/main.typ test/model_typst/config.yaml

produces (out/output.pdf, page 1):

AutoPDF Typst example output

The escaped author (Ada #1 _Lovelace_ [draft]) prints literally, the range loop expands, and Typst's own #pill[a[b]] call passes through untouched. Run with debug to keep the staged output.autopdf.typ and see exactly what was handed to typst.

Template syntax. Templates are the same text/template with delim[[ ]] actions and strict rendering. Outside an action, text/template does not lex ]], so Typst's own [...] content blocks (#f[a[b]]) and # calls pass through untouched. Values are inserted as raw markup, so a value that may contain any of \ # $ * _ ` < > @ [ ] ~ = - + / should go through escapeTypst, which backslash-escapes each of them:

= delim[[ escapeTypst .title ]]

Author: delim[[ escapeTypst .author ]]

delim[[ range .items -]]
- *delim[[ escapeTypst .name ]]*: delim[[ escapeTypst .note ]]
delim[[ end ]]

What is refused. Typst compiles in one pass, so passes greater than 1 and use_latexmk: true are refused with a named error (UnsupportedSettingError) instead of being ignored. An engine name no backend accepts is refused with the list of known engines. Typst output goes through the same completeness gate as LaTeX: a PDF without its %%EOF trailer is never published.

Compile details. The rendered template is staged next to it as <job>.autopdf.typ and compiled with typst compile --root <template dir>, so the document can read assets (images, data, #imports) inside the template's directory and nothing outside it. The staged file is removed unless debug is on. Typst leaves no auxiliary files, so clean has nothing to remove for it.

Preview. preview.TypstCompiler compiles a workspace's main .typ file and rasterizes pages with typst itself (--format png --ppi, 144 by default), so no Poppler is needed; diagnostics carry file, line and column. rest.NewBackendPreviewCompilerFactory picks the LaTeX or Typst compiler per session, and POST /sessions accepts an optional {"backend", "engine", "template"} body.

Projection. Component documents can project to Typst through pkg/render/typst. pkg/render/backends.Default() registers the LaTeX and Typst projection backends; set DocumentEngineConfig.Backends to it and Backend: "typst". The text, section and artifact builtins have Typst projections; any other component is refused by name (UnsupportedComponentError) rather than dropped.

Toolchain. make typst downloads the pinned release (TYPST_VERSION, default 0.15.1, x86_64 Linux musl build) into ./bin, verifies its sha256 (TYPST_SHA256) and extracts bin/typst; add ./bin to PATH. Other ways to install it:

cargo install typst-cli --locked   # from source, any platform
brew install typst                 # macOS / Linuxbrew
pacman -S typst                    # Arch
winget install --id Typst.Typst    # Windows

The end-to-end test in test/model_typst builds the CLI and compiles the example when typst is on PATH, and skips with a message saying so when it is not.

Configuration Examples
Basic Configuration
template: "document.tex"
output: "output.pdf"
engine: "pdflatex"
variables:
  title: "My Document"
  author: "AutoPDF User"
  date: "2025-01-07"
Complex Variables
template: "advanced_document.tex"
output: "advanced_output.pdf"
engine: "pdflatex"
variables:
  title: "Advanced Document"
  metadata:
    version: "1.0.0"
    tags: ["example", "advanced", "complex"]
    settings:
      verbose: true
      debug: false
  items:
    - name: "Feature 1"
      enabled: true
      priority: 1
    - name: "Feature 2"
      enabled: false
      priority: 2
Template Syntax
Basic Variables
\title{delim[[.title]]}
\author{delim[[.author]]}
\date{delim[[.date]]}
Complex Variables
% Direct access to nested properties
Version: delim[[.metadata.version]]
Verbose: delim[[.metadata.settings.verbose]]

% Range loops over arrays
delim[[range .complex.metadata.tags]]
delim[[.]]\par
delim[[end]]

% Range loops over objects
delim[[range .complex.items]]
\subsection{delim[[.name]]}
Enabled: delim[[.enabled]]
Priority: delim[[.priority]]
delim[[end]]

Examples

πŸ“ Test Examples

The test/ directory contains comprehensive examples:

Basic Usage (test/basic_usage/)
  • Simple variable substitution
  • Basic YAML configuration
  • LaTeX document generation
Advanced Features (test/advanced_features/)
  • Complex nested variables
  • Range loops and dynamic content
  • Mixed data types and structures
For Loops (test/for_loops/)
  • Array iteration with range loops
  • Object property access in loops
  • Nested loop structures
Persistent Settings (test/persistent_settings/)
  • CLI settings management
  • Configuration persistence
  • Cross-session settings
Legacy Examples
  • test/model_letter/: Letter document example
  • test/model_xelatex/: XeLaTeX engine example
  • test/complex_variables/: Complex variable demonstration
Typst (test/model_typst/)
  • engine: typst with a .typ template
  • escapeTypst, range loops and Typst content blocks side by side
  • End-to-end test that skips when typst is not on PATH
πŸš€ Quick Start
  1. Install AutoPDF:

    go install github.com/BuddhiLW/AutoPDF/v2/cmd/autopdf@latest
    
  2. Try Basic Example:

    cd test/basic_usage
    autopdf build document.tex config.yaml
    
  3. Explore Advanced Features:

    cd test/advanced_features
    autopdf build advanced_document.tex config.yaml
    
  4. Test For Loops:

    cd test/for_loops
    autopdf build loops_document.tex config.yaml
    
  5. Try the Typst backend (needs typst on PATH; make typst fetches it into ./bin):

    cd test/model_typst
    autopdf build main.typ config.yaml
    
πŸ› οΈ CLI Commands
Build Commands
# Basic build
autopdf build TEMPLATE [CONFIG]

# With options
autopdf build TEMPLATE [CONFIG] [OPTIONS]
Setting Commands
# Verbose settings
autopdf verbose [LEVEL|on|off]

# Clean settings
autopdf clean [on|off|switch|status]

# Debug settings
autopdf debug [on|off|switch]

# Force settings
autopdf force [on|off|switch]
Utility Commands
# Clean auxiliary files (each backend's own list; Typst leaves none)
autopdf clean <path>

# Convert PDF to images
autopdf convert <pdf> <formats>

License

This project is licensed under the Apache License 2.0.

Directories ΒΆ

Path Synopsis
cmd
autopdf command
internal
autopdf
Package autopdf provides the Bonzai command branch of the same name.
Package autopdf provides the Bonzai command branch of the same name.
autopdf/application/adapters/compilation
Package compilation adapts the public generation engine to the domain's CompilationStrategy port, so parallel compilation dispatches through one abstraction rather than reaching for a concrete builder.
Package compilation adapts the public generation engine to the domain's CompilationStrategy port, so parallel compilation dispatches through one abstraction rather than reaching for a concrete builder.
autopdf/application/adapters/typst
Package typst is the Typst backend: a ports.DocumentCompiler that runs `typst compile` through the FileSystem and CommandExecutor ports.
Package typst is the Typst backend: a ports.DocumentCompiler that runs `typst compile` through the FileSystem and CommandExecutor ports.
autopdf/application/backend
Package backend is the single source of truth for the document backends AutoPDF can compile with: their engine names, template extensions, staged source suffix, auxiliary files and compiler factory.
Package backend is the single source of truth for the document backends AutoPDF can compile with: their engine names, template extensions, staged source suffix, auxiliary files and compiler factory.
autopdf/application/ports/compilertest
Package compilertest is the shared contract suite every ports.DocumentCompiler must pass.
Package compilertest is the shared contract suite every ports.DocumentCompiler must pass.
autopdf/commands/deck
Package deck builds a PDF presentation from a DocumentSpec.
Package deck builds a PDF presentation from a DocumentSpec.
pkg
api
Package api is the supported entry point for embedding AutoPDF in Go programs.
Package api is the supported entry point for embedding AutoPDF in Go programs.
api/model
Package model contains dependency-free value types shared by public API layers.
Package model contains dependency-free value types shared by public API layers.
component
Package component defines renderer-independent component definitions and an immutable catalog for kind, variant, and target multi-dispatch.
Package component defines renderer-independent component definitions and an immutable catalog for kind, variant, and target multi-dispatch.
composition
Package composition promotes DocumentSpecs into deterministic RenderManifests.
Package composition promotes DocumentSpecs into deterministic RenderManifests.
document
Package document defines AutoPDF's inert, versioned document model.
Package document defines AutoPDF's inert, versioned document model.
pdf
Package pdf holds the rules about PDF bytes.
Package pdf holds the rules about PDF bytes.
preview
Package preview manages persistent, revisioned compilation sessions for low-latency web previews.
Package preview manages persistent, revisioned compilation sessions for low-latency web previews.
render/backends
Package backends is the composition root for projection backends: the one place that names every concrete render target pkg/api can select by name.
Package backends is the composition root for projection backends: the one place that names every concrete render target pkg/api can select by name.
render/beamer
Package beamer registers a `beamer` rendering target for the component catalog and projects its manifests into a compilable Beamer document.
Package beamer registers a `beamer` rendering target for the component catalog and projects its manifests into a compilable Beamer document.
render/latex
Package latex deterministically projects a renderer-neutral composition manifest into a main LaTeX document and content-addressed fragment files.
Package latex deterministically projects a renderer-neutral composition manifest into a main LaTeX document and content-addressed fragment files.
render/typst
Package typst projects composed render manifests into a compilable Typst workspace: a main .typ file, one .typ file per fragment, and inert asset bindings an effectful collector materializes.
Package typst projects composed render manifests into a compilable Typst workspace: a main .typ file, one .typ file per fragment, and inert asset bindings an effectful collector materializes.
template/escape
Package escape holds the template helpers that make variable values safe as document markup.
Package escape holds the template helpers that make variable values safe as document markup.
template/strict
Package strict decides whether a template's variable reads are satisfied by the variables supplied to it.
Package strict decides whether a template's variable reads are satisfied by the variables supplied to it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL