@threepenny/md2pdf 2.4.0 → 2.6.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 +15 -10
- package/bin/md2pdf.js +157 -26
- package/lib/css.js +35 -8
- package/lib/fit.js +393 -0
- package/lib/math.js +16 -11
- package/lib/page-size.js +20 -0
- package/lib/render.js +121 -16
- package/lib/typography.js +32 -0
- package/package.json +2 -1
- package/styles/github.css +12 -2
- package/styles/print/academic.css +24 -0
- package/styles/print/classic.css +24 -0
- package/styles/print/cyberpunk.css +24 -0
- package/styles/print/elvish.css +24 -0
- package/styles/print/github.css +20 -0
- package/styles/print/gothic.css +24 -0
- package/styles/print/modern.css +24 -0
- package/styles/print/report.css +24 -0
- package/styles/print/resume.css +24 -0
- package/styles/print/sandwake.css +24 -0
- package/styles/print/worksheet.css +24 -0
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
|
|
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 level-one heading, `#` or `<h1>`. A leading `---` block of ordinary Markdown prints as Markdown after a divider), and page breaks (`<div class="page-break"></div>`). Collapsed `<details>` sections print open. Typed `--`, `---`, `...` and `+-` print as –, —, … and ±, and straight quotes as curly ones; `(c)`, `(r)` and `(tm)` print as typed (before 2.5 they became ©, ® and ™, so type the symbol or `©`, `®`, `™` where you want one). 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. 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.
|
|
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. A displayed formula wider than the page shrinks until it fits, so a very long one prints small; split it over lines with `aligned` to keep it full size. A table wider than the page fits by letting the inline code and links in its widest columns break after a slash, then before a dot or an underscore too, so `@threepenny/md2pdf/render` can break after `@threepenny/`. If that isn't enough, a formula in one of its cells shrinks, to as little as half size. If it still doesn't fit, the long words in those columns break mid-word, without a hyphen, then their headers, then every cell as a last resort; a formula shrinks further only if the table still doesn't fit. A table that fits prints as written.
|
|
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, 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.
|
|
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, and your saved default style (below).
|
|
30
30
|
|
|
31
31
|
To use a different shortcut, pass it when installing (`@` ⌘, `~` ⌥, `^` ⌃, `$` ⇧), or set it to empty to skip:
|
|
32
32
|
|
|
@@ -50,6 +50,8 @@ md2pdf notes.md --css my.css # layer extra CSS on top of the style (its url()
|
|
|
50
50
|
md2pdf notes.md --html # also write the intermediate HTML (for tweaking CSS)
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
+
A `--css` file's `@import`s resolve against it too. The rules they import come before the style, so where they and the style set the same thing equally specifically, the style wins; rules written in the file itself win.
|
|
54
|
+
|
|
53
55
|
From Finder, a single file opens in Preview when done; multiple files show a notification.
|
|
54
56
|
|
|
55
57
|
## Styles
|
|
@@ -75,14 +77,14 @@ Switch the default style — used by the Finder Quick Action, the keyboard short
|
|
|
75
77
|
./set-style.sh classic # make classic the default
|
|
76
78
|
```
|
|
77
79
|
|
|
78
|
-
The choice is saved in `~/.config/md2pdf/config.json`. Use `md2pdf -s <style>` to override it for one conversion.
|
|
80
|
+
The choice is saved in `~/.config/md2pdf/config.json`. Use `md2pdf -s <style>` to override it for one conversion. If you set `XDG_CONFIG_HOME` in your shell, the `md2pdf` command and `set-style.sh` use `$XDG_CONFIG_HOME/md2pdf/config.json` instead, but the Quick Action and the shortcut still read `~/.config`, since Finder doesn't load your shell profile; `MD2PDF_CONFIG` names a config file of your own. `./uninstall.sh` deletes `config.json` from both of those `md2pdf` folders, and nothing else in them, and keeps a file elsewhere that `MD2PDF_CONFIG` names.
|
|
79
81
|
|
|
80
82
|
### Adding a style
|
|
81
83
|
|
|
82
84
|
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:
|
|
83
85
|
|
|
84
86
|
- `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.
|
|
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.
|
|
87
|
+
- `styles/print/<name>.css`, the print-only rules: `@page` margins, running headers and page numbers, `html, body` margins, collapsed `<details>` sections printed open, and `margin-trim: block-end` on `.markdown-body` in Safari, so it doesn't print a blank last page.
|
|
86
88
|
|
|
87
89
|
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.
|
|
88
90
|
|
|
@@ -91,15 +93,16 @@ Register it in `STYLES` and add its page margin to `pageMargins` in `lib/styles.
|
|
|
91
93
|
A style can bundle fonts, so it looks the same on every computer:
|
|
92
94
|
|
|
93
95
|
- 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.
|
|
96
|
+
- Check whether the font reserves its name, in the copyright lines at the top of upstream's `OFL.txt` or in the font's own copyright notice; a Fontsource or Google Fonts copy of `OFL.txt` can leave the name out. A modified font can't use a reserved name, and subsetting counts as modifying, so subset files like Fontsource's can't be bundled under it. Bundle upstream's own `.woff2` files, unchanged, and add the family's folder name to `RESERVED_NAME_FONTS` in `test/run.js` with the reason; or pick another font. IM Fell English is listed there for another reason: its files reserve the name, but Google Fonts' licence for them doesn't, and John decided that's the one that counts (#37).
|
|
94
97
|
- Declare them in the on-screen file with `@font-face`, relative to it: `src: url("fonts/<family>/<file>.woff2") format("woff2")`, with a `font-weight` and `font-style` for each face. The print file can use them without declaring them again.
|
|
95
98
|
- Name each family `md2pdf <Name>`, so it can't collide with a font on a page that embeds the style. Don't use `local()`, which would bring back the differences between computers, or `font-display: optional`, which lets the browser skip the font.
|
|
96
99
|
- Set the bundled family through the font variables, e.g. `--md2pdf-font: "md2pdf Andika", sans-serif`, so they can still be overridden.
|
|
97
100
|
|
|
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`.
|
|
101
|
+
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 and any reserved font name, the family names, `local()` and `font-display`.
|
|
99
102
|
|
|
100
103
|
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
104
|
|
|
102
|
-
The text of the document's first
|
|
105
|
+
The text of the document's first level-one heading, written as `#` or as an HTML `<h1>`, read as a browser shows it (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.
|
|
103
106
|
|
|
104
107
|
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`.
|
|
105
108
|
|
|
@@ -126,14 +129,16 @@ const html = buildDocument({
|
|
|
126
129
|
});
|
|
127
130
|
```
|
|
128
131
|
|
|
132
|
+
`pageSize` is the page size the CLI's `--page-size` takes, Letter by default: `auto`; `portrait` or `landscape`; a paper name (`a5`, `a4`, `a3`, `b5`, `b4`, `jis-b5`, `jis-b4`, `letter`, `legal`, `ledger`) alone or with `portrait` or `landscape`; or one or two lengths in `in`, `cm`, `mm`, `q`, `pt`, `pc`, `px`, `em`, `rem`, `ex`, `ch`, `vw`, `vh`, `vmin` or `vmax`, such as `5in 8in` (no `calc()` or newer units). Case doesn't matter. Anything else, including a value that isn't a string, throws a `TypeError`, so check a value you didn't choose with `isPageSize(size)` first. `head` (HTML added to the page's `<head>`) and `bodyHtml` are written into the page as given, and so is `css`, except that a `</style` in it can't end the page's `<style>` element. `css` and `head` must come from you, not from a visitor: CSS can still restyle the whole page and load URLs, which can send the page's content to another server. For Markdown you didn't write, render `bodyHtml` with `html: false`, as [below](#embedding-in-a-web-page) describes.
|
|
133
|
+
|
|
129
134
|
A style that [bundles fonts](#adding-a-style) loads them relative to its stylesheet, so a page that inlines the CSS must rewrite those `url()`s, as the CLI does, or let a bundler do it (in Vite, `?inline`, not `?raw`). Before printing, start every font loading and wait: a font used only in a page header may otherwise not be requested until printing starts, and the PDF falls back, as it does in headless Chrome. `await Promise.allSettled([...document.fonts].map((f) => f.load()))`.
|
|
130
135
|
|
|
131
136
|
| Export | What it is |
|
|
132
137
|
| ------ | ---------- |
|
|
133
|
-
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument(
|
|
138
|
+
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument({ bodyHtml, title, css, pageSize?, head? })`, `isPageSize(size)` (whether `buildDocument` takes `size` as its `pageSize`), `titleOf(markdown, fallback)` (the first level-one heading's text, a `#` heading or a raw-HTML `<h1>`, without Markdown syntax: the h1 `headingText` finds in a render with raw HTML on. Else the front matter's `title:`, else the fallback. The text is decoded, so escape it before writing it into HTML; `buildDocument` escapes its `title`), `escapeHtml(s)`, `cssString(s)`, `headingText(html)` (the text of the first `<h1>` in rendered HTML, as a browser shows it, formulas as their TeX) |
|
|
134
139
|
| `@threepenny/md2pdf/styles` | `pageMargins`: each style's `@page` margin at default spacing, e.g. `pageMargins.classic` is `'1in 1.1in 0.9in'` |
|
|
135
140
|
| `@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 |
|
|
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 |
|
|
141
|
+
| `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers, collapsed `<details>` sections printed open, 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. A section without a `<summary>` still shows the browser's closed arrow; to turn the arrow, remove each section's `name` and set `open` on it before printing, as the CLI does |
|
|
137
142
|
|
|
138
143
|
`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.
|
|
139
144
|
|
|
@@ -149,7 +154,7 @@ Every style takes the same variables, set on the `.markdown-body` element. A `--
|
|
|
149
154
|
| `--md2pdf-background` | The document's background, white |
|
|
150
155
|
| `--md2pdf-text` | Body text |
|
|
151
156
|
| `--md2pdf-muted` | Secondary text, such as footnotes and captions |
|
|
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 |
|
|
157
|
+
| `--md2pdf-accent` | The accent color: links, headings, list markers or callouts, depending on the style, and `github`'s focus rings. `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 |
|
|
153
158
|
| `--md2pdf-rule` | Rules, borders and table lines (every style but `github`) |
|
|
154
159
|
| `--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 |
|
|
155
160
|
| `--md2pdf-font` | The body font |
|
package/bin/md2pdf.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// md2pdf: convert Markdown files to PDF using headless Chrome.
|
|
3
3
|
|
|
4
4
|
import { spawn } from 'node:child_process';
|
|
5
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
6
6
|
import { homedir, tmpdir } from 'node:os';
|
|
7
7
|
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
8
8
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
@@ -11,7 +11,9 @@ import { createRequire } from 'node:module';
|
|
|
11
11
|
|
|
12
12
|
import hljs from 'highlight.js';
|
|
13
13
|
import { buildDocument, createRenderer, titleOf } from '../lib/render.js';
|
|
14
|
-
import {
|
|
14
|
+
import { fitFormulas, fitTables } from '../lib/fit.js';
|
|
15
|
+
import { rewriteUrls, splitImports } from '../lib/css.js';
|
|
16
|
+
import { PAPER, isPageSize } from '../lib/page-size.js';
|
|
15
17
|
|
|
16
18
|
const require = createRequire(import.meta.url);
|
|
17
19
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
@@ -34,6 +36,8 @@ const STYLES = {
|
|
|
34
36
|
cyberpunk: styleFiles('cyberpunk'),
|
|
35
37
|
};
|
|
36
38
|
const FALLBACK_STYLE = 'github';
|
|
39
|
+
// Not STYLES[name], which is truthy for names every object inherits, such as toString.
|
|
40
|
+
const isStyle = (name) => typeof name === 'string' && Object.hasOwn(STYLES, name);
|
|
37
41
|
// A checkout installed before KaTeX was a dependency has none until install.sh runs again; it still converts.
|
|
38
42
|
const katex = await import('katex').then(
|
|
39
43
|
(m) => m.default,
|
|
@@ -75,7 +79,7 @@ Options:
|
|
|
75
79
|
-o, --output <file> Output path (only with a single input file)
|
|
76
80
|
-s, --style <name> Style to use (${Object.keys(STYLES).join(', ')}; default: ${defaultStyle})
|
|
77
81
|
--css <file> Extra CSS file applied after the style
|
|
78
|
-
-p, --page-size <size> Letter, A4, Legal, ... (default: Letter)
|
|
82
|
+
-p, --page-size <size> Letter, A4, Legal, "A4 landscape", "5in 8in", ... (default: Letter)
|
|
79
83
|
--open Open the PDF when done
|
|
80
84
|
--html Also write the intermediate .html (for debugging styles)
|
|
81
85
|
--set-style <name> Make <name> the default style (also used by the Finder Quick Action)
|
|
@@ -89,7 +93,9 @@ Environment:
|
|
|
89
93
|
function readConfig() {
|
|
90
94
|
if (!existsSync(CONFIG_PATH)) return {};
|
|
91
95
|
try {
|
|
92
|
-
|
|
96
|
+
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
|
97
|
+
if (config === null || typeof config !== 'object' || Array.isArray(config)) throw new Error('not a JSON object');
|
|
98
|
+
return config;
|
|
93
99
|
} catch (err) {
|
|
94
100
|
console.error(`md2pdf: ignoring unreadable config ${CONFIG_PATH}: ${err.message}`);
|
|
95
101
|
return {};
|
|
@@ -113,9 +119,9 @@ function findChrome() {
|
|
|
113
119
|
return found;
|
|
114
120
|
}
|
|
115
121
|
|
|
116
|
-
// A stylesheet's text, with its relative url()s (a style's bundled fonts, say) made absolute:
|
|
117
|
-
// into the page, they would otherwise resolve against the Markdown file's folder. Warns once about
|
|
118
|
-
// file they name that doesn't exist.
|
|
122
|
+
// A stylesheet's text, with its relative url()s and @imports (a style's bundled fonts, say) made absolute:
|
|
123
|
+
// inlined into the page, they would otherwise resolve against the Markdown file's folder. Warns once about
|
|
124
|
+
// each file they name that doesn't exist.
|
|
119
125
|
const warned = new Set();
|
|
120
126
|
function readCss(file) {
|
|
121
127
|
return rewriteUrls(readFileSync(file, 'utf8'), (ref) => {
|
|
@@ -138,7 +144,15 @@ function readCss(file) {
|
|
|
138
144
|
function buildHtml({ markdown, title, baseDir, style, extraCss, pageSize }) {
|
|
139
145
|
const bodyHtml = createRenderer({ hljs, ...(katex && { math: { katex } }) }).render(markdown);
|
|
140
146
|
const math = /<eqn?>/.test(bodyHtml) ? [readCss(MATH_CSS) + EQUATION_NUMBERS] : [];
|
|
141
|
-
|
|
147
|
+
// An @import counts only before every other rule, so the --css file's @imports lead the page's CSS: the
|
|
148
|
+
// style then wins ties with the rules they import, while the file's own rules still follow the style.
|
|
149
|
+
const extra = extraCss ? splitImports(readCss(extraCss)) : null;
|
|
150
|
+
const css = [...(extra ? extra.head : []), ...STYLES[style].map(readCss), ...math, ...(extra ? [extra.rest] : [])].join('\n');
|
|
151
|
+
const loadFonts = `() => document.fonts.forEach((f) => f.load().catch(() => {}))`;
|
|
152
|
+
// Once its fonts have loaded, a displayed formula wider than the column shrinks to fit. It fits whatever
|
|
153
|
+
// column it ends up in, so the printed page needs no second run. Then a table wider than the printed page
|
|
154
|
+
// fits it, measured at that page's width; it goes second, since fitFormulas resets a formula in a cell.
|
|
155
|
+
const fits = [...(/<eqn>/.test(bodyHtml) ? [fitFormulas] : []), ...(/<table[\s>]/i.test(bodyHtml) ? [fitTables] : [])];
|
|
142
156
|
return buildDocument({
|
|
143
157
|
bodyHtml,
|
|
144
158
|
title,
|
|
@@ -146,9 +160,29 @@ function buildHtml({ markdown, title, baseDir, style, extraCss, pageSize }) {
|
|
|
146
160
|
pageSize,
|
|
147
161
|
// <base> makes relative image/link paths resolve against the Markdown file's folder.
|
|
148
162
|
// Chrome loads a font used only in a page header or footer too late for the PDF, so start every
|
|
149
|
-
// declared font loading now; the PDF waits for those loads with the rest of the page.
|
|
163
|
+
// declared font loading now; the PDF waits for those loads with the rest of the page. An imported
|
|
164
|
+
// stylesheet's fonts may not be declared until the page has loaded, so they start then.
|
|
150
165
|
head: `<base href="${pathToFileURL(baseDir + '/').href}">
|
|
151
|
-
<script>document.addEventListener('DOMContentLoaded',
|
|
166
|
+
<script>document.addEventListener('DOMContentLoaded', ${loadFonts});</script>${extra?.head.length ? `
|
|
167
|
+
<script>addEventListener('load', ${loadFonts});</script>` : ''}${
|
|
168
|
+
// The print stylesheet shows a collapsed section's content, but can't reach the closed arrow the
|
|
169
|
+
// browser draws for one without a <summary>. Opening each section turns that arrow too. Opening one
|
|
170
|
+
// section of a named group closes the rest, so each leaves its group first.
|
|
171
|
+
/<details[\s/>]/i.test(bodyHtml)
|
|
172
|
+
? `
|
|
173
|
+
<script>document.addEventListener('DOMContentLoaded', () => {
|
|
174
|
+
for (const section of document.querySelectorAll('details')) {
|
|
175
|
+
section.removeAttribute('name');
|
|
176
|
+
section.open = true;
|
|
177
|
+
}
|
|
178
|
+
});</script>`
|
|
179
|
+
: ''
|
|
180
|
+
}${fits.length
|
|
181
|
+
? `
|
|
182
|
+
<script>${fits.join('\n')}
|
|
183
|
+
addEventListener('load', () => document.fonts.ready.then(() => { ${fits.map((fit) => `${fit.name}();`).join(' ')} }));</script>`
|
|
184
|
+
: ''
|
|
185
|
+
}`,
|
|
152
186
|
});
|
|
153
187
|
}
|
|
154
188
|
|
|
@@ -189,6 +223,45 @@ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
|
|
189
223
|
});
|
|
190
224
|
}
|
|
191
225
|
|
|
226
|
+
// What went wrong and what to do on the first line, the only one the Quick Action's notification shows,
|
|
227
|
+
// so it never suggests setting CHROME_PATH, which a Quick Action can't see. The Chrome that ran and its
|
|
228
|
+
// own output go below.
|
|
229
|
+
function chromeFailed(chrome, first, { output = '', suggestChromePath = true } = {}) {
|
|
230
|
+
const lines = [first];
|
|
231
|
+
if (suggestChromePath) lines.push(' If it keeps failing, set CHROME_PATH to a different Chrome-based browser.');
|
|
232
|
+
lines.push(` Chrome: ${chrome}`);
|
|
233
|
+
if (output.trim()) lines.push(" Chrome's output:", ...output.trim().split('\n').map((l) => ` ${l}`));
|
|
234
|
+
return new Error(lines.join('\n'));
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const TRY_AGAIN = 'It may be updating; try again in a moment.';
|
|
238
|
+
|
|
239
|
+
function cantStart(chrome, err) {
|
|
240
|
+
if (!process.env.CHROME_PATH) return chromeFailed(chrome, `Chrome couldn't start (${err.code ?? err.message}). ${TRY_AGAIN}`);
|
|
241
|
+
let folder = false;
|
|
242
|
+
try {
|
|
243
|
+
folder = statSync(chrome).isDirectory();
|
|
244
|
+
} catch {
|
|
245
|
+
// Missing, or in a folder md2pdf can't read: not a folder it can name.
|
|
246
|
+
}
|
|
247
|
+
if (folder) {
|
|
248
|
+
return chromeFailed(
|
|
249
|
+
chrome,
|
|
250
|
+
`Chrome couldn't start: CHROME_PATH names a folder (${err.code ?? err.message}). ` +
|
|
251
|
+
'For an app, give the program inside it, such as /Applications/Google Chrome.app/Contents/MacOS/Google Chrome.',
|
|
252
|
+
{ suggestChromePath: false },
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
const why = {
|
|
256
|
+
ENOENT: "there's no file at CHROME_PATH",
|
|
257
|
+
ENOTDIR: "there's no file at CHROME_PATH",
|
|
258
|
+
EACCES: "the file at CHROME_PATH can't be run",
|
|
259
|
+
}[err.code] ?? "the file at CHROME_PATH didn't run";
|
|
260
|
+
return chromeFailed(chrome, `Chrome couldn't start: ${why} (${err.code ?? err.message}). Check that it names a Chrome-based browser.`, {
|
|
261
|
+
suggestChromePath: false,
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
|
|
192
265
|
function runChrome(chrome, htmlPath, pdfPath) {
|
|
193
266
|
// A throwaway profile keeps headless Chrome separate from any Chrome you have open.
|
|
194
267
|
const profile = makeTempDir('md2pdf-chrome-');
|
|
@@ -205,30 +278,64 @@ function runChrome(chrome, htmlPath, pdfPath) {
|
|
|
205
278
|
pathToFileURL(htmlPath).href,
|
|
206
279
|
];
|
|
207
280
|
return new Promise((resolvePromise, reject) => {
|
|
208
|
-
|
|
281
|
+
let proc;
|
|
282
|
+
try {
|
|
283
|
+
proc = chromeProc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
284
|
+
} catch (err) {
|
|
285
|
+
// Most failures to start arrive as 'error' below; some (ENOTDIR, say) are thrown here.
|
|
286
|
+
removeTempDir(profile);
|
|
287
|
+
reject(cantStart(chrome, err));
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
209
290
|
let stderr = '';
|
|
210
291
|
proc.stderr.on('data', (d) => (stderr += d));
|
|
211
292
|
// A Chrome that fails to start emits 'error' first, and main() may exit before its 'close' arrives.
|
|
212
293
|
proc.on('error', (err) => {
|
|
213
294
|
if (chromeProc === proc) chromeProc = null;
|
|
214
295
|
removeTempDir(profile);
|
|
215
|
-
reject(err);
|
|
296
|
+
reject(cantStart(chrome, err));
|
|
216
297
|
});
|
|
217
|
-
proc.on('close', (code) => {
|
|
298
|
+
proc.on('close', (code, signal) => {
|
|
218
299
|
if (chromeProc === proc) chromeProc = null;
|
|
219
300
|
removeTempDir(profile);
|
|
220
301
|
if (code === 0 && existsSync(pdfPath)) resolvePromise();
|
|
221
|
-
else reject(
|
|
302
|
+
else if (code === 0) reject(chromeFailed(chrome, `Chrome quit without printing. ${TRY_AGAIN}`, { output: stderr }));
|
|
303
|
+
else {
|
|
304
|
+
const how = signal ? `stopped by ${signal}` : `exit ${code}`;
|
|
305
|
+
reject(chromeFailed(chrome, `Chrome quit before printing (${how}). ${TRY_AGAIN}`, { output: stderr }));
|
|
306
|
+
}
|
|
222
307
|
});
|
|
223
308
|
});
|
|
224
309
|
}
|
|
225
310
|
|
|
226
|
-
|
|
311
|
+
// A file's identity, whatever name reaches it: names can differ by case, a symlink or a hard link.
|
|
312
|
+
const fileId = (stat) => `${stat.dev}:${stat.ino}`;
|
|
313
|
+
|
|
314
|
+
// `written` maps each PDF this run has written, by fileId, to the input it came from;
|
|
315
|
+
// `inputs` maps each of this run's inputs, by fileId, to its name.
|
|
316
|
+
async function convert(input, opts, chrome, written, inputs) {
|
|
227
317
|
const inputPath = resolve(input);
|
|
228
318
|
if (!existsSync(inputPath)) throw new Error(`No such file: ${input}`);
|
|
229
|
-
const
|
|
319
|
+
const source = fileId(statSync(inputPath));
|
|
230
320
|
const stem = basename(inputPath, extname(inputPath));
|
|
231
321
|
const pdfPath = resolve(opts.output ?? join(dirname(inputPath), `${stem}.pdf`));
|
|
322
|
+
const target = statSync(pdfPath, { throwIfNoEntry: false });
|
|
323
|
+
if (target && fileId(target) === source) {
|
|
324
|
+
throw new Error('The PDF would replace the file it is made from; give another path with --output');
|
|
325
|
+
}
|
|
326
|
+
const htmlPath = opts.html && pdfPath.replace(/\.pdf$/i, '') + '.html';
|
|
327
|
+
const htmlTarget = htmlPath && statSync(htmlPath, { throwIfNoEntry: false });
|
|
328
|
+
if (htmlTarget && fileId(htmlTarget) === source) {
|
|
329
|
+
throw new Error('The HTML would replace the file it is made from; give another path with --output');
|
|
330
|
+
}
|
|
331
|
+
if (htmlTarget && inputs.has(fileId(htmlTarget))) {
|
|
332
|
+
throw new Error(`The HTML would replace ${inputs.get(fileId(htmlTarget))}, another input; convert it alone with --output`);
|
|
333
|
+
}
|
|
334
|
+
if (target && written.has(fileId(target))) {
|
|
335
|
+
throw new Error(`${pdfPath} was already written from ${written.get(fileId(target))}; convert it alone with --output`);
|
|
336
|
+
}
|
|
337
|
+
if (!existsSync(dirname(pdfPath))) throw new Error(`No such folder: ${dirname(pdfPath)}`);
|
|
338
|
+
const markdown = readFileSync(inputPath, 'utf8');
|
|
232
339
|
const title = titleOf(markdown, stem);
|
|
233
340
|
|
|
234
341
|
const html = buildHtml({
|
|
@@ -242,13 +349,21 @@ async function convert(input, opts, chrome) {
|
|
|
242
349
|
|
|
243
350
|
const workDir = makeTempDir('md2pdf-');
|
|
244
351
|
try {
|
|
245
|
-
const
|
|
246
|
-
writeFileSync(
|
|
247
|
-
if (
|
|
248
|
-
|
|
352
|
+
const page = join(workDir, `${stem}.html`);
|
|
353
|
+
writeFileSync(page, html);
|
|
354
|
+
if (htmlPath) writeFileSync(htmlPath, html);
|
|
355
|
+
// Chrome prints into the temp folder: printing over a PDF it can't replace, it reports success.
|
|
356
|
+
const printed = join(workDir, 'print.pdf');
|
|
357
|
+
await runChrome(chrome, page, printed);
|
|
358
|
+
try {
|
|
359
|
+
writeFileSync(pdfPath, readFileSync(printed));
|
|
360
|
+
} catch (err) {
|
|
361
|
+
throw new Error(`Could not write ${pdfPath}: ${err.message.split(',')[0]}`);
|
|
362
|
+
}
|
|
249
363
|
} finally {
|
|
250
364
|
removeTempDir(workDir);
|
|
251
365
|
}
|
|
366
|
+
written.set(fileId(statSync(pdfPath)), input);
|
|
252
367
|
return pdfPath;
|
|
253
368
|
}
|
|
254
369
|
|
|
@@ -275,10 +390,10 @@ async function main() {
|
|
|
275
390
|
}
|
|
276
391
|
const { values: opts, positionals: files } = parsed;
|
|
277
392
|
const config = readConfig();
|
|
278
|
-
const defaultStyle =
|
|
393
|
+
const defaultStyle = isStyle(config.style) ? config.style : FALLBACK_STYLE;
|
|
279
394
|
|
|
280
395
|
if (opts['set-style'] !== undefined) {
|
|
281
|
-
if (!
|
|
396
|
+
if (!isStyle(opts['set-style'])) unknownStyle(opts['set-style']);
|
|
282
397
|
writeConfig({ ...config, style: opts['set-style'] });
|
|
283
398
|
console.log(`Default style is now "${opts['set-style']}".`);
|
|
284
399
|
process.exit(0);
|
|
@@ -291,22 +406,38 @@ async function main() {
|
|
|
291
406
|
console.log(usage(defaultStyle));
|
|
292
407
|
process.exit(opts.help ? 0 : 2);
|
|
293
408
|
}
|
|
294
|
-
if (config.style && !
|
|
409
|
+
if (config.style && !isStyle(config.style)) {
|
|
295
410
|
console.error(`md2pdf: config style "${config.style}" no longer exists; using ${FALLBACK_STYLE}`);
|
|
296
411
|
}
|
|
297
412
|
opts.style ??= defaultStyle;
|
|
298
|
-
if (!
|
|
413
|
+
if (!isStyle(opts.style)) unknownStyle(opts.style);
|
|
414
|
+
if (!isPageSize(opts['page-size'])) {
|
|
415
|
+
console.error(`md2pdf: unknown page size "${opts['page-size']}". Use one of ${PAPER.join(', ')}, alone or with "landscape", or a width and height such as "5in 8in"`);
|
|
416
|
+
process.exit(2);
|
|
417
|
+
}
|
|
299
418
|
if (opts.output && files.length > 1) {
|
|
300
419
|
console.error('md2pdf: --output can only be used with a single input file');
|
|
301
420
|
process.exit(2);
|
|
302
421
|
}
|
|
303
422
|
|
|
304
|
-
|
|
423
|
+
let chrome;
|
|
424
|
+
try {
|
|
425
|
+
chrome = findChrome();
|
|
426
|
+
} catch (err) {
|
|
427
|
+
console.error(`md2pdf: ${err.message}`);
|
|
428
|
+
process.exit(1);
|
|
429
|
+
}
|
|
305
430
|
if (!katex) console.error(`md2pdf: KaTeX isn't installed, so formulas print as their source; run ${join(ROOT, 'install.sh')} again`);
|
|
306
431
|
let failed = 0;
|
|
432
|
+
const written = new Map();
|
|
433
|
+
const inputs = new Map();
|
|
434
|
+
for (const file of files) {
|
|
435
|
+
const stat = statSync(resolve(file), { throwIfNoEntry: false });
|
|
436
|
+
if (stat) inputs.set(fileId(stat), file);
|
|
437
|
+
}
|
|
307
438
|
for (const file of files) {
|
|
308
439
|
try {
|
|
309
|
-
const pdf = await convert(file, opts, chrome);
|
|
440
|
+
const pdf = await convert(file, opts, chrome, written, inputs);
|
|
310
441
|
console.log(pdf);
|
|
311
442
|
if (opts.open) spawn('open', [pdf], { stdio: 'ignore', detached: true }).unref();
|
|
312
443
|
} catch (err) {
|
package/lib/css.js
CHANGED
|
@@ -2,26 +2,53 @@
|
|
|
2
2
|
|
|
3
3
|
import { cssString } from './render.js';
|
|
4
4
|
|
|
5
|
-
// A comment, a string, or a url()
|
|
5
|
+
// A comment, a string, an @import of a string, or a url(); the groups hold the @import's double- or
|
|
6
|
+
// single-quoted reference, then the url()'s double-quoted, single-quoted or bare one.
|
|
6
7
|
const STRING = (q) => `${q}(?:\\\\[^]|[^${q}\\\\\\n])*${q}`;
|
|
7
8
|
const TOKENS = new RegExp(
|
|
8
|
-
String.raw`\/\*[^]
|
|
9
|
+
String.raw`\/\*[^]*?\*\/|@import\s*(?:"((?:\\[^]|[^"\\\n])*)"|'((?:\\[^]|[^'\\\n])*)')|${STRING('"')}|${STRING("'")}|url\(\s*(?:"((?:\\[^]|[^"\\\n])*)"|'((?:\\[^]|[^'\\\n])*)'|([^)\s'"\\]*))\s*\)`,
|
|
9
10
|
'gi',
|
|
10
11
|
);
|
|
11
12
|
|
|
12
|
-
// Replaces each relative url() in a stylesheet with url(<resolve(ref)>)
|
|
13
|
-
// and references that are absolute, root-relative,
|
|
13
|
+
// Replaces each relative url() and @import "…" in a stylesheet with url(<resolve(ref)>) or
|
|
14
|
+
// @import "<resolve(ref)>", leaving comments, strings, and references that are absolute, root-relative,
|
|
15
|
+
// fragments or contain CSS escapes as they are.
|
|
14
16
|
export function rewriteUrls(css, resolve) {
|
|
15
|
-
return css.replace(TOKENS, (whole, dq, sq, bare) => {
|
|
16
|
-
const ref = dq ?? sq ?? bare;
|
|
17
|
+
return css.replace(TOKENS, (whole, idq, isq, dq, sq, bare) => {
|
|
18
|
+
const ref = idq ?? isq ?? dq ?? sq ?? bare;
|
|
17
19
|
if (!ref || ref.includes('\\') || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(ref)) return whole;
|
|
18
|
-
return `url(${cssString(resolve(ref))})`;
|
|
20
|
+
return (idq ?? isq) !== undefined ? `@import ${cssString(resolve(ref))}` : `url(${cssString(resolve(ref))})`;
|
|
19
21
|
});
|
|
20
22
|
}
|
|
21
23
|
|
|
22
|
-
// The relative references a stylesheet's url()s make, as rewriteUrls sees them.
|
|
24
|
+
// The relative references a stylesheet's url()s and @imports make, as rewriteUrls sees them.
|
|
23
25
|
export function relativeUrls(css) {
|
|
24
26
|
const refs = [];
|
|
25
27
|
rewriteUrls(css, (ref) => (refs.push(ref), ref));
|
|
26
28
|
return refs;
|
|
27
29
|
}
|
|
30
|
+
|
|
31
|
+
// What may open a stylesheet: white space, a comment, or an @charset, @layer or @import statement.
|
|
32
|
+
// Each character of a statement can match only one way, and a comment ends at its first */, so a long
|
|
33
|
+
// statement that never ends can't make the match backtrack; an unclosed comment ends the opening.
|
|
34
|
+
const COMMENT = String.raw`\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/`;
|
|
35
|
+
const QUOTED = `${STRING('"')}|${STRING("'")}`;
|
|
36
|
+
const group = (inner) => String.raw`\((?:${COMMENT}|${QUOTED}|${inner}|\/(?!\*)|[^()"'/])*\)`;
|
|
37
|
+
const PRELUDE = String.raw`\s+|${COMMENT}|@(charset|layer|import)(?![\w-])(?:${COMMENT}|${QUOTED}|${group(group(group('(?!)')))}|\/(?!\*)|[^;{}()"'/])*(?:;|$)`;
|
|
38
|
+
|
|
39
|
+
// A stylesheet's leading @import rules, which count only before every other rule, with the @layer
|
|
40
|
+
// statements among them so its layers keep their order; and the rest of its text. A stylesheet with no
|
|
41
|
+
// @import comes back whole.
|
|
42
|
+
export function splitImports(css) {
|
|
43
|
+
const prelude = new RegExp(PRELUDE, 'iy');
|
|
44
|
+
const head = [];
|
|
45
|
+
let rest = '';
|
|
46
|
+
let end = 0;
|
|
47
|
+
for (let m; (m = prelude.exec(css)); end = prelude.lastIndex) {
|
|
48
|
+
// One at the very end may have no semicolon; moved ahead of other rules, it needs one.
|
|
49
|
+
if (/^(?:import|layer)$/i.test(m[1] ?? '')) head.push(m[0].endsWith(';') ? m[0] : `${m[0]};`);
|
|
50
|
+
else rest += m[0];
|
|
51
|
+
}
|
|
52
|
+
if (!head.some((rule) => /^@import/i.test(rule))) return { head: [], rest: css };
|
|
53
|
+
return { head, rest: rest + css.slice(end) };
|
|
54
|
+
}
|