@threepenny/md2pdf 2.2.3 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -14
- package/bin/md2pdf.js +75 -8
- package/lib/math.js +15 -8
- package/lib/render.js +24 -3
- package/lib/styles.js +4 -0
- package/package.json +2 -2
- package/styles/academic.css +18 -1
- package/styles/classic.css +18 -1
- package/styles/cyberpunk.css +710 -0
- package/styles/elvish.css +659 -0
- package/styles/fonts/chakra-petch/OFL.txt +93 -0
- package/styles/fonts/chakra-petch/chakra-petch-latin-400-italic.woff2 +0 -0
- package/styles/fonts/chakra-petch/chakra-petch-latin-400-normal.woff2 +0 -0
- package/styles/fonts/chakra-petch/chakra-petch-latin-700-italic.woff2 +0 -0
- package/styles/fonts/chakra-petch/chakra-petch-latin-700-normal.woff2 +0 -0
- package/styles/fonts/cormorant-garamond/OFL.txt +93 -0
- package/styles/fonts/cormorant-garamond/cormorant-garamond-latin-500-italic.woff2 +0 -0
- package/styles/fonts/cormorant-garamond/cormorant-garamond-latin-500-normal.woff2 +0 -0
- package/styles/fonts/cormorant-garamond/cormorant-garamond-latin-700-italic.woff2 +0 -0
- package/styles/fonts/cormorant-garamond/cormorant-garamond-latin-700-normal.woff2 +0 -0
- package/styles/fonts/cormorant-unicase/OFL.txt +93 -0
- package/styles/fonts/cormorant-unicase/cormorant-unicase-latin-600-normal.woff2 +0 -0
- package/styles/fonts/grenze-gotisch/OFL.txt +93 -0
- package/styles/fonts/grenze-gotisch/grenze-gotisch-latin-600-normal.woff2 +0 -0
- package/styles/fonts/im-fell-english/OFL.txt +93 -0
- package/styles/fonts/im-fell-english/im-fell-english-latin-400-italic.woff2 +0 -0
- package/styles/fonts/im-fell-english/im-fell-english-latin-400-normal.woff2 +0 -0
- package/styles/fonts/jetbrains-mono/OFL.txt +93 -0
- package/styles/fonts/jetbrains-mono/jetbrains-mono-latin-400-italic.woff2 +0 -0
- package/styles/fonts/jetbrains-mono/jetbrains-mono-latin-400-normal.woff2 +0 -0
- package/styles/fonts/jetbrains-mono/jetbrains-mono-latin-700-normal.woff2 +0 -0
- package/styles/fonts/michroma/OFL.txt +93 -0
- package/styles/fonts/michroma/michroma-latin-400-normal.woff2 +0 -0
- package/styles/fonts/space-mono/OFL.txt +93 -0
- package/styles/fonts/space-mono/space-mono-latin-400-italic.woff2 +0 -0
- package/styles/fonts/space-mono/space-mono-latin-400-normal.woff2 +0 -0
- package/styles/fonts/space-mono/space-mono-latin-700-normal.woff2 +0 -0
- package/styles/fonts/spectral/OFL.txt +93 -0
- package/styles/fonts/spectral/spectral-latin-400-italic.woff2 +0 -0
- package/styles/fonts/spectral/spectral-latin-400-normal.woff2 +0 -0
- package/styles/fonts/spectral/spectral-latin-600-italic.woff2 +0 -0
- package/styles/fonts/spectral/spectral-latin-600-normal.woff2 +0 -0
- package/styles/github.css +30 -0
- package/styles/gothic.css +503 -0
- package/styles/modern.css +18 -1
- package/styles/print/academic.css +9 -0
- package/styles/print/classic.css +9 -0
- package/styles/print/cyberpunk.css +101 -0
- package/styles/print/elvish.css +78 -0
- package/styles/print/github.css +9 -0
- package/styles/print/gothic.css +38 -0
- package/styles/print/modern.css +9 -0
- package/styles/print/report.css +9 -0
- package/styles/print/resume.css +9 -0
- package/styles/print/sandwake.css +56 -0
- package/styles/print/worksheet.css +9 -0
- package/styles/report.css +18 -1
- package/styles/resume.css +18 -1
- package/styles/sandwake.css +556 -0
- package/styles/worksheet.css +18 -1
package/README.md
CHANGED
|
@@ -6,11 +6,11 @@ Convert Markdown to beautifully styled PDFs. This is the rendering engine and ma
|
|
|
6
6
|
- **On a Mac and comfortable with a terminal?** Install the command-line tool below. It adds a Finder right-click action and a keyboard shortcut.
|
|
7
7
|
- **Building something?** Use the renderer and styles as a dependency, to make PDFs ([Using the renderer](#using-the-renderer)) or to show Markdown in your own pages ([Embedding in a web page](#embedding-in-a-web-page)).
|
|
8
8
|
|
|
9
|
-
Supports GitHub-flavored Markdown: tables, task lists, footnotes, emoji shortcodes, syntax-highlighted code, raw HTML, GitHub alerts and Obsidian callouts (`> [!NOTE]`, `> [!tip] Custom title`), Obsidian wikilinks and embeds (`[[Note|alias]]` prints as plain text, `![[image.png]]` as an image, and an embedded note as a placeholder naming it), YAML front matter (a leading `---` block of `key: value` properties, left out of the PDF; its `title:` names the document when there is no `#` heading. A leading `---` block of ordinary Markdown prints as Markdown after a divider), and page breaks (`<div class="page-break"></div>`).
|
|
9
|
+
Supports GitHub-flavored Markdown: tables, task lists, footnotes, emoji shortcodes, syntax-highlighted code, raw HTML, GitHub alerts and Obsidian callouts (`> [!NOTE]`, `> [!tip] Custom title`), Obsidian wikilinks and embeds (`[[Note|alias]]` prints as plain text, `![[image.png]]` as an image, and an embedded note as a placeholder naming it), YAML front matter (a leading `---` block of `key: value` properties, left out of the PDF; its `title:` names the document when there is no `#` heading. A leading `---` block of ordinary Markdown prints as Markdown after a divider), and page breaks (`<div class="page-break"></div>`). Eleven print styles are included: `github`, `classic`, `academic`, `modern`, `report`, `resume`, `worksheet`, `gothic`, `sandwake`, `elvish` and `cyberpunk`.
|
|
10
10
|
|
|
11
11
|
# Command-line tool (macOS)
|
|
12
12
|
|
|
13
|
-
Markdown is rendered to HTML with [markdown-it](https://github.com/markdown-it/markdown-it) and printed to PDF by headless Chrome.
|
|
13
|
+
Markdown is rendered to HTML with [markdown-it](https://github.com/markdown-it/markdown-it) and printed to PDF by headless Chrome. Formulas (`$…$`, `$$…$$`, `\(…\)`, `\[…\]`, and environments such as `\begin{aligned}…\end{aligned}` or `\begin{align*}…\end{align*}` that start a block) are drawn with [KaTeX](https://katex.org), as on md2pdf.me; the HTML that `--html` writes also carries MathML for screen readers, which the PDF doesn't. Prices such as $5 and $10 stay text, even beside a formula.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
@@ -26,7 +26,7 @@ This installs:
|
|
|
26
26
|
- **Convert to PDF** Quick Action — right-click any `.md` file in Finder → **Quick Actions → Convert to PDF**
|
|
27
27
|
- **⌃⌥⌘P** keyboard shortcut — select `.md` files in Finder and press it
|
|
28
28
|
|
|
29
|
-
Re-run `install.sh` if you move this folder
|
|
29
|
+
Re-run `install.sh` if you move this folder, remove the Node version it was installed with, or pull a version that adds a dependency (md2pdf says so when KaTeX, which draws formulas, is missing). `./uninstall.sh` removes all of it.
|
|
30
30
|
|
|
31
31
|
To use a different shortcut, pass it when installing (`@` ⌘, `~` ⌥, `^` ⌃, `$` ⇧), or set it to empty to skip:
|
|
32
32
|
|
|
@@ -63,6 +63,10 @@ From Finder, a single file opens in Preview when done; multiple files show a not
|
|
|
63
63
|
| `report` | Business or technical report: title block from the first heading, running header with the title, "Page N of M" footers, gridded tables |
|
|
64
64
|
| `resume` | Compact and one-page friendly: the first heading is your name, the paragraph after it your contact line, `##` headings are ruled section dividers |
|
|
65
65
|
| `worksheet` | For worksheets, stories and class handouts: Andika body text and rounded Fredoka headings (both bundled), larger type, bright headings that change color each section, outlined rounded boxes and big tick boxes for task lists |
|
|
66
|
+
| `gothic` | An old book of dread: blackletter Grenze Gotisch headings and IM Fell English body text (both bundled), oxblood red titles, main headings, bold text and table rules, a drop cap after the title, leaf ornaments for rules, page numbers between dashes |
|
|
67
|
+
| `sandwake` | A space-opera codex: wide Michroma capitals for titles and sections, Spectral text and Space Mono labels (all bundled), rust section numbers and drop cap, later titles numbered as books ("Liber II"), a setting-sun rule, outlined code and callouts, a running title and folio numbers |
|
|
68
|
+
| `elvish` | A quiet manuscript from under the trees: Cormorant Unicase titles and sections and Cormorant Garamond text (both bundled) at a larger size, a gold star between leafed sprigs above the title, leaves for bullets and beside `##` headings, a drop cap after each `#` heading, verse-like quotes between stars, double-ruled callouts, italic Roman numerals for lists and page numbers |
|
|
69
|
+
| `cyberpunk` | A job file leaked off somebody's terminal: squared Chakra Petch text and JetBrains Mono labels (both bundled), teal and hot magenta on white, the title in a gridded panel with corner brackets and a cyan and magenta offset, numbered sections ("01 //"), `###` headings as terminal prompts, intercept boxes for quotes, pale terminal panels for code, boxed two-digit list numbers, a running title and page numbers out of the total |
|
|
66
70
|
|
|
67
71
|
Switch the default style — used by the Finder Quick Action, the keyboard shortcut and the `md2pdf` command:
|
|
68
72
|
|
|
@@ -78,10 +82,12 @@ The choice is saved in `~/.config/md2pdf/config.json`. Use `md2pdf -s <style>` t
|
|
|
78
82
|
Styles are registered in the `STYLES` map in `bin/md2pdf.js`; each is a list of CSS files inlined into the page in order. A style has two files:
|
|
79
83
|
|
|
80
84
|
- `styles/<name>.css`, the on-screen look. The content is wrapped in `<article class="markdown-body">`, and every rule must be scoped to it: no `:root`, `html`, `body` or `@page` rules, so the style can be embedded in other pages.
|
|
81
|
-
- `styles/print/<name>.css`, the print-only rules: `@page` margins, running headers and page numbers,
|
|
85
|
+
- `styles/print/<name>.css`, the print-only rules: `@page` margins, running headers and page numbers, `html, body` margins, and `margin-trim: block-end` on `.markdown-body` in Safari, so it doesn't print a blank last page.
|
|
82
86
|
|
|
83
87
|
Register it in `STYLES` and add its page margin to `pageMargins` in `lib/styles.js`, and it's available to `-s` and `set-style.sh`. Use `md2pdf --html` to get the intermediate HTML for tweaking in a browser. For one-off tweaks, `--css` is enough.
|
|
84
88
|
|
|
89
|
+
`test/fixtures/sample.md` has the elements a style needs to handle: headings, lists, tables, code, block quotes, footnotes, images, math and a diagram; `test/fixtures/callouts.md` has the callouts. Check a style against them with `bin/md2pdf.js -s <name> test/fixtures/sample.md` (each PDF lands beside its Markdown; `*.pdf` is ignored). Its `mermaid` block prints as code here; md2pdf.me draws it as a diagram, so check diagrams there.
|
|
90
|
+
|
|
85
91
|
A style can bundle fonts, so it looks the same on every computer:
|
|
86
92
|
|
|
87
93
|
- Put each family in `styles/fonts/<family>/`: its `.woff2` files (the smallest format, and every current browser reads it) and its `OFL.txt`, and nothing else. Only fonts under the SIL Open Font License, which allows bundling. Fonts are the only files a style bundles.
|
|
@@ -91,7 +97,9 @@ A style can bundle fonts, so it looks the same on every computer:
|
|
|
91
97
|
|
|
92
98
|
The CLI resolves a stylesheet's relative `url()`s against the stylesheet, and loads every declared font before printing, including one used only in a page header. `npm test` checks the file layout, the licence, the family names, `local()` and `font-display`.
|
|
93
99
|
|
|
94
|
-
|
|
100
|
+
End the on-screen file with the rule the other styles end with, which turns off ligatures when Safari prints: Safari's PDFs copy a ligature as the wrong characters ("The" pastes as "!e"), while Chrome's, the CLI's and on-screen text are unaffected. It belongs in the on-screen file, not the print file, because a page that embeds a style prints without the print file. On a Mac with `swiftc`, `npm test` prints every style through WebKit and checks the copied text.
|
|
101
|
+
|
|
102
|
+
The text of the document's first `#` heading (empty if there is none, and a formula in it as its TeX, `$e^{i\pi}$`) is available to page margin boxes as `var(--document-title)`, e.g. `@top-left { content: var(--document-title); }`, as the `report` style does.
|
|
95
103
|
|
|
96
104
|
A style declares the [shared variables](#variables) in its first rule, `:where(.markdown-body) { … }`, with a comment saying what each one does there, and uses them for every size, gap, color and font they name. Spacing follows two patterns: `line-height: calc(1 + 0.55 * var(--md2pdf-leading))` and `margin: calc(1.8em * var(--md2pdf-space)) 0 …`. `npm test` checks that each variable is declared and changes the document. Page margins aren't included: they stay in the style's `@page` rule, in `styles/print/<name>.css`.
|
|
97
105
|
|
|
@@ -125,9 +133,9 @@ A style that [bundles fonts](#adding-a-style) loads them relative to its stylesh
|
|
|
125
133
|
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument(...)`, `titleOf(markdown, fallback)` (the first `#` heading's text as it renders, without Markdown syntax, else the front matter's `title:`, else the fallback), `escapeHtml(s)`, `cssString(s)`, `headingText(html)` |
|
|
126
134
|
| `@threepenny/md2pdf/styles` | `pageMargins`: each style's `@page` margin at default spacing, e.g. `pageMargins.classic` is `'1in 1.1in 0.9in'` |
|
|
127
135
|
| `@threepenny/md2pdf/styles/<name>.css` | Each style's on-screen look, scoped to `.markdown-body`. For `github`, load `github-markdown-css/github-markdown-light.css` first |
|
|
128
|
-
| `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers. Load it after the on-screen file, only in a page that holds nothing but the document |
|
|
136
|
+
| `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers, and, in Safari, no space below the document's last block. Load it after the on-screen file, only in a page that holds nothing but the document |
|
|
129
137
|
|
|
130
|
-
`createRenderer` takes the highlight.js instance to use (so you can pass a smaller bundle such as `highlight.js/lib/common`) and, optionally, `math: { katex }` to render `\( \)`, `\[ \]`, `$` and `$$` formulas with KaTeX; formulas also need KaTeX's stylesheet, `katex/dist/katex.min.css
|
|
138
|
+
`createRenderer` takes the highlight.js instance to use (so you can pass a smaller bundle such as `highlight.js/lib/common`) and, optionally, `math: { katex }` to render `\( \)`, `\[ \]`, `$` and `$$` formulas with KaTeX; formulas also need KaTeX's stylesheet, `katex/dist/katex.min.css`, which hides the MathML each formula carries for screen readers; without it, that MathML shows beside the formula and can draw far outside it. (Before 2.2 it also took markdown-it-texmath, as `math: { texmath, katex }`; that still works, and texmath is ignored.) A formula over 8,000 characters, one with braces nested over 100 levels deep, or one that defines a macro (`\def`, `\newcommand`), shows as its source in red. So does a formula that would take the HTML of a document's formulas, their MathML included, past 10,000,000 characters, and every formula after it, so that a short document can't make a page hundreds of megabytes; `math: { katex, maxHtml }` changes that budget, and `maxHtml: Infinity` removes it. Sizes such as `\rule` and `\raisebox` are capped at 30em, before a size command such as `\Huge` scales them. Raw HTML in the Markdown is passed through unless you pass `html: false`, which escapes it; page breaks (`<div class="page-break"></div>`) are raw HTML, so they then print as text. `idPrefix` starts the document's ids, as [Embedding in a web page](#embedding-in-a-web-page) describes. `highlightBudget` is how many milliseconds each render may spend highlighting code, after which the rest of the code shows without colour: 100 with `html: false`, unlimited otherwise. Under a budget, a block over 4 KB is highlighted in pieces split at line breaks where it can, so a comment or string that spans a split can be coloured wrongly.
|
|
131
139
|
|
|
132
140
|
### Variables
|
|
133
141
|
|
|
@@ -135,18 +143,18 @@ Every style takes the same variables, set on the `.markdown-body` element. A `--
|
|
|
135
143
|
|
|
136
144
|
| Variable | What it sets |
|
|
137
145
|
| -------- | ------------ |
|
|
138
|
-
| `--md2pdf-font-size` | The body text size; headings and smaller text scale with it. An absolute length (`pt`, `px` or `rem`), since `em` and `%` would compound. 11pt, or 10.5pt in `modern` and `report`, 10pt in `resume
|
|
146
|
+
| `--md2pdf-font-size` | The body text size; headings and smaller text scale with it. An absolute length (`pt`, `px` or `rem`), since `em` and `%` would compound. 11pt, or 10.5pt in `modern` and `report`, 10pt in `resume`, 13.5pt in `worksheet` and `elvish`, and 12pt in `gothic` and `cyberpunk` |
|
|
139
147
|
| `--md2pdf-leading` | Line spacing: scales each line height's excess over 1. 1 as designed |
|
|
140
148
|
| `--md2pdf-space` | The vertical gaps between blocks. 1 as designed |
|
|
141
149
|
| `--md2pdf-background` | The document's background, white |
|
|
142
150
|
| `--md2pdf-text` | Body text |
|
|
143
151
|
| `--md2pdf-muted` | Secondary text, such as footnotes and captions |
|
|
144
|
-
| `--md2pdf-accent` | The accent color: links, headings, list markers or callouts, depending on the style |
|
|
152
|
+
| `--md2pdf-accent` | The accent color: links, headings, list markers or callouts, depending on the style. `gothic`'s leaf ornaments stay oxblood, `sandwake`'s horizon ornament stays rust, `elvish`'s title, `#`, `##`, `####` and `#####` headings, links, quotes, note callouts, table rules and ornaments keep their own greens and gold, and `cyberpunk`'s `##` and `####` headings, links, nested bullets, list numbers, tick boxes, table headings, the title's frame, most of each rule, the quote label, note callouts and function names in code stay teal |
|
|
145
153
|
| `--md2pdf-rule` | Rules, borders and table lines (every style but `github`) |
|
|
146
|
-
| `--md2pdf-surface` | A tinted background: inline code and code blocks in `classic`, `modern` and `
|
|
154
|
+
| `--md2pdf-surface` | A tinted background: inline code and code blocks in `classic`, `modern`, `worksheet`, `gothic` and `elvish`, and callouts too in `classic` and `gothic`; inline code, quotes and table headings in `report`; the inside of code blocks, callouts and inline code in `sandwake`, white as designed; the title panel, inline code, code blocks, table headings and shaded table rows in `cyberpunk`. The other styles don't use it |
|
|
147
155
|
| `--md2pdf-font` | The body font |
|
|
148
|
-
| `--md2pdf-heading-font` | The heading font: the body font, except in `report`, where it's Helvetica and also sets callout titles and tables,
|
|
149
|
-
| `--md2pdf-code-font` | The code font |
|
|
156
|
+
| `--md2pdf-heading-font` | The heading font: the body font, except in `report`, where it's Helvetica and also sets callout titles and tables, in `worksheet`, where it's Fredoka and also sets callout titles, table headings and list markers, in `gothic`, where it's Grenze Gotisch for `#`, `##` and `###` headings and the drop cap, in `sandwake`, where it's Michroma for `#` and `##` headings and the drop cap, and in `elvish`, where it's Cormorant Unicase for `#` and `##` headings and the drop cap |
|
|
157
|
+
| `--md2pdf-code-font` | The code font, and in `sandwake` the small capital labels too: section and book numbers, `####` headings, table headings, callout titles and ordered-list numbers; in `cyberpunk` also keys, `###` and `######` headings, footnotes and every small label: section numbers, list numbers, table headings, callout titles and the title's, quotes' and code blocks' labels |
|
|
150
158
|
|
|
151
159
|
The styles are designed for light pages; a dark page isn't supported. Page headers and footers in a PDF keep the style's own fonts and colors.
|
|
152
160
|
|
|
@@ -199,9 +207,9 @@ A style that bundles fonts loads them from `fonts/` beside its stylesheet, so se
|
|
|
199
207
|
|
|
200
208
|
Set the [variables](#variables) on the `.markdown-body` element itself, with any selector or inline (`<article class="markdown-body" style="--md2pdf-font-size: 10pt">`). The style declares its defaults with no specificity, so your rule wins wherever it appears. A value set on `:root` or another element around the document doesn't reach it. One page can hold several documents in the same style, each with its own overrides, but not two different styles.
|
|
201
209
|
|
|
202
|
-
The document paints its own background, so on a page that isn't white, give it some padding. Your page's own CSS still applies inside the document, for whatever the style doesn't set: a global `
|
|
210
|
+
The document paints its own background, so on a page that isn't white, give it some padding. Your page's own CSS still applies inside the document, for whatever the style doesn't set: a global `em { color: #c00 }` reddens italic text in the document too. A highlight.js theme on your page is the exception: the styles keep it out of the document's code blocks. Headings get ids from their text (`# Notes` becomes `id="notes"`) so `[[#Notes]]` links work. Pass `idPrefix`, letters, digits, `_` and `-` starting with a letter and ending in `-`, to start every heading and footnote id with it, and every link to a `#` in the document: with `idPrefix: 'notes-'`, `# Notes` becomes `id="notes-notes"` and `[see](#notes)` links to it. Then no heading takes an id your page uses, as long as none of your page's ids start with the prefix, and two documents on one page don't share ids, as long as neither's prefix starts the other's (`a-` and `a-b-` would). Without it, give your own elements ids that a heading won't produce. Links in raw HTML, which only `html: true` lets through, aren't rewritten.
|
|
203
211
|
|
|
204
|
-
For Markdown you didn't write, render with `html: false` and an `idPrefix`, as in the example above. `html: false` escapes raw HTML, so the output has no scripts, event handlers, forms or style elements of the author's, and markdown-it refuses `javascript:`, `vbscript:`, `file:` and non-image `data:` URLs in links and images. The prefix keeps the document's ids from shadowing your page's globals (`# config` would otherwise give `id="config"`, which a browser exposes as `window.config`) or its own ids. Documents built to be slow to parse, such as thousands of identical headings, unclosed `[[` or unclosed formulas, render in about the time markdown-it itself takes. Code built to be slow to highlight is cut off by `highlightBudget`, which `html: false` sets to 100 ms: a render spends about that long highlighting, plus the 4 KB piece in progress, and shows the rest of the code without colour. A sanitizer such as DOMPurify is still worth running as a second line of defence. What's left to your page:
|
|
212
|
+
For Markdown you didn't write, render with `html: false` and an `idPrefix`, as in the example above. `html: false` escapes raw HTML, so the output has no scripts, event handlers, forms or style elements of the author's, and markdown-it refuses `javascript:`, `vbscript:`, `file:` and non-image `data:` URLs in links and images. The prefix keeps the document's ids from shadowing your page's globals (`# config` would otherwise give `id="config"`, which a browser exposes as `window.config`) or its own ids. Documents built to be slow to parse, such as thousands of identical headings, unclosed `[[` or unclosed formulas, render in about the time markdown-it itself takes. Code built to be slow to highlight is cut off by `highlightBudget`, which `html: false` sets to 100 ms: a render spends about that long highlighting, plus the 4 KB piece in progress, and shows the rest of the code without colour. A sanitizer such as DOMPurify is still worth running as a second line of defence; with math, pass DOMPurify `ADD_TAGS: ['semantics', 'annotation']`, or it unwraps the MathML's annotation and screen readers read each formula's TeX after it. What's left to your page:
|
|
205
213
|
|
|
206
214
|
- Limit the size of documents you accept. Without math the HTML can be about 23 times the size of the Markdown, for a document of nothing but callouts (only a document's first 200 callouts draw an icon, and only its first 1,000 inline footnotes `^[…]` become footnotes; the rest print as text). With math, the formulas' HTML stops at 10,000,000 characters (`maxHtml`), and the formulas after that show as their source.
|
|
207
215
|
- Images load from any URL the author chooses. A Content Security Policy's `img-src` limits that.
|
package/bin/md2pdf.js
CHANGED
|
@@ -28,8 +28,29 @@ const STYLES = {
|
|
|
28
28
|
report: styleFiles('report'),
|
|
29
29
|
resume: styleFiles('resume'),
|
|
30
30
|
worksheet: styleFiles('worksheet'),
|
|
31
|
+
gothic: styleFiles('gothic'),
|
|
32
|
+
sandwake: styleFiles('sandwake'),
|
|
33
|
+
elvish: styleFiles('elvish'),
|
|
34
|
+
cyberpunk: styleFiles('cyberpunk'),
|
|
31
35
|
};
|
|
32
36
|
const FALLBACK_STYLE = 'github';
|
|
37
|
+
// A checkout installed before KaTeX was a dependency has none until install.sh runs again; it still converts.
|
|
38
|
+
const katex = await import('katex').then(
|
|
39
|
+
(m) => m.default,
|
|
40
|
+
(err) => {
|
|
41
|
+
if (err.code === 'ERR_MODULE_NOT_FOUND') return null;
|
|
42
|
+
throw err;
|
|
43
|
+
},
|
|
44
|
+
);
|
|
45
|
+
// Added after the style only when the document has a formula, so a document without math prints as before.
|
|
46
|
+
// The rules after KaTeX's keep a displayed formula on one page and put a $$ … $$ (1) equation number at the
|
|
47
|
+
// right margin, as md2pdf.me does.
|
|
48
|
+
const MATH_CSS = katex && require.resolve('katex/dist/katex.min.css');
|
|
49
|
+
const EQUATION_NUMBERS = `
|
|
50
|
+
.markdown-body eqn { display: block; break-inside: avoid; }
|
|
51
|
+
.markdown-body section.eqno { display: flex; align-items: center; }
|
|
52
|
+
.markdown-body section.eqno > eqn { flex: 1; margin-left: 3em; }
|
|
53
|
+
.markdown-body section.eqno > span { width: 3em; text-align: right; }`;
|
|
33
54
|
|
|
34
55
|
// Settings shared by the CLI, Finder Quick Action and keyboard shortcut.
|
|
35
56
|
const CONFIG_PATH =
|
|
@@ -115,9 +136,11 @@ function readCss(file) {
|
|
|
115
136
|
}
|
|
116
137
|
|
|
117
138
|
function buildHtml({ markdown, title, baseDir, style, extraCss, pageSize }) {
|
|
118
|
-
const
|
|
139
|
+
const bodyHtml = createRenderer({ hljs, ...(katex && { math: { katex } }) }).render(markdown);
|
|
140
|
+
const math = /<eqn?>/.test(bodyHtml) ? [readCss(MATH_CSS) + EQUATION_NUMBERS] : [];
|
|
141
|
+
const css = [...STYLES[style].map(readCss), ...math, ...(extraCss ? [readCss(extraCss)] : [])].join('\n');
|
|
119
142
|
return buildDocument({
|
|
120
|
-
bodyHtml
|
|
143
|
+
bodyHtml,
|
|
121
144
|
title,
|
|
122
145
|
css,
|
|
123
146
|
pageSize,
|
|
@@ -129,9 +152,46 @@ function buildHtml({ markdown, title, baseDir, style, extraCss, pageSize }) {
|
|
|
129
152
|
});
|
|
130
153
|
}
|
|
131
154
|
|
|
155
|
+
// The temp folders that exist right now, and the Chrome printing, so an interrupt can clean up.
|
|
156
|
+
const tempDirs = new Set();
|
|
157
|
+
let chromeProc = null;
|
|
158
|
+
|
|
159
|
+
function makeTempDir(prefix) {
|
|
160
|
+
const dir = mkdtempSync(join(tmpdir(), prefix));
|
|
161
|
+
tempDirs.add(dir);
|
|
162
|
+
return dir;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function removeTempDir(dir) {
|
|
166
|
+
rmSync(dir, { recursive: true, force: true });
|
|
167
|
+
tempDirs.delete(dir);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// On an interrupt, stop Chrome, wait for it to let go of its profile, remove the temp folders, then
|
|
171
|
+
// die of the same signal so the shell sees it. Chrome gets SIGKILL: a Control + C reaches it too, and
|
|
172
|
+
// headless Chrome that has had a SIGINT hangs and ignores SIGTERM, outliving md2pdf.
|
|
173
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
|
174
|
+
process.once(signal, () => {
|
|
175
|
+
const die = () => {
|
|
176
|
+
for (const dir of tempDirs) {
|
|
177
|
+
try {
|
|
178
|
+
removeTempDir(dir);
|
|
179
|
+
} catch {
|
|
180
|
+
// Leave a folder that can't be removed rather than miss the others or the signal.
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
process.kill(process.pid, signal);
|
|
184
|
+
};
|
|
185
|
+
if (!chromeProc) return die();
|
|
186
|
+
chromeProc.once('close', die);
|
|
187
|
+
chromeProc.kill('SIGKILL');
|
|
188
|
+
setTimeout(die, 5000).unref();
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
132
192
|
function runChrome(chrome, htmlPath, pdfPath) {
|
|
133
193
|
// A throwaway profile keeps headless Chrome separate from any Chrome you have open.
|
|
134
|
-
const profile =
|
|
194
|
+
const profile = makeTempDir('md2pdf-chrome-');
|
|
135
195
|
const args = [
|
|
136
196
|
'--headless',
|
|
137
197
|
'--disable-gpu',
|
|
@@ -145,12 +205,18 @@ function runChrome(chrome, htmlPath, pdfPath) {
|
|
|
145
205
|
pathToFileURL(htmlPath).href,
|
|
146
206
|
];
|
|
147
207
|
return new Promise((resolvePromise, reject) => {
|
|
148
|
-
const proc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
208
|
+
const proc = (chromeProc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe'] }));
|
|
149
209
|
let stderr = '';
|
|
150
210
|
proc.stderr.on('data', (d) => (stderr += d));
|
|
151
|
-
|
|
211
|
+
// A Chrome that fails to start emits 'error' first, and main() may exit before its 'close' arrives.
|
|
212
|
+
proc.on('error', (err) => {
|
|
213
|
+
if (chromeProc === proc) chromeProc = null;
|
|
214
|
+
removeTempDir(profile);
|
|
215
|
+
reject(err);
|
|
216
|
+
});
|
|
152
217
|
proc.on('close', (code) => {
|
|
153
|
-
|
|
218
|
+
if (chromeProc === proc) chromeProc = null;
|
|
219
|
+
removeTempDir(profile);
|
|
154
220
|
if (code === 0 && existsSync(pdfPath)) resolvePromise();
|
|
155
221
|
else reject(new Error(`Chrome failed (exit ${code}):\n${stderr.trim()}`));
|
|
156
222
|
});
|
|
@@ -174,14 +240,14 @@ async function convert(input, opts, chrome) {
|
|
|
174
240
|
pageSize: opts['page-size'],
|
|
175
241
|
});
|
|
176
242
|
|
|
177
|
-
const workDir =
|
|
243
|
+
const workDir = makeTempDir('md2pdf-');
|
|
178
244
|
try {
|
|
179
245
|
const htmlPath = join(workDir, `${stem}.html`);
|
|
180
246
|
writeFileSync(htmlPath, html);
|
|
181
247
|
if (opts.html) writeFileSync(pdfPath.replace(/\.pdf$/i, '') + '.html', html);
|
|
182
248
|
await runChrome(chrome, htmlPath, pdfPath);
|
|
183
249
|
} finally {
|
|
184
|
-
|
|
250
|
+
removeTempDir(workDir);
|
|
185
251
|
}
|
|
186
252
|
return pdfPath;
|
|
187
253
|
}
|
|
@@ -236,6 +302,7 @@ async function main() {
|
|
|
236
302
|
}
|
|
237
303
|
|
|
238
304
|
const chrome = findChrome();
|
|
305
|
+
if (!katex) console.error(`md2pdf: KaTeX isn't installed, so formulas print as their source; run ${join(ROOT, 'install.sh')} again`);
|
|
239
306
|
let failed = 0;
|
|
240
307
|
for (const file of files) {
|
|
241
308
|
try {
|
package/lib/math.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// TeX math, rendered by KaTeX: $…$ and \(…\) inline, $$…$$, \[…\] and \begin{env}…\end{env} displayed,
|
|
2
2
|
// and a number in parentheses after a displayed formula, `$$E = mc^2$$ (1)`. The syntax is that of
|
|
3
3
|
// markdown-it-texmath 1.0.0 with its brackets, dollars and beg_end delimiters and outerSpace, except that
|
|
4
|
-
// a $ formula may also start or end beside a line break
|
|
5
|
-
//
|
|
4
|
+
// a $ formula may also start or end beside a line break and can't hold an unescaped $, and that starred
|
|
5
|
+
// environments such as align* start a block too. texmath searches for the closing delimiter from every
|
|
6
|
+
// opening one, which takes quadratic time on a line of openers, so these rules find closers through
|
|
6
7
|
// tables built in one pass over the source. A displayed formula also ends inside the blockquote it starts
|
|
7
8
|
// in; texmath's could run on past it, so that each of a run of quotes echoed the rest of the document.
|
|
8
9
|
|
|
@@ -19,8 +20,9 @@ const DEFINITION = /\\(?:[egx]?def|let|futurelet|global|long|(?:re|provide)?newc
|
|
|
19
20
|
// Caps how far a formula can reach (\rule, \raisebox, \hspace). Negative sizes aren't capped.
|
|
20
21
|
const MAX_SIZE = 30;
|
|
21
22
|
// The HTML a document's formulas may add up to, in characters, by default. KaTeX's HTML is about 50 to 250 times
|
|
22
|
-
// its TeX for ordinary formulas and over 500 times for a matrix of empty cells
|
|
23
|
-
//
|
|
23
|
+
// its TeX for ordinary formulas and over 500 times for a matrix of empty cells, and the MathML adds 10% to
|
|
24
|
+
// 30% to that, or nearly doubles a one-letter formula. A formula that would take the HTML past the budget,
|
|
25
|
+
// and every one after it, shows as its source.
|
|
24
26
|
const MAX_HTML = 10_000_000;
|
|
25
27
|
|
|
26
28
|
// How deeply {…} nest in `tex`, not counting a brace after a backslash.
|
|
@@ -48,6 +50,7 @@ const closeBracket = (s, i) => s.startsWith('\\]', i);
|
|
|
48
50
|
const dollar = (s, i) => s[i] === '$';
|
|
49
51
|
// A $ that can close an inline formula: not after a space or a backslash.
|
|
50
52
|
const dollarCloser = (s, i) => s[i] === '$' && i > 0 && !SPACE.test(s[i - 1]) && s[i - 1] !== '\\';
|
|
53
|
+
const bareDollar = (s, i) => s[i] === '$' && s[i - 1] !== '\\';
|
|
51
54
|
const lineBreak = (s, i) => isBreak(s[i]);
|
|
52
55
|
const nonSpace = (s, i) => !SPACE.test(s[i]);
|
|
53
56
|
const bracketNumberStop = (s, i) => ')$\r\n'.includes(s[i]);
|
|
@@ -72,7 +75,8 @@ function* doubleDollar(state, at) {
|
|
|
72
75
|
if (src[d + 1] === '$' && src[d + 2] === '$') yield { content: src.slice(at + 2, d + 1), end: d + 3 };
|
|
73
76
|
}
|
|
74
77
|
|
|
75
|
-
// $…$ from `at`, as texmath's \$((?:[^\s\\])|(?:\S.*?[^\s\\]))\$ matches it, or null.
|
|
78
|
+
// $…$ from `at`, as texmath's \$((?:[^\s\\])|(?:\S.*?[^\s\\]))\$ matches it, or null. Unlike texmath's,
|
|
79
|
+
// a formula can't hold an unescaped $ of its own, so in `From $5 to $10, $x$` only $x$ is a formula.
|
|
76
80
|
function singleDollar(state, at) {
|
|
77
81
|
const { src } = state;
|
|
78
82
|
const c = src[at + 1];
|
|
@@ -82,6 +86,8 @@ function singleDollar(state, at) {
|
|
|
82
86
|
if (close < 0) return null;
|
|
83
87
|
const br = first(state, lineBreak, at + 2);
|
|
84
88
|
if (br >= 0 && br < close) return null;
|
|
89
|
+
const inner = first(state, bareDollar, at + 1);
|
|
90
|
+
if (inner >= 0 && inner < close) return null;
|
|
85
91
|
return { content: src.slice(at + 1, close), end: close + 1 };
|
|
86
92
|
}
|
|
87
93
|
|
|
@@ -138,7 +144,7 @@ function equationNumber(state, from, stop) {
|
|
|
138
144
|
function environmentEnd(state, name, from) {
|
|
139
145
|
if (!state.md2pdfEnds) {
|
|
140
146
|
state.md2pdfEnds = new Map();
|
|
141
|
-
for (const m of state.src.matchAll(/\\end\{([a-z]
|
|
147
|
+
for (const m of state.src.matchAll(/\\end\{([a-z]+\*?)\}/g)) {
|
|
142
148
|
if (!state.md2pdfEnds.has(m[1])) state.md2pdfEnds.set(m[1], []);
|
|
143
149
|
state.md2pdfEnds.get(m[1]).push(m.index);
|
|
144
150
|
}
|
|
@@ -154,7 +160,7 @@ function environmentEnd(state, name, from) {
|
|
|
154
160
|
return lo < ends.length ? ends[lo] : -1;
|
|
155
161
|
}
|
|
156
162
|
|
|
157
|
-
const BEGIN = /\\begin\{([a-z]
|
|
163
|
+
const BEGIN = /\\begin\{([a-z]+\*?)\}/y;
|
|
158
164
|
|
|
159
165
|
// The displayed formula starting at `at`, trying texmath's block rules in their order, or null.
|
|
160
166
|
function displayed(state, at) {
|
|
@@ -256,7 +262,8 @@ export default function math(md, { katex, maxHtml = MAX_HTML }) {
|
|
|
256
262
|
try {
|
|
257
263
|
return katex.renderToString(tex, {
|
|
258
264
|
displayMode,
|
|
259
|
-
|
|
265
|
+
// MathML, which KaTeX's stylesheet hides, gives screen readers the formula; KaTeX hides its HTML from them.
|
|
266
|
+
output: 'htmlAndMathml',
|
|
260
267
|
throwOnError: false,
|
|
261
268
|
trust: false,
|
|
262
269
|
maxSize: MAX_SIZE,
|
package/lib/render.js
CHANGED
|
@@ -150,11 +150,32 @@ export function titleOf(markdown, fallback) {
|
|
|
150
150
|
export const cssString = (s) =>
|
|
151
151
|
`"${s.replace(/[\\"]/g, '\\$&').replace(/[\0-\x1f\x7f<]/g, (c) => `\\${c.charCodeAt(0).toString(16)} `)}"`;
|
|
152
152
|
|
|
153
|
-
|
|
153
|
+
const TEX = /<annotation encoding="application\/x-tex">([^<]*)<\/annotation>/;
|
|
154
|
+
|
|
155
|
+
// `html` with each formula in <eq> or <eqn> as its TeX between $ or $$, taken from KaTeX's MathML. A
|
|
156
|
+
// formula without it, such as one that failed to render, is left as it is.
|
|
157
|
+
function formulasAsTex(html) {
|
|
158
|
+
for (const [tag, dollars] of [['eq', '$'], ['eqn', '$$']]) {
|
|
159
|
+
const parts = html.split(`</${tag}>`);
|
|
160
|
+
html = parts
|
|
161
|
+
.map((part, i) => {
|
|
162
|
+
if (i === parts.length - 1) return part;
|
|
163
|
+
const at = part.lastIndexOf(`<${tag}>`);
|
|
164
|
+
const tex = at < 0 ? undefined : part.slice(at).match(TEX)?.[1];
|
|
165
|
+
return tex === undefined ? `${part}</${tag}>` : `${part.slice(0, at)}${dollars}${tex}${dollars}`;
|
|
166
|
+
})
|
|
167
|
+
.join('');
|
|
168
|
+
}
|
|
169
|
+
return html;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const ENTITIES = { lt: '<', gt: '>', quot: '"', amp: '&', '#x27': "'", '#039': "'" };
|
|
173
|
+
|
|
174
|
+
// The text of the first <h1> in rendered HTML, or '' if there is none. A formula in it shows as its TeX.
|
|
154
175
|
export function headingText(html) {
|
|
155
176
|
const inner = html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/)?.[1] ?? '';
|
|
156
|
-
const text = inner.replace(/<[^>]*>/g, '');
|
|
157
|
-
return text.replace(/&(lt|gt|quot|amp);/g, (_, e) =>
|
|
177
|
+
const text = formulasAsTex(inner).replace(/<[^>]*>/g, '');
|
|
178
|
+
return text.replace(/&(lt|gt|quot|amp|#x27|#039);/g, (_, e) => ENTITIES[e]).trim();
|
|
158
179
|
}
|
|
159
180
|
|
|
160
181
|
// A complete printable HTML document. `css` is the style's on-screen stylesheet followed by its print
|
package/lib/styles.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@threepenny/md2pdf",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.4.0",
|
|
4
4
|
"description": "Markdown to beautifully styled PDF: the renderer and macOS CLI behind md2pdf.me",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -35,12 +35,12 @@
|
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"github-markdown-css": "5.9.0",
|
|
37
37
|
"highlight.js": "^11.12.0",
|
|
38
|
+
"katex": "^0.19.1",
|
|
38
39
|
"markdown-it": "^15.0.2",
|
|
39
40
|
"markdown-it-emoji": "^3.1.0",
|
|
40
41
|
"markdown-it-footnote": "^4.0.0"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
|
-
"katex": "^0.19.1",
|
|
44
44
|
"markdown-it-task-lists": "^2.1.1",
|
|
45
45
|
"markdown-it-texmath": "^1.0.0"
|
|
46
46
|
}
|
package/styles/academic.css
CHANGED
|
@@ -383,7 +383,8 @@
|
|
|
383
383
|
break-after: avoid;
|
|
384
384
|
}
|
|
385
385
|
.markdown-body .footnotes ol {
|
|
386
|
-
|
|
386
|
+
/* Room for numbers up to 99, which Safari sets further left than Chrome. */
|
|
387
|
+
padding-left: 2em;
|
|
387
388
|
}
|
|
388
389
|
.markdown-body .footnotes p + p {
|
|
389
390
|
text-indent: 0;
|
|
@@ -397,6 +398,11 @@
|
|
|
397
398
|
display: none;
|
|
398
399
|
}
|
|
399
400
|
|
|
401
|
+
/* A word joiner keeps a footnote mark on the line with the word before it. */
|
|
402
|
+
.markdown-body .footnote-ref::before {
|
|
403
|
+
content: "\2060";
|
|
404
|
+
}
|
|
405
|
+
|
|
400
406
|
/* An Obsidian embed (![[Other note]]) that can't be shown: a muted placeholder. */
|
|
401
407
|
.markdown-body .markdown-embed {
|
|
402
408
|
color: var(--md2pdf-muted);
|
|
@@ -407,3 +413,14 @@
|
|
|
407
413
|
.markdown-body .page-break {
|
|
408
414
|
break-after: page;
|
|
409
415
|
}
|
|
416
|
+
|
|
417
|
+
/* Safari's PDFs copy a ligature as the wrong characters ("The" pastes as "!e", "ffi" as "ffi"), so it
|
|
418
|
+
prints without them. An element's own font-feature-settings or `font` shorthand undoes this; set
|
|
419
|
+
its features with font-variant-* instead. */
|
|
420
|
+
@media print {
|
|
421
|
+
@supports (font: -apple-system-body) {
|
|
422
|
+
.markdown-body {
|
|
423
|
+
font-feature-settings: "liga" 0, "clig" 0;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
package/styles/classic.css
CHANGED
|
@@ -375,13 +375,19 @@
|
|
|
375
375
|
break-after: avoid;
|
|
376
376
|
}
|
|
377
377
|
.markdown-body .footnotes ol {
|
|
378
|
-
|
|
378
|
+
/* Room for numbers up to 99, which Safari sets further left than Chrome. */
|
|
379
|
+
padding-left: 2.2em;
|
|
379
380
|
}
|
|
380
381
|
.markdown-body .footnote-ref a,
|
|
381
382
|
.markdown-body .footnote-backref {
|
|
382
383
|
color: var(--md2pdf-accent);
|
|
383
384
|
}
|
|
384
385
|
|
|
386
|
+
/* A word joiner keeps a footnote mark on the line with the word before it. */
|
|
387
|
+
.markdown-body .footnote-ref::before {
|
|
388
|
+
content: "\2060";
|
|
389
|
+
}
|
|
390
|
+
|
|
385
391
|
/* An Obsidian embed (![[Other note]]) that can't be shown: a muted placeholder. */
|
|
386
392
|
.markdown-body .markdown-embed {
|
|
387
393
|
color: var(--md2pdf-muted);
|
|
@@ -392,3 +398,14 @@
|
|
|
392
398
|
.markdown-body .page-break {
|
|
393
399
|
break-after: page;
|
|
394
400
|
}
|
|
401
|
+
|
|
402
|
+
/* Safari's PDFs copy a ligature as the wrong characters ("The" pastes as "!e", "ffi" as "ffi"), so it
|
|
403
|
+
prints without them. An element's own font-feature-settings or `font` shorthand undoes this; set
|
|
404
|
+
its features with font-variant-* instead. */
|
|
405
|
+
@media print {
|
|
406
|
+
@supports (font: -apple-system-body) {
|
|
407
|
+
.markdown-body {
|
|
408
|
+
font-feature-settings: "liga" 0, "clig" 0;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|