Skip to content
scttfrdmnPublic

About

Markdown → typeset PDF in one static Go binary. No headless browser, no LaTeX, no CSS engine.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

inkcap — Markdown to typeset PDF. One static Go binary. No headless browser, no LaTeX, no CSS engine.

CI

inkcap

Markdown → typeset PDF. One static Go binary. No headless browser, no LaTeX, no CSS engine.

Coprinopsis atramentaria, the inkcap: a mushroom that deliquesces into black ink.

Two pages rendered by inkcap: a table of contents with dotted leaders and page numbers, page-anchored footnotes, a running header, and a table with a deliberately enormous cell, set at 1.5x line spacing.

testdata/gaps.md rendered with inkcap -toc gaps.md. The full PDF is example.pdf.

inkcap notes.md                    # -> notes.pdf
inkcap init                        # write ~/.inkcap/config.toml
inkcap -toc -style nord doc.md
inkcap doc.md -toc -o out.pdf      # flags may also follow the file
cat doc.md | inkcap - > doc.pdf    # - reads stdin; writes stdout unless -o
inkcap version                     # print version, Go version, platform

Install

# Homebrew (macOS / Linux) — Homebrew 7+ requires trusting third-party taps
brew tap scttfrdmn/tap && brew trust scttfrdmn/tap
brew install --cask inkcap

# Scoop (Windows)
scoop bucket add scttfrdmn https://github.com/scttfrdmn/scoop-bucket
scoop install inkcap

# Install script (macOS / Linux) — detects OS/arch, verifies the checksum
curl -fsSL https://raw.githubusercontent.com/scttfrdmn/inkcap/main/install.sh | sh

# Go
go install github.com/scttfrdmn/inkcap/cmd/inkcap@latest

# Docker
docker run --rm -v "$PWD":/work ghcr.io/scttfrdmn/inkcap notes.md

# Debian / Ubuntu (.deb) — latest release; use arm64 for ARM
curl -fsSLO https://github.com/scttfrdmn/inkcap/releases/latest/download/inkcap_linux_amd64.deb
sudo dpkg -i inkcap_linux_amd64.deb

# Fedora / RHEL (.rpm)
sudo rpm -i https://github.com/scttfrdmn/inkcap/releases/latest/download/inkcap_linux_amd64.rpm

# From source
go build -o inkcap ./cmd/inkcap

Prebuilt binaries, .deb/.rpm packages, and checksums are on the Releases page. The macOS binaries are Developer ID signed and notarized, so Gatekeeper runs them as downloaded.

Configuration

~/.inkcap/config.toml, created by inkcap init with every default written out and annotated. Override the location with -config or $INKCAP_CONFIG. Flags beat the file; the file beats the built-in defaults. A missing file is not an error. Unknown keys (usually typos) are reported as warnings; invalid values (a bad colour, an unknown paper size, a negative length) are errors that name the key.

Font sizes are in points (canvas' Face() wants points); every other length is in millimetres. Fonts default to embedded IBM Plex Serif/Mono; point [fonts.*] at .ttf files to override, per style, with a fallback to the embedded face for anything left blank.

[page]

Key Default Meaning
size "a4" a4 | letter | legal | a5
width, height — explicit mm; override size when both are set
margin_top 25 mm
margin_bottom 22 mm
margin_left 28 mm
margin_right 28 mm

[typography]

Key Default Meaning
body_size 10.5 body text, points
code_size 9 code blocks, points
small_size 8.5 footnotes, captions, folios, points
heading_sizes [20, 15.5, 13, 11.5, 10.5, 10] H1..H6, points
line_height 1.5 line spacing as a multiple of the font size, like CSS line-height (1–4)
justify true justify body text
orphans 2 min lines left at the foot of a page
widows 2 min lines carried to the next page
heading_rules 2 hairline under H1..Hn; 0 for none
smart_punctuation false curly quotes, -- → –, --- → —, ... → … in prose (never in code)

[spacing] — all millimetres

Key Default Meaning
paragraph 2.5 space after a paragraph
block 2.8 around code, tables, rules, figures
indent 7.0 per level of list / blockquote nesting
code_padding 2.5 inside the code-block box
heading_above [0, 5.6, 4.6, 3.9, 3.2, 3.2] H1..H6
heading_below [2.8, 2.1, 1.8, 1.4, 1.1, 1.1] H1..H6

[colors] — #rrggbb or #rrggbbaa

Key Default
fg #1a1a1e body text
muted #6b6f76 folios, captions, leaders
link #1a549e links
rule #d8dbe0 hairlines
code_bg #f6f7f9 code-block background
quote_bar #c7ccd4 blockquote bar
table_head_bg #f2f4f7 table header row
table_rule #c9ced6 table rules
note, tip, important, warning, caution GitHub's GitHub alert (> [!NOTE] …) bar and label

[code]

Key Default Meaning
style "github" any Chroma style: monokai, dracula, nord, tango, …
line_numbers false number lines in a gutter
tab_width 4 spaces per tab

[document]

Key Default Meaning
toc false generate a table of contents
toc_depth 3 deepest heading level listed
toc_title "Contents" TOC heading text
footnotes "page" page | end | none
page_numbers true print folios
page_total false render 3 / 12 instead of 3
running_header true document title in the header from page 2
h1_new_page false start each H1 after the first on a new page
number_sections false prefix headings with 1, 1.1, 1.1.1 …; anchors keep the unnumbered slug
number_from 1 first numbered level; 2 leaves an H1 title unnumbered
title_page false a cover page from front matter (title, subtitle, author, date, logo); unnumbered, with the TOC after it
math true $x^2$, $$…$$ and ```math as typeset formulas
html "strip" strip (keep text, drop tags) | drop (discard)
image_dpi 150 nominal resolution for figures; raise to shrink them on the page

[fonts.text] and [fonts.mono]

Key Meaning
regular, bold, italic, bold_italic paths to .ttf/.otf files; any left blank falls back to the embedded IBM Plex face ([fonts.mono] has no bold_italic)

[fonts]

Key Default Meaning
fallback [] font files consulted in order for any glyph the primary faces lack. The embedded faces cover Latin only; add e.g. a CJK or symbol font here. A glyph missing from every fallback is reported once on stderr.

Flags

Flags override the config file for a single run.

Flag Config equivalent
-o <file> output path, or - for stdout (default: input with .pdf; stdout when the input is -). Written atomically, and never over the input.
-title <s> document title (default: first H1)
-config <file> config location (also $INKCAP_CONFIG)
-paper <size> page.size
-style <name> code.style
-margin <mm> all four page.margin_*
-toc document.toc
-footnotes <mode> document.footnotes
-linenumbers code.line_numbers
-q suppress warnings on stderr

Why it isn't just AST → gofpdf

The usual pure-Go markdown-to-PDF tools walk the AST and emit boxes with a running y cursor. That's a renderer, not a layout engine, and it's why they produce tables that don't fit and headings stranded at the foot of a page.

markdown ──goldmark──▶ AST
                       │
                       ├─ build.go   AST → flat block flow  (nesting becomes
                       │              indent + decoration, not recursion)
                       ▼
                    []Item  { Block, Indent, Bars, Marker }
                       │
                       ├─ layout.go  paginate  → []Page   (pure)
                       │              draw      → PDF
                       ▼
              tdewolff/canvas ──▶ PDF   (shaping, kerning, subsetting,
                                         links, bookmarks)

Two decisions carry the whole design:

The document model is a single column with no floats. Blockquotes and list items are not recursive containers; they are a left inset plus a bar or a marker. The paginator therefore operates on a flat slice.

Pagination is a separate pass from drawing. A table of contents needs page numbers that only exist after pagination, and footnotes shrink the height of the page they land on. Neither is expressible in a draw-as-you-go loop. paginate is pure and returns []Page; draw consumes it.

canvas fork. inkcap builds against github.com/scttfrdmn/canvas, which is tdewolff/canvas at the commit inkcap pinned, with its module path renamed and one fix applied: tdewolff/canvas#397, a text shift after an unused soft hyphen or zero-width space. The fork is renamed rather than wired in with a replace directive so go install keeps working. inkcap goes back to upstream once #397 is merged.

The Block contract

type Block interface {
    Measure(w float64) float64
    Split(w, avail float64) (head, tail Block, ok bool)
    Draw(r *Rctx, x, y, w float64)

    SpaceBefore() float64
    SpaceAfter() float64
    KeepWithNext() bool
    Refs(reg map[*canvas.FontFace]int) []int   // footnotes carried
}

Split is where the typography lives. A block that doesn't want to be broken says so by returning (nil, self, true) — "put me on the next page".

Block Splits at Policy
Para line boundaries orphans ≥ 2, widows ≥ 2 (configurable), else move whole
Code source-line boundaries never mid-wrap, so numbering stays honest; ≥ 3 kept, ≥ 2 carried
Table body-row boundaries header repeats; a row taller than a page is broken inside, cell by cell
Heading never KeepWithNext: won't be left alone at the foot of a page; a run of headings moves as one
TocLine, Rule, Image never move whole

Because Split also splits a block's Refs, footnote placement follows paragraph splitting for free: the fragment that carries the marker is the fragment whose page reserves the space.

Paragraph splitting is the non-obvious trick. canvas does Knuth-Plass line breaking internally but doesn't expose the broken lines as a mutable structure — so extractLines reads them back out through Text.WalkLines, joinLines re-flattens any suffix into a run list, and fitLines binary-searches the largest prefix that fits (O(log n) relayouts, not O(n)). Table.splitRow reuses exactly this machinery to break an oversized row.

Table of contents

-toc. Built by a fixed-point iteration: paginate, read the heading pages, splice the TOC in, paginate again. The TOC's height doesn't depend on the numbers it contains, so the second pass is stable; TestTOCConverges asserts it settles and that every entry's number matches where the heading actually landed.

Math

GitHub-flavoured Markdown math, typeset by the pure-Go TeX engine inside the canvas library (so the binary stays static):

  • inline $x^2$ and $`x^2`$; display $$…$$ (in a paragraph or on lines of its own) and ```math blocks
  • the usual LaTeX/KaTeX commands: \frac, \sqrt, \sum, \int, \lim, Greek, \mathrm, \mathbf, \text, \operatorname, \left…\right, and the cases, matrix/pmatrix/bmatrix/vmatrix and aligned environments
  • dollar signs follow GitHub's rules: $5 and $10 stays text (no space just inside the delimiters, no digit right after the closing one)

The engine is plain TeX, so \mathbb is drawn bold (there's no blackboard-bold font) and packages beyond these mappings aren't available. A formula TeX can't set shows its source in code style, with a warning. document.math = false turns it off. Formulas use Computer Modern (Latin Modern), not the text font.

GitHub alerts

> [!NOTE], > [!TIP], > [!IMPORTANT], > [!WARNING] and > [!CAUTION] (the marker alone on the quote's first line, as on GitHub) render as a quote with a coloured bar and a bold label, in the [colors] for that type.

Page breaks

<!-- pagebreak --> (also page-break, newpage) on its own, or a paragraph that is just \newpage or \pagebreak, starts a new page. A break at the top of a page is ignored, so you never get blank pages. h1_new_page = true breaks before every H1 after the first.

Front matter

A leading YAML (--- … --- or ...) or TOML (+++ … +++) block is stripped from the output. title, author/authors, subject/description, keywords/tags and date are read from it; lists are joined with commas. title sets the PDF title and running header (-title still wins, then front matter, then the first heading), and author, subject and keywords go into the PDF's document properties. With title_page = true, title, subtitle, author, date and logo (an image path) make a cover page. Other keys are ignored. A document that merely opens with a --- rule followed by a blank line or prose is left alone.

Links

External links become URI annotations. Every heading also gets a GitHub-style anchor (## Getting Started → #getting-started, repeats get -1, -2…), so in-document links written for GitHub — [setup](#getting-started) — jump to the heading in the PDF, and every table-of-contents entry is a link to its heading. An explicit {#id} after a heading (## Install {#setup}) overrides the slug. A #name link with no matching heading is reported on stderr.

Footnotes

footnotes = "page" | "end" | "none". Page mode reserves the footnote area before deciding whether a block fits, so a paragraph is broken earlier on a page that has to carry three notes. Notes land on the page that references them; only if they would fill more than 60% of a page does the excess continue at the foot of the next page, in order, as in TeX.

Table column widths

CSS "auto" table layout: compute each column's minimum (longest unbreakable word) and maximum (all on one line) content width, then grow every column from its min toward its max in proportion to its slack. If even the minimums don't fit, distribute proportionally and overflow.

Code blocks

Chroma highlighting (style, any of its ~70 themes), optional line numbers in a gutter (line_numbers), configurable tab_width. Monospace means wrapping is by exact character count with a two-column hanging indent, so a long line breaks without reflowing away its indentation. Token faces are cached by chroma.StyleEntry, so a 2,000-line block allocates a handful of font faces.

Images

An image on its own line is a centred figure with an optional caption; an image mid-paragraph is inline, scaled to the surrounding text's cap height. Raster formats (PNG, JPEG, GIF) embed at image_dpi (default 150). SVG embeds as true vector — parsed by tdewolff/canvas, so it stays sharp at any zoom and image_dpi doesn't apply (the SVG carries its own size). A missing file or an SVG the parser can't handle falls back to the image's alt text, with a warning. Remote (http(s)://) images are not fetched, by design, so builds stay offline and reproducible; they show their alt text and say so. A linked image on its own line, [![alt](fig.png)](url), is a figure that links to url. The SVG parser is not a full SVG/CSS engine; exotic features (filters, some <text>, CSS gradients) may render partially.

HTML

html = "strip" (default) keeps the text and drops the tags; <br> becomes a line break. <img> is the one tag inkcap renders: a block holding only images (the centred README logo) shows each local one as a figure, captioned with its alt and sized by width (CSS pixels); a remote or missing one, or an <img> inside text, shows its alt text or an inline image. html = "drop" discards HTML blocks entirely. Either way, each distinct dropped tag is reported once on stderr — no more silent mangling.

Tests

go test ./... asserts the invariants that matter, and they are mutation-checked (break the code, watch them fail):

  • a heading, or a chain of headings, is never the last thing on a page
  • no paragraph fragment is shorter than the orphan/widow thresholds
  • nothing is laid out past the bottom margin, footnote area included
  • every footnote lands on the page that references it, or continues in order on later pages when there are too many to fit
  • a table repeats its header on every continuation
  • a row taller than a page terminates rather than looping
  • the TOC reaches a fixed point and its numbers are correct

Not supported, on purpose

Floats, multi-column, nested tables. This is a tool for developer docs and single-flow notes, not a replacement for a browser.

About

Markdown → typeset PDF in one static Go binary. No headless browser, no LaTeX, no CSS engine.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages