turbo-html2pdf 0.1.0 → 0.1.2
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/Cargo.toml +17 -1
- package/README.md +184 -68
- package/index.d.ts +111 -7
- package/index.js +4 -1
- package/package.json +2 -2
- package/src/convert.rs +70 -24
- package/src/errors.rs +7 -1
- package/src/lib.rs +297 -54
- package/turbo-pdf-napi.darwin-arm64.node +0 -0
- package/turbo-pdf-napi.linux-arm64-gnu.node +0 -0
- package/turbo-pdf-napi.linux-x64-gnu.node +0 -0
- package/turbo-pdf-napi.linux-x64-musl.node +0 -0
- package/turbo-pdf-napi.win32-x64-msvc.node +0 -0
package/Cargo.toml
CHANGED
|
@@ -14,11 +14,27 @@ rust-version.workspace = true
|
|
|
14
14
|
crate-type = ["cdylib", "rlib"]
|
|
15
15
|
|
|
16
16
|
[dependencies]
|
|
17
|
-
turbo-pdf-core = { path = "../turbo-pdf-core"
|
|
17
|
+
turbo-pdf-core = { path = "../turbo-pdf-core", features = [
|
|
18
|
+
"endnotes",
|
|
19
|
+
"xref",
|
|
20
|
+
"pdf-a",
|
|
21
|
+
"pdf-ua",
|
|
22
|
+
"print-color",
|
|
23
|
+
"append",
|
|
24
|
+
"encrypt",
|
|
25
|
+
] }
|
|
26
|
+
serde = { workspace = true }
|
|
18
27
|
serde_json = { workspace = true }
|
|
19
28
|
# napi-rs front-end (native addon). `napi6` matches turbo-dom's ABI baseline.
|
|
20
29
|
napi = { version = "2", default-features = false, features = ["napi6", "serde-json"] }
|
|
21
30
|
napi-derive = "2"
|
|
22
31
|
|
|
32
|
+
[features]
|
|
33
|
+
# Passthrough for the core `svg` feature (vector `<img>` via resvg). OFF by
|
|
34
|
+
# default: the standard `turbo-html2pdf` package ships without it. The separate
|
|
35
|
+
# `turbo-html2pdf-svg` package is built with `napi build --features svg` (see the
|
|
36
|
+
# `build-napi-svg`/`publish-svg` jobs in .github/workflows/release.yml).
|
|
37
|
+
svg = ["turbo-pdf-core/svg"]
|
|
38
|
+
|
|
23
39
|
[build-dependencies]
|
|
24
40
|
napi-build = "2"
|
package/README.md
CHANGED
|
@@ -1,95 +1,211 @@
|
|
|
1
1
|
# turbo-html2pdf
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
**Turn HTML + CSS (with a Jinja templating layer) into a PDF — natively, in Rust,
|
|
4
|
+
with no headless browser.** A from-scratch document engine: templating → HTML/CSS
|
|
5
|
+
layout → automatic pagination → PDF, shipped as a tiny native addon for Node and
|
|
6
|
+
WebAssembly. No Chromium download, no 200 ms browser spin-up, deterministic output.
|
|
7
|
+
|
|
8
|
+
> npm: `turbo-html2pdf` (Node) · `turbo-html2pdf-wasm` (browser) ·
|
|
9
|
+
> `turbo-html2pdf-react` / `turbo-html2pdf-template` (authoring) · `turbo-html2pdf`
|
|
10
|
+
> on PyPI (Python). The name says exactly what it does — HTML → PDF — and avoids
|
|
11
|
+
> clashing with the unrelated "TurboPDF".
|
|
12
|
+
|
|
13
|
+
## 🌐 It generates PDFs entirely in the browser
|
|
14
|
+
|
|
15
|
+
Because the engine is pure Rust → WebAssembly (~3 MB), it runs **100% client-side**
|
|
16
|
+
— no server, no backend, no Chromium. A user pastes HTML/CSS, supplies a font as a
|
|
17
|
+
`Uint8Array`, and gets PDF bytes, all in the browser tab.
|
|
18
|
+
|
|
19
|
+
As far as we know, **no other library does HTML/CSS → PDF in the browser**: the
|
|
20
|
+
HTML→PDF tools that match its fidelity (Puppeteer, Playwright, Gotenberg, WeasyPrint,
|
|
21
|
+
wkhtmltopdf) are all **server-side** — they drive a headless browser or a native
|
|
22
|
+
binary you have to host. The libraries that *do* run in the browser (jsPDF, PDFKit,
|
|
23
|
+
react-pdf) are **draw APIs**, not HTML/CSS layout engines — you place every box by
|
|
24
|
+
hand. turbo-html2pdf is the only one that is *both* a real HTML/CSS engine *and*
|
|
25
|
+
runs with zero server.
|
|
8
26
|
|
|
9
27
|
```js
|
|
10
|
-
|
|
11
|
-
|
|
28
|
+
import init, { compile } from 'turbo-html2pdf-wasm'
|
|
29
|
+
await init() // load the ~3 MB wasm once
|
|
30
|
+
const program = compile('<h1>{{ t }}</h1>')
|
|
31
|
+
const { pdf } = program.render({ data: { t: 'Hello' }, css: 'h1{font-size:24pt}',
|
|
32
|
+
fonts: [{ data: fontBytes, family: 'Inter' }] })
|
|
33
|
+
// `pdf` is a Uint8Array — download it, no round-trip to a server
|
|
34
|
+
```
|
|
12
35
|
|
|
13
|
-
|
|
36
|
+
---
|
|
14
37
|
|
|
15
|
-
|
|
16
|
-
const program = compile('<h1>{{ title }}</h1><p>{{ body }}</p>')
|
|
38
|
+
## Why it's fast
|
|
17
39
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
now: 0, // pin the now() clock for reproducible output
|
|
24
|
-
})
|
|
25
|
-
// pdf: Buffer (starts with %PDF-1.7), diagnostics: lint[], pageCount: number
|
|
40
|
+
It does **HTML/CSS → PDF without a browser**. The incumbent way to turn HTML into a
|
|
41
|
+
PDF is to drive headless Chrome (Puppeteer/Playwright/Gotenberg) — which means
|
|
42
|
+
shipping ~200 MB of Chromium, paying a per-process spin-up, and a big memory
|
|
43
|
+
footprint. turbo-html2pdf is a native layout + PDF engine instead, so the common
|
|
44
|
+
"render one document" path is **tens to hundreds of times faster**.
|
|
26
45
|
|
|
27
|
-
|
|
46
|
+
### Benchmarks (this machine: Apple M3, 8 cores; `benches/competitive`)
|
|
28
47
|
|
|
29
|
-
|
|
30
|
-
const r = render('<p>{{ x }}</p>', { data: { x: 1 }, fonts: [font] })
|
|
31
|
-
```
|
|
48
|
+
Two scenarios, both measured:
|
|
32
49
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
50
|
+
- **Warm (server):** the realistic server path — the template's compiled `Program`
|
|
51
|
+
is reused and **fonts are parsed once and cached** (the `Fonts` handle). This is
|
|
52
|
+
the number to lead with.
|
|
53
|
+
- **Cold (one-shot):** a single render from a cold start (compile + parse fonts +
|
|
54
|
+
render), e.g. a CLI invocation.
|
|
37
55
|
|
|
38
|
-
|
|
39
|
-
|
|
56
|
+
All engines render the **same** content (same fonts, A4 geometry, same text); a
|
|
57
|
+
PNG-equivalence diff (`sim` ≈ 0.98 vs the reference) confirms the outputs are
|
|
58
|
+
comparable, so this isn't "winning by doing less".
|
|
40
59
|
|
|
41
|
-
|
|
42
|
-
|----------|------------|-------|
|
|
43
|
-
| `data` | any | interpolated into the body (`{{ field }}`, not `{{ data.field }}`) |
|
|
44
|
-
| `css` | string | author CSS; also supplies `@page` geometry (size/margins) |
|
|
45
|
-
| `fonts` | Buffer[] | font programs, registered via `FontFace::from_bytes` |
|
|
46
|
-
| `images` | Buffer[] | accepted but **not yet embedded** (see Deferred) |
|
|
47
|
-
| `meta` | DocMeta | title/author/subject/keywords/creationDate for the PDF info dict |
|
|
48
|
-
| `now` | number | Unix seconds; pins the clock for byte-deterministic output |
|
|
60
|
+
**`invoice` — a one-page document (the bread-and-butter case), median ms:**
|
|
49
61
|
|
|
50
|
-
|
|
51
|
-
|
|
62
|
+
| Engine | Warm (cached) | Cold | vs turbo (warm) | Memory | Ships a browser? |
|
|
63
|
+
|---|--:|--:|--:|--:|:--:|
|
|
64
|
+
| **turbo-html2pdf** | **1.27** | **1.48** | **1×** | **232 MB** | **no** |
|
|
65
|
+
| Playwright (Chromium) | 46.3 | 49.4 | **36× slower** | 393 MB | yes (~200 MB) |
|
|
66
|
+
| Gotenberg (Chromium) | 66.9 | 70.6 | **53× slower** | 424 MB | yes (~1 GB) |
|
|
67
|
+
| Puppeteer (Chromium) | 86.1 | 132.2 | **68× slower** | 550 MB | yes (~200 MB) |
|
|
68
|
+
| Typst (native, own DSL) | 63.8 | 62.7 | **50× slower** | 1.5 GB | no |
|
|
69
|
+
| WeasyPrint (Python) | 375.8 | 379.3 | **296× slower** | 379 MB | no |
|
|
52
70
|
|
|
53
|
-
|
|
54
|
-
* **Fatal** compile/render faults are thrown as `TurboPdfError`, carrying
|
|
55
|
-
`.code` (e.g. `"TemplateSyntax"`, `"UndefinedValue"`) and `.span`
|
|
56
|
-
(`{ line, col, byteOffset }`).
|
|
57
|
-
* **Non-fatal** lints (e.g. `"NotdefGlyph"`, `"RegionOverflow"`,
|
|
58
|
-
`"UnsupportedCss"`) are **returned** in `result.diagnostics`, never thrown.
|
|
71
|
+
**It's also the fastest on every other workload — not just the small one:**
|
|
59
72
|
|
|
60
|
-
|
|
73
|
+
| Workload | turbo-html2pdf (warm/cold) | Playwright | Puppeteer | Gotenberg | WeasyPrint | Typst |
|
|
74
|
+
|---|--:|--:|--:|--:|--:|--:|
|
|
75
|
+
| `invoice` (1 page) | **1.27 / 1.48** | 46 / 49 | 86 / 132 | 67 / 71 | 376 / 379 | 64 / 63 |
|
|
76
|
+
| `report-1k` (1 000-row table) | **119 / 130** | 187 / 170 | 384 / 429 | 204 / 204 | 2 550 / 2 547 | 220 / 221 |
|
|
77
|
+
| `legal` (prose + footnotes) | **25 / 26** | 71 / 98 | 124 / 147 | 80 / 80 | 444 / 453 | 72 / 72 |
|
|
78
|
+
| `mixed` (flex + table) | **8.6 / 9.2** | 57 / 58 | 94 / 229 | 73 / 73 | 432 / 437 | 69 / 71 |
|
|
61
79
|
|
|
62
|
-
|
|
80
|
+
Against every **HTML/CSS-to-PDF** engine, turbo-html2pdf wins on **all** workloads —
|
|
81
|
+
by 1.6× (big tables) up to ~300× (small docs) — at **lower memory** and with **no
|
|
82
|
+
browser** to install.
|
|
63
83
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
84
|
+
> **Honest footnote.** `pdfkit` (~6 ms) and `jspdf` (~2 ms) are faster on raw
|
|
85
|
+
> output, but they are **imperative draw APIs** — *you* compute and place every box;
|
|
86
|
+
> there is no HTML/CSS, no layout engine, no pagination. `@react-pdf` is a React
|
|
87
|
+
> component DSL (no HTML/CSS) and its flexbox layout melts on big tables (`report-1k`
|
|
88
|
+
> ≈ **1 300 ms**, ~10× slower than turbo). Different category from "give me HTML, get
|
|
89
|
+
> a PDF". `wkhtmltopdf` (legacy/unmaintained) was not installed.
|
|
90
|
+
|
|
91
|
+
Numbers are "on this machine", never absolutes — rerun with `cd benches/competitive
|
|
92
|
+
&& pnpm bench`. Full table + methodology in
|
|
93
|
+
[`benches/competitive/RESULTS.md`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/benches/competitive/RESULTS.md).
|
|
94
|
+
|
|
95
|
+
### Why it's *that* fast
|
|
96
|
+
|
|
97
|
+
- **No browser, no process spin-up.** It's a library call, not an IPC round-trip to
|
|
98
|
+
Chrome.
|
|
99
|
+
- **The font program is parsed once.** `ttf-parser` + `rustybuzz` faces are cached
|
|
100
|
+
in the `FontFace` (via `self_cell`) instead of re-parsed per text run; with the
|
|
101
|
+
`Fonts` warm-start handle a server parses fonts once at startup and reuses them.
|
|
102
|
+
- **Box styles resolve once per box.** Context-independent boxes cache their
|
|
103
|
+
resolved `BoxStyle` instead of re-parsing ~25 CSS properties on every layout pass.
|
|
104
|
+
- **Shaping is memoized** by run text (the measure + place passes, and repeated
|
|
105
|
+
cells, share one shape).
|
|
106
|
+
- **Deterministic.** No wall clock, no randomness, no system-font lookup — identical
|
|
107
|
+
inputs produce byte-identical PDFs.
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## Architecture
|
|
68
112
|
|
|
69
|
-
|
|
113
|
+
A template is **compiled once** into a reusable `Program`, then rendered against
|
|
114
|
+
data many times. The pipeline (`crates/turbo-pdf-core`):
|
|
70
115
|
|
|
71
|
-
```sh
|
|
72
|
-
npm run build:cargo # cargo build -p turbo-pdf-napi --release && copy-addon
|
|
73
116
|
```
|
|
117
|
+
template (HTML + Jinja + t: directives)
|
|
118
|
+
│ compile() ── parse + cache (MiniJinja)
|
|
119
|
+
▼
|
|
120
|
+
render_pages(data, css, fonts):
|
|
121
|
+
│ 1. render markup ── Jinja → HTML string (data substituted)
|
|
122
|
+
│ 2. parse ── html5ever → node tree, t: directives typed
|
|
123
|
+
│ 3. cascade + inherit ── CSS subset → ComputedStyle per node
|
|
124
|
+
│ 4. layout ── box tree → block / inline / flex (taffy) / table
|
|
125
|
+
│ → a "galley" of positioned, shaped fragments
|
|
126
|
+
│ 5. paginate ── break the galley into pages (orphans/widows,
|
|
127
|
+
│ break rules, repeated <thead>); resolve
|
|
128
|
+
│ running headers/footers + footnotes per page
|
|
129
|
+
▼ emit_pdf() ── fragments → PDF 1.7: subset + embed fonts
|
|
130
|
+
(TrueType / Type0-CFF), text, vector boxes/
|
|
131
|
+
PDF bytes borders, raster images, watermark
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Layout, font shaping (`rustybuzz`), and PDF writing (`pdf-writer` + `subsetter`) are
|
|
135
|
+
all native; `taffy` powers flexbox. The engine embeds no fonts and does no network
|
|
136
|
+
or filesystem I/O — fonts and images are supplied by the caller.
|
|
137
|
+
|
|
138
|
+
**Frontends & bindings** (`packages/`, `crates/`):
|
|
139
|
+
- `turbo-html2pdf` — Node native addon (`compile`/`render` → `Buffer`).
|
|
140
|
+
- `turbo-html2pdf-wasm` — the same engine in the browser (WebAssembly).
|
|
141
|
+
- `turbo-html2pdf-react` — author templates as React components (compiled to the
|
|
142
|
+
template string at build time, never on the render path).
|
|
143
|
+
- `turbo-html2pdf-template` — author templates with plain functions (no React).
|
|
144
|
+
|
|
145
|
+
The engine is `Send + Sync`: one compiled `Program` renders concurrently across
|
|
146
|
+
threads.
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## The DSL — HTML for documents
|
|
151
|
+
|
|
152
|
+
You write **ordinary HTML + a CSS subset**, plus a Jinja templating layer for data,
|
|
153
|
+
plus a handful of `t:` directives for paged-media features browsers can't do.
|
|
154
|
+
Full reference in [`docs/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/): [`dsl.md`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/dsl.md),
|
|
155
|
+
[`paged-media.md`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/paged-media.md), [`css-support.md`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/css-support.md),
|
|
156
|
+
[`api.md`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/api.md).
|
|
157
|
+
|
|
158
|
+
- **Templating (Jinja / MiniJinja):** `{{ value }}`, `{% for %}`, `{% if %}`,
|
|
159
|
+
includes/macros, plus document filters (`currency`, `number`, `percent`, `ordinal`,
|
|
160
|
+
`date`, `datetime`, …) and a `{% switch %}` / `{% case %}` extension.
|
|
161
|
+
- **`t:` directives** (the paged-media layer):
|
|
162
|
+
- `<t:running-header>` / `<t:running-footer>` — headers/footers repeated on every
|
|
163
|
+
page, re-evaluated per page so `{{ page.number }}` / `{{ page.total }}` (and
|
|
164
|
+
`<t:page/>` / `<t:pages/>`) are correct.
|
|
165
|
+
- `<t:footnote>` — auto-numbered footnotes; the body lands on the page where the
|
|
166
|
+
reference falls (content-driven, with a body/footnote fix-point).
|
|
167
|
+
- Pagination is automatic: **page count is an output, never an input.** `@page`
|
|
168
|
+
sets size/margins; break rules + orphans/widows are honored; `<thead>` repeats
|
|
169
|
+
when a table spans pages.
|
|
74
170
|
|
|
75
|
-
|
|
76
|
-
|
|
171
|
+
```js
|
|
172
|
+
const { compile, Fonts } = require('turbo-html2pdf')
|
|
173
|
+
const fs = require('node:fs')
|
|
77
174
|
|
|
78
|
-
|
|
175
|
+
// Warm at startup, reuse per request — the fast path.
|
|
176
|
+
const program = compile('<h1>{{ title }}</h1><p>{{ body }}</p>')
|
|
177
|
+
const fonts = Fonts.load([fs.readFileSync('Inter.ttf')]) // parse fonts ONCE
|
|
79
178
|
|
|
80
|
-
|
|
81
|
-
|
|
179
|
+
const { pdf, pageCount } = program.render({
|
|
180
|
+
data: { title: 'Hello', body: 'World' },
|
|
181
|
+
css: '@page { size: A4; margin: 20mm } h1 { font-size: 24pt }',
|
|
182
|
+
meta: { title: 'My Doc' },
|
|
183
|
+
}, fonts) // reuse the handle
|
|
184
|
+
|
|
185
|
+
fs.writeFileSync('out.pdf', pdf) // %PDF-1.7
|
|
82
186
|
```
|
|
83
187
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## Features
|
|
191
|
+
|
|
192
|
+
- HTML + CSS subset (block / inline / flexbox / tables), automatic pagination.
|
|
193
|
+
- Running headers & footers with per-page values; auto-numbered footnotes.
|
|
194
|
+
- Font subsetting + embedding (TrueType & CFF/OpenType); per-glyph fallback.
|
|
195
|
+
- Raster images (PNG/JPEG, alpha → SMask) with a sane max-size clamp.
|
|
196
|
+
- Watermarks: out-of-the-box faded diagonal **DRAFT** text (word/colour/angle
|
|
197
|
+
configurable) and background-image watermarks.
|
|
198
|
+
- Optional, off-by-default capability gates: `endnotes`, `print-color` (CMYK).
|
|
199
|
+
Planned: `xref`, `svg`, `pdf-a`, `pdf-ua` — see [`TODO/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/TODO/).
|
|
200
|
+
- Deterministic output; `Send + Sync`; no network / no system fonts.
|
|
201
|
+
|
|
202
|
+
## Status
|
|
203
|
+
|
|
204
|
+
`v0.1.2`. The core engine is complete and heavily tested (the `turbo-pdf-core`
|
|
205
|
+
crate holds 100% line coverage with a cyclomatic-complexity ≤ 5 gate). Bindings:
|
|
206
|
+
Node (napi) and WebAssembly. See [`docs/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/) for the full guide and
|
|
207
|
+
[`benches/competitive/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/benches/competitive/) for the benchmark harness.
|
|
88
208
|
|
|
89
|
-
##
|
|
209
|
+
## License
|
|
90
210
|
|
|
91
|
-
|
|
92
|
-
serializable today (it holds a live MiniJinja `Environment`). Deferred to
|
|
93
|
-
`phase10b`; omitted from the surface rather than shipped as a throwing stub.
|
|
94
|
-
* **Raster images** — the `images` param is accepted and wired through but is a
|
|
95
|
-
no-op; raster image embedding is Phase 9b.
|
|
211
|
+
MIT.
|
package/index.d.ts
CHANGED
|
@@ -43,20 +43,118 @@ export interface DocMeta {
|
|
|
43
43
|
creationDate?: number
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/** One font face: the program bytes plus the selection metadata the cascade
|
|
47
|
+
* matches `font-family` / `font-weight` / italic against. */
|
|
48
|
+
export interface FontFace {
|
|
49
|
+
/** The font program bytes (`.ttf`/`.otf`). */
|
|
50
|
+
data: Buffer
|
|
51
|
+
/** The CSS `font-family` name this face answers to. */
|
|
52
|
+
family: string
|
|
53
|
+
/** CSS `font-weight` (100..=900). Defaults to 400 (normal). */
|
|
54
|
+
weight?: number
|
|
55
|
+
/** Whether this is the italic/oblique face. Defaults to `false`. */
|
|
56
|
+
italic?: boolean
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One named raster image: a template name plus its encoded PNG/JPEG bytes.
|
|
60
|
+
* `<img src="name">` / `background-image: url(name)` embeds the matching
|
|
61
|
+
* bytes as a PDF image XObject. */
|
|
62
|
+
export interface NamedImage {
|
|
63
|
+
/** The name the template refers to this image by. */
|
|
64
|
+
name: string
|
|
65
|
+
/** The encoded image bytes (PNG or JPEG). */
|
|
66
|
+
data: Buffer
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A page watermark stamped behind the body on every page. Either a shaped-word
|
|
70
|
+
* text mark or a raster image mark (resolved by name through
|
|
71
|
+
* `RenderOptions.images`); set `image` for the raster form. */
|
|
72
|
+
export interface Watermark {
|
|
73
|
+
/** Word to stamp (text mark). Defaults to `DRAFT`. */
|
|
74
|
+
text?: string
|
|
75
|
+
/** Fill color `#rrggbb` (text mark). Defaults to gray. */
|
|
76
|
+
color?: string
|
|
77
|
+
/** Image name (image mark), resolved against `RenderOptions.images`. */
|
|
78
|
+
image?: string
|
|
79
|
+
/** Fill opacity `0.0..=1.0`. Defaults to 0.25 (text) / 1.0 (image). */
|
|
80
|
+
opacity?: number
|
|
81
|
+
/** Rotation in degrees (text mark). Defaults to 45. */
|
|
82
|
+
angle?: number
|
|
83
|
+
/** Tile the image mark across the page instead of centering it. */
|
|
84
|
+
tiled?: boolean
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Compile-time knobs: partials, missing-value policy, and include depth. */
|
|
88
|
+
export interface CompileOptions {
|
|
89
|
+
/** Partial templates by name, for `{% include %}`. */
|
|
90
|
+
partials?: Record<string, string>
|
|
91
|
+
/** `"strict"` (default) throws on a missing value; `"empty"`/`"lenient"`
|
|
92
|
+
* renders it as empty. */
|
|
93
|
+
missingPolicy?: 'strict' | 'empty' | 'lenient'
|
|
94
|
+
/** Maximum `{% include %}` nesting depth (defaults to the core default). */
|
|
95
|
+
includeMaxDepth?: number
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** AES-256 password-encryption settings. `userPassword` is required to open the
|
|
99
|
+
* document; `ownerPassword` (when set) grants full permissions. Permission bits
|
|
100
|
+
* default to all-granted; set one to `false` to clear it for a user-password
|
|
101
|
+
* open. Encrypted output is intentionally non-deterministic. */
|
|
102
|
+
export interface Encryption {
|
|
103
|
+
/** Password required to open the document. */
|
|
104
|
+
userPassword: string
|
|
105
|
+
/** Owner password granting full permissions. Defaults to the user password. */
|
|
106
|
+
ownerPassword?: string
|
|
107
|
+
/** Allow printing. Defaults to `true`. */
|
|
108
|
+
print?: boolean
|
|
109
|
+
/** Allow modifying contents. Defaults to `true`. */
|
|
110
|
+
modify?: boolean
|
|
111
|
+
/** Allow copying/extracting text and graphics. Defaults to `true`. */
|
|
112
|
+
copy?: boolean
|
|
113
|
+
/** Allow adding/modifying annotations. Defaults to `true`. */
|
|
114
|
+
annotate?: boolean
|
|
115
|
+
/** Allow filling existing form fields. Defaults to `true`. */
|
|
116
|
+
fillForms?: boolean
|
|
117
|
+
/** Allow accessibility text extraction. Defaults to `true`. */
|
|
118
|
+
accessibility?: boolean
|
|
119
|
+
/** Allow document assembly (insert/rotate/delete pages). Defaults to `true`. */
|
|
120
|
+
assemble?: boolean
|
|
121
|
+
/** Allow full-resolution printing. Defaults to `true`. */
|
|
122
|
+
highQualityPrint?: boolean
|
|
123
|
+
}
|
|
124
|
+
|
|
46
125
|
/** Options for a single render pass. All fields optional. */
|
|
47
126
|
export interface RenderOptions {
|
|
48
127
|
/** Data object interpolated into the template (`{{ data.* }}`). */
|
|
49
128
|
data?: unknown
|
|
50
129
|
/** Author CSS; also supplies `@page` geometry (size/margins). */
|
|
51
130
|
css?: string
|
|
52
|
-
/** Font
|
|
53
|
-
fonts?:
|
|
54
|
-
/**
|
|
55
|
-
images?:
|
|
131
|
+
/** Font faces, each `{ data, family, weight?, italic? }`. */
|
|
132
|
+
fonts?: FontFace[]
|
|
133
|
+
/** Named raster images embedded by template name. */
|
|
134
|
+
images?: NamedImage[]
|
|
56
135
|
/** PDF document metadata. */
|
|
57
136
|
meta?: DocMeta
|
|
137
|
+
/** A faded watermark stamped behind the body on every page. */
|
|
138
|
+
watermark?: Watermark
|
|
58
139
|
/** Pins the `now()` clock (Unix seconds) for deterministic output. */
|
|
59
140
|
now?: number
|
|
141
|
+
/** Emit PDF/A-2b archival conformance (sRGB `/OutputIntents`, XMP `pdfaid`,
|
|
142
|
+
* trailer `/ID`). Defaults to `false`. */
|
|
143
|
+
pdfA?: boolean
|
|
144
|
+
/** Emit tagged / accessible PDF/UA-1 machinery (`/StructTreeRoot`, `/MarkInfo`,
|
|
145
|
+
* per-face `/ToUnicode`, `/Lang`). Defaults to `false`. */
|
|
146
|
+
pdfUa?: boolean
|
|
147
|
+
/** Natural-language tag (RFC 3066, e.g. `en-US`) written as the catalog
|
|
148
|
+
* `/Lang`. Only meaningful with `pdfUa`. */
|
|
149
|
+
lang?: string
|
|
150
|
+
/** Emit fills in DeviceCMYK instead of DeviceRGB. Defaults to `false`. */
|
|
151
|
+
cmyk?: boolean
|
|
152
|
+
/** AES-256 password protection. Omit for an unencrypted, byte-deterministic
|
|
153
|
+
* PDF. */
|
|
154
|
+
encryption?: Encryption
|
|
155
|
+
/** Foreign PDF documents glued (page by page) AFTER the rendered pages, in
|
|
156
|
+
* order. Each entry is a complete PDF. */
|
|
157
|
+
appendPdfs?: Buffer[]
|
|
60
158
|
}
|
|
61
159
|
|
|
62
160
|
/** The result of a render. */
|
|
@@ -74,8 +172,9 @@ export interface RenderResult {
|
|
|
74
172
|
* parsed once instead of on every request. Omit to fall back to per-call
|
|
75
173
|
* `RenderOptions.fonts`. */
|
|
76
174
|
export class Fonts {
|
|
77
|
-
/** Parse `fonts`
|
|
78
|
-
|
|
175
|
+
/** Parse `fonts` (each `{ data, family, weight?, italic? }`) once into a
|
|
176
|
+
* reusable handle. Do this at startup, then reuse. */
|
|
177
|
+
static load(fonts: FontFace[]): Fonts
|
|
79
178
|
}
|
|
80
179
|
|
|
81
180
|
/** A compiled, reusable template program (thread-safe native handle). */
|
|
@@ -90,8 +189,13 @@ export interface Program {
|
|
|
90
189
|
}
|
|
91
190
|
|
|
92
191
|
/** Compile a template into a reusable {@link Program}. Throws `TurboPdfError`. */
|
|
93
|
-
export function compile(templateHtml: string, opts?:
|
|
192
|
+
export function compile(templateHtml: string, opts?: CompileOptions): Program
|
|
94
193
|
|
|
95
194
|
/** One-shot convenience: compile + render in a single call. Pass a prebuilt
|
|
96
195
|
* {@link Fonts} handle to reuse parsed fonts. */
|
|
97
196
|
export function render(templateHtml: string, opts?: RenderOptions, fonts?: Fonts): RenderResult
|
|
197
|
+
|
|
198
|
+
/** Glue one or more foreign PDF documents after `base`, page by page, returning
|
|
199
|
+
* the merged PDF. Equivalent to `RenderOptions.appendPdfs` but usable on
|
|
200
|
+
* already-emitted bytes. Throws `TurboPdfError` if any input fails to parse. */
|
|
201
|
+
export function appendPdf(base: Buffer, extras: Buffer[]): Buffer
|
package/index.js
CHANGED
|
@@ -125,5 +125,8 @@ const compile = guard((templateHtml, opts) => {
|
|
|
125
125
|
|
|
126
126
|
const render = guard((templateHtml, opts, fonts) => native.render(templateHtml, opts, fonts))
|
|
127
127
|
|
|
128
|
-
|
|
128
|
+
// Glue foreign PDFs after `base`; parse faults surface as a typed TurboPdfError.
|
|
129
|
+
const appendPdf = guard((base, extras) => native.appendPdf(base, extras))
|
|
130
|
+
|
|
131
|
+
module.exports = { compile, render, appendPdf, Fonts: native.Fonts, TurboPdfError }
|
|
129
132
|
module.exports.default = module.exports
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "turbo-html2pdf",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "Fast native HTML/CSS + Jinja templating to PDF for Node — no headless browser, no Chromium.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "index.js",
|
|
7
7
|
"types": "index.d.ts",
|
package/src/convert.rs
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
//! Pure conversions between core types and the N-API wire shapes: diagnostics,
|
|
2
|
-
//! lint codes,
|
|
2
|
+
//! lint codes, the font registry assembled from caller-supplied faces, and the
|
|
3
|
+
//! name-keyed image resolver assembled from caller-supplied rasters.
|
|
3
4
|
|
|
5
|
+
use std::collections::HashMap;
|
|
6
|
+
|
|
7
|
+
use napi::bindgen_prelude::Buffer;
|
|
4
8
|
use napi_derive::napi;
|
|
5
9
|
|
|
6
|
-
use turbo_pdf_core::{Diagnostics, FontFace, FontRegistry, Lint, LintCode};
|
|
10
|
+
use turbo_pdf_core::{Diagnostics, FontFace, FontRegistry, ImageResolver, Lint, LintCode};
|
|
7
11
|
|
|
8
12
|
/// A non-fatal diagnostic (lint) returned in the render result, never thrown.
|
|
9
13
|
#[napi(object)]
|
|
@@ -45,32 +49,74 @@ pub fn diagnostics_to_js(diags: &Diagnostics) -> Vec<JsDiagnostic> {
|
|
|
45
49
|
diags.lints.iter().map(lint_to_js).collect()
|
|
46
50
|
}
|
|
47
51
|
|
|
48
|
-
///
|
|
49
|
-
///
|
|
50
|
-
///
|
|
51
|
-
///
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
///
|
|
55
|
-
pub
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
52
|
+
/// One caller-supplied font face: the raw program bytes plus the selection
|
|
53
|
+
/// metadata (`family`, `weight`, `italic`) the cascade matches against. Without
|
|
54
|
+
/// it every face was tagged `font0/1` and author CSS `font-family`/bold could
|
|
55
|
+
/// not select a specific face.
|
|
56
|
+
#[napi(object)]
|
|
57
|
+
pub struct JsFont {
|
|
58
|
+
/// The font program bytes (`.ttf`/`.otf`).
|
|
59
|
+
pub data: Buffer,
|
|
60
|
+
/// The CSS `font-family` name this face answers to.
|
|
61
|
+
pub family: String,
|
|
62
|
+
/// The CSS `font-weight` (100..=900); defaults to 400 (normal) when omitted.
|
|
63
|
+
pub weight: Option<u16>,
|
|
64
|
+
/// Whether this is the italic/oblique face; defaults to `false`.
|
|
65
|
+
pub italic: Option<bool>,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// One caller-supplied raster image: its template name (the `<img src>` /
|
|
69
|
+
/// `background-image: url(name)` key) and its encoded PNG/JPEG bytes.
|
|
70
|
+
#[napi(object)]
|
|
71
|
+
pub struct JsImage {
|
|
72
|
+
/// The name the template refers to this image by.
|
|
73
|
+
pub name: String,
|
|
74
|
+
/// The encoded image bytes (PNG or JPEG).
|
|
75
|
+
pub data: Buffer,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// A name-keyed [`ImageResolver`] built from caller-supplied rasters. The core
|
|
79
|
+
/// layout/emit path resolves every `<img src="X">` / `background-image:url(X)`
|
|
80
|
+
/// by the name `X`; this maps that name back to the bytes the caller passed.
|
|
81
|
+
pub struct MapResolver(HashMap<String, Vec<u8>>);
|
|
82
|
+
|
|
83
|
+
impl MapResolver {
|
|
84
|
+
/// Build the resolver from the JS image list (`{ name, data }` each).
|
|
85
|
+
pub fn new(images: Vec<JsImage>) -> MapResolver {
|
|
86
|
+
let map = images
|
|
87
|
+
.into_iter()
|
|
88
|
+
.map(|img| (img.name, img.data.to_vec()))
|
|
89
|
+
.collect();
|
|
90
|
+
MapResolver(map)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// Whether any images were supplied. When empty the caller keeps the
|
|
94
|
+
/// zero-image `&NoImages` path so that render stays byte-identical.
|
|
95
|
+
pub fn is_empty(&self) -> bool {
|
|
96
|
+
self.0.is_empty()
|
|
59
97
|
}
|
|
60
|
-
reg
|
|
61
98
|
}
|
|
62
99
|
|
|
63
|
-
|
|
64
|
-
fn
|
|
65
|
-
|
|
66
|
-
if let Some(face) = FontFace::from_bytes(bytes.to_vec(), family, 400, false) {
|
|
67
|
-
reg.add(face);
|
|
100
|
+
impl ImageResolver for MapResolver {
|
|
101
|
+
fn resolve(&self, name: &str) -> Option<&[u8]> {
|
|
102
|
+
self.0.get(name).map(Vec::as_slice)
|
|
68
103
|
}
|
|
69
104
|
}
|
|
70
105
|
|
|
71
|
-
///
|
|
72
|
-
///
|
|
73
|
-
///
|
|
74
|
-
|
|
75
|
-
|
|
106
|
+
/// Build a [`FontRegistry`] from caller-supplied faces. Each face is parsed via
|
|
107
|
+
/// [`FontFace::from_bytes`] and tagged with its `family`/`weight`/`italic`, so
|
|
108
|
+
/// author CSS `font-family`/bold selects the right face via the cascade.
|
|
109
|
+
///
|
|
110
|
+
/// Unparseable blobs are skipped (the registry simply has fewer faces); the
|
|
111
|
+
/// caller sees a `NotdefGlyph` lint downstream if nothing maps a needed glyph.
|
|
112
|
+
pub fn build_registry(fonts: Vec<JsFont>) -> FontRegistry {
|
|
113
|
+
let mut reg = FontRegistry::new();
|
|
114
|
+
for font in fonts {
|
|
115
|
+
let weight = font.weight.unwrap_or(400);
|
|
116
|
+
let italic = font.italic.unwrap_or(false);
|
|
117
|
+
if let Some(face) = FontFace::from_bytes(font.data.to_vec(), font.family, weight, italic) {
|
|
118
|
+
reg.add(face);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
reg
|
|
76
122
|
}
|
package/src/errors.rs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
//! JS wrapper (`index.js`) detects the prefix and rethrows a typed
|
|
8
8
|
//! `TurboPdfError` whose `.code` and `.span` mirror this payload.
|
|
9
9
|
|
|
10
|
-
use turbo_pdf_core::{CompileError, ErrorCode, RenderError, Span};
|
|
10
|
+
use turbo_pdf_core::{AppendError, CompileError, ErrorCode, RenderError, Span};
|
|
11
11
|
|
|
12
12
|
/// Sentinel that marks a `reason` string as a structured turbo-pdf error. The JS
|
|
13
13
|
/// wrapper splits on this to recover the JSON payload.
|
|
@@ -49,3 +49,9 @@ pub fn from_compile(e: CompileError) -> napi::Error {
|
|
|
49
49
|
pub fn from_render(e: RenderError) -> napi::Error {
|
|
50
50
|
encode(e.code, &e.message, e.span)
|
|
51
51
|
}
|
|
52
|
+
|
|
53
|
+
/// Map a PDF append/merge failure to a typed N-API error. Append errors carry no
|
|
54
|
+
/// source span, so a zeroed span is used under the generic `Render` code.
|
|
55
|
+
pub fn from_append(e: AppendError) -> napi::Error {
|
|
56
|
+
encode(ErrorCode::Render, &e.to_string(), Span::default())
|
|
57
|
+
}
|
package/src/lib.rs
CHANGED
|
@@ -29,13 +29,17 @@ use serde_json::Value;
|
|
|
29
29
|
|
|
30
30
|
use std::sync::Arc;
|
|
31
31
|
|
|
32
|
+
use std::collections::HashMap;
|
|
33
|
+
|
|
32
34
|
use turbo_pdf_core::style::TokenSet;
|
|
33
35
|
use turbo_pdf_core::{
|
|
34
|
-
build_cascade, compile as core_compile,
|
|
35
|
-
CompileOptions, Diagnostics, EmitOptions,
|
|
36
|
+
append_pdfs, build_cascade, compile as core_compile, emit_pdf_with_images, render_pages,
|
|
37
|
+
style::parse_stylesheet, CompileOptions, Diagnostics, EmitOptions, Encryption, FontRegistry,
|
|
38
|
+
ImageWatermark, MissingPolicy, NoImages, Permissions, RenderInputs, Rgba, TextWatermark,
|
|
39
|
+
Watermark,
|
|
36
40
|
};
|
|
37
41
|
|
|
38
|
-
use convert::{build_registry, diagnostics_to_js, JsDiagnostic};
|
|
42
|
+
use convert::{build_registry, diagnostics_to_js, JsDiagnostic, JsFont, JsImage, MapResolver};
|
|
39
43
|
|
|
40
44
|
/// Options for a single render pass. All fields are optional; omit what you do
|
|
41
45
|
/// not need. `data` defaults to `null`, `css` to empty, `fonts`/`images` to empty.
|
|
@@ -46,14 +50,116 @@ pub struct RenderOptions {
|
|
|
46
50
|
pub data: Option<Value>,
|
|
47
51
|
/// Author CSS. Also feeds `@page` geometry (size/margins) via the parser.
|
|
48
52
|
pub css: Option<String>,
|
|
49
|
-
/// Font
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
+
/// Font faces, each `{ data, family, weight?, italic? }`. The `family`/weight
|
|
54
|
+
/// drive CSS `font-family`/bold selection.
|
|
55
|
+
pub fonts: Option<Vec<JsFont>>,
|
|
56
|
+
/// Named raster images, each `{ name, data }`. A `<img src="name">` or
|
|
57
|
+
/// `background-image: url(name)` in the template embeds the matching bytes.
|
|
58
|
+
pub images: Option<Vec<JsImage>>,
|
|
53
59
|
/// PDF document metadata written to the info dictionary.
|
|
54
60
|
pub meta: Option<DocMeta>,
|
|
61
|
+
/// A faded watermark stamped behind the body on every page. Either a text
|
|
62
|
+
/// mark (`{ text?, color?, opacity?, angle? }`) or an image mark
|
|
63
|
+
/// (`{ image, opacity?, tiled? }`, resolved against `images` by name).
|
|
64
|
+
pub watermark: Option<JsWatermark>,
|
|
55
65
|
/// Pins the `now()` clock (Unix seconds) for deterministic output.
|
|
56
66
|
pub now: Option<i64>,
|
|
67
|
+
/// Emit PDF/A-2b archival conformance for this render (sRGB `/OutputIntents`,
|
|
68
|
+
/// an XMP `pdfaid` packet, a trailer `/ID`). Defaults to `false`.
|
|
69
|
+
pub pdf_a: Option<bool>,
|
|
70
|
+
/// Emit tagged / accessible PDF/UA-1 machinery for this render
|
|
71
|
+
/// (`/StructTreeRoot`, `/MarkInfo`, per-face `/ToUnicode`, `/Lang`).
|
|
72
|
+
/// Defaults to `false`.
|
|
73
|
+
pub pdf_ua: Option<bool>,
|
|
74
|
+
/// The document's natural-language tag (RFC 3066, e.g. `en-US`), written as
|
|
75
|
+
/// the catalog `/Lang` for tagged PDF. Only meaningful with `pdfUa`.
|
|
76
|
+
pub lang: Option<String>,
|
|
77
|
+
/// Emit fills in DeviceCMYK instead of DeviceRGB for print workflows.
|
|
78
|
+
/// Defaults to `false`.
|
|
79
|
+
pub cmyk: Option<bool>,
|
|
80
|
+
/// AES-256 password protection. Set `userPassword` (required to open) and
|
|
81
|
+
/// optionally `ownerPassword`. Encrypted output is intentionally
|
|
82
|
+
/// non-deterministic. Omit for an unencrypted, byte-deterministic PDF.
|
|
83
|
+
pub encryption: Option<JsEncryption>,
|
|
84
|
+
/// Foreign PDF blobs glued (page by page) AFTER the rendered pages, in order.
|
|
85
|
+
/// Each entry is a complete PDF document. Omit to append nothing.
|
|
86
|
+
pub append_pdfs: Option<Vec<Buffer>>,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// AES-256 password-encryption settings. `userPassword` is required to open the
|
|
90
|
+
/// document; `ownerPassword` (when set) grants full permissions. Permission bits
|
|
91
|
+
/// default to all-granted; set a field to `false` to clear it for a user-password
|
|
92
|
+
/// open.
|
|
93
|
+
#[napi(object)]
|
|
94
|
+
pub struct JsEncryption {
|
|
95
|
+
/// Password required to open the document (required).
|
|
96
|
+
pub user_password: String,
|
|
97
|
+
/// Owner password granting full permissions. Defaults to the user password.
|
|
98
|
+
pub owner_password: Option<String>,
|
|
99
|
+
/// Allow printing. Defaults to `true`.
|
|
100
|
+
pub print: Option<bool>,
|
|
101
|
+
/// Allow modifying contents. Defaults to `true`.
|
|
102
|
+
pub modify: Option<bool>,
|
|
103
|
+
/// Allow copying/extracting text and graphics. Defaults to `true`.
|
|
104
|
+
pub copy: Option<bool>,
|
|
105
|
+
/// Allow adding/modifying annotations. Defaults to `true`.
|
|
106
|
+
pub annotate: Option<bool>,
|
|
107
|
+
/// Allow filling existing form fields. Defaults to `true`.
|
|
108
|
+
pub fill_forms: Option<bool>,
|
|
109
|
+
/// Allow accessibility text extraction. Defaults to `true`.
|
|
110
|
+
pub accessibility: Option<bool>,
|
|
111
|
+
/// Allow document assembly (insert/rotate/delete pages). Defaults to `true`.
|
|
112
|
+
pub assemble: Option<bool>,
|
|
113
|
+
/// Allow full-resolution printing. Defaults to `true`.
|
|
114
|
+
pub high_quality_print: Option<bool>,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
impl JsEncryption {
|
|
118
|
+
/// Lower into the core [`Encryption`], applying permission overrides onto the
|
|
119
|
+
/// all-granted default.
|
|
120
|
+
fn into_core(self) -> Encryption {
|
|
121
|
+
let mut perms = Permissions::all();
|
|
122
|
+
apply_perm(&mut perms.print, self.print);
|
|
123
|
+
apply_perm(&mut perms.modify, self.modify);
|
|
124
|
+
apply_perm(&mut perms.copy, self.copy);
|
|
125
|
+
apply_perm(&mut perms.annotate, self.annotate);
|
|
126
|
+
apply_perm(&mut perms.fill_forms, self.fill_forms);
|
|
127
|
+
apply_perm(&mut perms.accessibility, self.accessibility);
|
|
128
|
+
apply_perm(&mut perms.assemble, self.assemble);
|
|
129
|
+
apply_perm(&mut perms.high_quality_print, self.high_quality_print);
|
|
130
|
+
Encryption {
|
|
131
|
+
user_password: self.user_password,
|
|
132
|
+
owner_password: self.owner_password,
|
|
133
|
+
permissions: perms,
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// Apply an optional permission override onto a slot (no-op when `None`).
|
|
139
|
+
fn apply_perm(slot: &mut bool, over: Option<bool>) {
|
|
140
|
+
if let Some(v) = over {
|
|
141
|
+
*slot = v;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// A page watermark. Set `text` for a shaped-word mark (defaulting to `DRAFT`
|
|
146
|
+
/// when omitted) or `image` for a raster mark resolved by name through `images`;
|
|
147
|
+
/// the two are mutually exclusive (`image` wins if both are set). All other
|
|
148
|
+
/// fields are optional and take the core's `DRAFT` preset defaults.
|
|
149
|
+
#[napi(object)]
|
|
150
|
+
pub struct JsWatermark {
|
|
151
|
+
/// The word to stamp (text mark). Defaults to `DRAFT` when omitted.
|
|
152
|
+
pub text: Option<String>,
|
|
153
|
+
/// Fill color `#rrggbb` for the text mark. Defaults to gray.
|
|
154
|
+
pub color: Option<String>,
|
|
155
|
+
/// The image name (image mark), resolved against `RenderOptions.images`.
|
|
156
|
+
pub image: Option<String>,
|
|
157
|
+
/// Fill opacity `0.0..=1.0`. Defaults to the preset (0.25 text / 1.0 image).
|
|
158
|
+
pub opacity: Option<f64>,
|
|
159
|
+
/// Rotation in degrees for the text mark. Defaults to 45.
|
|
160
|
+
pub angle: Option<f64>,
|
|
161
|
+
/// Tile the image mark across the page instead of centering it.
|
|
162
|
+
pub tiled: Option<bool>,
|
|
57
163
|
}
|
|
58
164
|
|
|
59
165
|
/// PDF document-info metadata. Every field is optional and omitted when unset.
|
|
@@ -90,13 +196,12 @@ pub struct Fonts {
|
|
|
90
196
|
|
|
91
197
|
#[napi]
|
|
92
198
|
impl Fonts {
|
|
93
|
-
/// Parse `fonts` (
|
|
94
|
-
/// handle. Do this at startup, then reuse it across renders.
|
|
199
|
+
/// Parse `fonts` (each `{ data, family, weight?, italic? }`) once into a
|
|
200
|
+
/// reusable handle. Do this at startup, then reuse it across renders.
|
|
95
201
|
#[napi(factory)]
|
|
96
|
-
pub fn load(fonts: Vec<
|
|
97
|
-
let blobs: Vec<Vec<u8>> = fonts.iter().map(|b| b.to_vec()).collect();
|
|
202
|
+
pub fn load(fonts: Vec<JsFont>) -> Fonts {
|
|
98
203
|
Fonts {
|
|
99
|
-
inner: Arc::new(build_registry(
|
|
204
|
+
inner: Arc::new(build_registry(fonts)),
|
|
100
205
|
}
|
|
101
206
|
}
|
|
102
207
|
}
|
|
@@ -139,16 +244,49 @@ impl Program {
|
|
|
139
244
|
// Compile is cheap enough that callers re-compile from source in the interim.
|
|
140
245
|
}
|
|
141
246
|
|
|
142
|
-
/// Compile `template_html` into a reusable [`Program`]. `
|
|
143
|
-
///
|
|
144
|
-
///
|
|
247
|
+
/// Compile `template_html` into a reusable [`Program`]. `opts` is the optional
|
|
248
|
+
/// `{ partials?, missingPolicy?, includeMaxDepth? }` object (mirrors the wasm
|
|
249
|
+
/// binding); an unknown/omitted field falls back to the [`CompileOptions`]
|
|
250
|
+
/// default.
|
|
145
251
|
#[napi]
|
|
146
|
-
pub fn compile(template_html: String,
|
|
252
|
+
pub fn compile(template_html: String, opts: Option<Value>) -> napi::Result<Program> {
|
|
147
253
|
let (program, _diags) =
|
|
148
|
-
core_compile(&template_html, &
|
|
254
|
+
core_compile(&template_html, &compile_options(opts)).map_err(errors::from_compile)?;
|
|
149
255
|
Ok(Program { inner: program })
|
|
150
256
|
}
|
|
151
257
|
|
|
258
|
+
/// The JS shape of the compile options: `{ partials?, missingPolicy?,
|
|
259
|
+
/// includeMaxDepth? }`. Every field is optional and defaulted.
|
|
260
|
+
#[derive(Default, serde::Deserialize)]
|
|
261
|
+
#[serde(rename_all = "camelCase", default)]
|
|
262
|
+
struct JsCompileOptions {
|
|
263
|
+
partials: HashMap<String, String>,
|
|
264
|
+
missing_policy: Option<String>,
|
|
265
|
+
include_max_depth: Option<u32>,
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/// Lower the optional JS compile-options value into core [`CompileOptions`],
|
|
269
|
+
/// treating a malformed object as the default rather than erroring.
|
|
270
|
+
fn compile_options(opts: Option<Value>) -> CompileOptions {
|
|
271
|
+
let js: JsCompileOptions = opts
|
|
272
|
+
.and_then(|v| serde_json::from_value(v).ok())
|
|
273
|
+
.unwrap_or_default();
|
|
274
|
+
let defaults = CompileOptions::default();
|
|
275
|
+
CompileOptions {
|
|
276
|
+
partials: js.partials,
|
|
277
|
+
missing_policy: parse_missing_policy(js.missing_policy.as_deref()),
|
|
278
|
+
include_max_depth: js.include_max_depth.unwrap_or(defaults.include_max_depth),
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/// Map a `missingPolicy` string to the core enum; unknown/absent stays strict.
|
|
283
|
+
fn parse_missing_policy(name: Option<&str>) -> MissingPolicy {
|
|
284
|
+
match name {
|
|
285
|
+
Some("empty") | Some("lenient") => MissingPolicy::Empty,
|
|
286
|
+
_ => MissingPolicy::Strict,
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
152
290
|
/// One-shot convenience: compile `template_html` and render it in a single call.
|
|
153
291
|
#[napi(js_name = "render")]
|
|
154
292
|
pub fn render_oneshot(
|
|
@@ -161,6 +299,17 @@ pub fn render_oneshot(
|
|
|
161
299
|
run_pipeline(&program, opts.unwrap_or_default(), fonts)
|
|
162
300
|
}
|
|
163
301
|
|
|
302
|
+
/// Glue one or more foreign PDF documents after `base`, page by page, returning
|
|
303
|
+
/// the merged PDF. Equivalent to `RenderOptions.appendPdfs` but usable on
|
|
304
|
+
/// already-emitted bytes. Throws `TurboPdfError` if any input fails to parse or
|
|
305
|
+
/// the inputs together contain no pages.
|
|
306
|
+
#[napi]
|
|
307
|
+
pub fn append_pdf(base: Buffer, extras: Vec<Buffer>) -> napi::Result<Buffer> {
|
|
308
|
+
let refs: Vec<&[u8]> = extras.iter().map(|b| b.as_ref()).collect();
|
|
309
|
+
let merged = append_pdfs(base.as_ref(), &refs).map_err(errors::from_append)?;
|
|
310
|
+
Ok(merged.into())
|
|
311
|
+
}
|
|
312
|
+
|
|
164
313
|
/// The shared render pipeline: cascade + geometry + fonts -> `render_pages` ->
|
|
165
314
|
/// `emit_pdf`. Diagnostics flow into the result; only fatal faults throw.
|
|
166
315
|
fn run_pipeline(
|
|
@@ -178,55 +327,149 @@ fn run_pipeline(
|
|
|
178
327
|
let registry: &FontRegistry = match fonts {
|
|
179
328
|
Some(handle) => &handle.inner,
|
|
180
329
|
None => {
|
|
181
|
-
owned_registry = build_registry(
|
|
330
|
+
owned_registry = build_registry(opts.fonts.unwrap_or_default());
|
|
182
331
|
&owned_registry
|
|
183
332
|
}
|
|
184
333
|
};
|
|
185
334
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
cascade: &cascade,
|
|
190
|
-
at_rules: &at_rules,
|
|
191
|
-
fonts: registry,
|
|
192
|
-
// Image embedding (§7.4) is not yet surfaced through the Node binding; a
|
|
193
|
-
// future option will supply a resolver here. No images for now.
|
|
194
|
-
images: &turbo_pdf_core::NoImages,
|
|
195
|
-
now: opts.now,
|
|
196
|
-
};
|
|
335
|
+
// Build the name-keyed image resolver from this call's images. When empty we
|
|
336
|
+
// keep the `&NoImages` path so a no-image render stays byte-identical.
|
|
337
|
+
let resolver = MapResolver::new(opts.images.unwrap_or_default());
|
|
197
338
|
|
|
198
339
|
let mut diags = Diagnostics::default();
|
|
199
|
-
let
|
|
200
|
-
|
|
340
|
+
let conformance = Conformance {
|
|
341
|
+
pdf_a: opts.pdf_a.unwrap_or(false),
|
|
342
|
+
pdf_ua: opts.pdf_ua.unwrap_or(false),
|
|
343
|
+
lang: opts.lang,
|
|
344
|
+
cmyk: opts.cmyk.unwrap_or(false),
|
|
345
|
+
encryption: opts.encryption.map(JsEncryption::into_core),
|
|
346
|
+
};
|
|
347
|
+
let append = opts.append_pdfs.unwrap_or_default();
|
|
348
|
+
let emit = emit_options(opts.meta, opts.watermark, registry, conformance);
|
|
349
|
+
|
|
350
|
+
let pages = {
|
|
351
|
+
let inputs = RenderInputs {
|
|
352
|
+
program,
|
|
353
|
+
data: &data,
|
|
354
|
+
cascade: &cascade,
|
|
355
|
+
at_rules: &at_rules,
|
|
356
|
+
fonts: registry,
|
|
357
|
+
images: image_source(&resolver),
|
|
358
|
+
now: opts.now,
|
|
359
|
+
};
|
|
360
|
+
render_pages(&inputs, &mut diags).map_err(errors::from_render)?
|
|
361
|
+
};
|
|
362
|
+
let page_count = pages.len() as u32;
|
|
363
|
+
let pdf = emit_pdf_with_images(&pages, &emit, image_source(&resolver));
|
|
364
|
+
let pdf = apply_append(pdf, &append)?;
|
|
201
365
|
|
|
202
366
|
Ok(RenderResult {
|
|
203
367
|
pdf: pdf.into(),
|
|
204
368
|
diagnostics: diagnostics_to_js(&diags),
|
|
205
|
-
page_count
|
|
369
|
+
page_count,
|
|
206
370
|
})
|
|
207
371
|
}
|
|
208
372
|
|
|
209
|
-
///
|
|
210
|
-
///
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
///
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
373
|
+
/// The per-render conformance / encryption toggles lowered to core types,
|
|
374
|
+
/// extracted from [`RenderOptions`] before it is partly consumed.
|
|
375
|
+
struct Conformance {
|
|
376
|
+
pdf_a: bool,
|
|
377
|
+
pdf_ua: bool,
|
|
378
|
+
lang: Option<String>,
|
|
379
|
+
cmyk: bool,
|
|
380
|
+
encryption: Option<Encryption>,
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/// Glue each foreign PDF blob after the rendered `pdf`, page by page. A parse
|
|
384
|
+
/// failure on any input becomes a fatal `TurboPdfError`. With no extras the input
|
|
385
|
+
/// passes through unchanged.
|
|
386
|
+
fn apply_append(pdf: Vec<u8>, extras: &[Buffer]) -> napi::Result<Vec<u8>> {
|
|
387
|
+
if extras.is_empty() {
|
|
388
|
+
return Ok(pdf);
|
|
389
|
+
}
|
|
390
|
+
let refs: Vec<&[u8]> = extras.iter().map(|b| b.as_ref()).collect();
|
|
391
|
+
append_pdfs(&pdf, &refs).map_err(errors::from_append)
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/// The image source for layout/emit: the caller's resolver when it carries
|
|
395
|
+
/// images, else the zero-image [`NoImages`] so the no-image path is identical.
|
|
396
|
+
fn image_source(resolver: &MapResolver) -> &dyn turbo_pdf_core::ImageResolver {
|
|
397
|
+
if resolver.is_empty() {
|
|
398
|
+
&NoImages
|
|
399
|
+
} else {
|
|
400
|
+
resolver
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/// Translate optional [`DocMeta`] + watermark into core [`EmitOptions`]. A text
|
|
405
|
+
/// watermark is shaped with the registry's first face; with no face the text
|
|
406
|
+
/// mark is dropped (nothing to shape with).
|
|
407
|
+
fn emit_options(
|
|
408
|
+
meta: Option<DocMeta>,
|
|
409
|
+
watermark: Option<JsWatermark>,
|
|
410
|
+
registry: &FontRegistry,
|
|
411
|
+
conformance: Conformance,
|
|
412
|
+
) -> EmitOptions {
|
|
413
|
+
let mut opts = EmitOptions::default();
|
|
414
|
+
if let Some(m) = meta {
|
|
415
|
+
opts.title = m.title;
|
|
416
|
+
opts.author = m.author;
|
|
417
|
+
opts.subject = m.subject;
|
|
418
|
+
opts.keywords = m.keywords;
|
|
419
|
+
opts.creation_date = m.creation_date;
|
|
420
|
+
}
|
|
421
|
+
opts.watermark = watermark.and_then(|w| build_watermark(w, registry));
|
|
422
|
+
opts.cmyk = conformance.cmyk;
|
|
423
|
+
opts.pdf_a = conformance.pdf_a;
|
|
424
|
+
opts.pdf_ua = conformance.pdf_ua;
|
|
425
|
+
opts.lang = conformance.lang;
|
|
426
|
+
opts.encryption = conformance.encryption;
|
|
427
|
+
opts
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/// Build a core [`Watermark`] from the JS shape. `image` (if set) makes a raster
|
|
431
|
+
/// mark; otherwise a text mark seeded from the `DRAFT` preset of the registry's
|
|
432
|
+
/// first face. Returns `None` for a text mark with no face available.
|
|
433
|
+
fn build_watermark(w: JsWatermark, registry: &FontRegistry) -> Option<Watermark> {
|
|
434
|
+
if let Some(name) = w.image {
|
|
435
|
+
return Some(Watermark::Image(ImageWatermark {
|
|
436
|
+
name,
|
|
437
|
+
opacity: w.opacity.map(|o| o as f32).unwrap_or(1.0),
|
|
438
|
+
tiled: w.tiled.unwrap_or(false),
|
|
439
|
+
}));
|
|
440
|
+
}
|
|
441
|
+
let face = registry.select(&[], 400, false)?.clone();
|
|
442
|
+
let mut mark = TextWatermark::draft(face);
|
|
443
|
+
apply_text_overrides(&mut mark, w);
|
|
444
|
+
Some(Watermark::Text(Box::new(mark)))
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/// Apply the optional JS overrides onto a preset text watermark, leaving any
|
|
448
|
+
/// omitted field at its `DRAFT`-preset default.
|
|
449
|
+
fn apply_text_overrides(mark: &mut TextWatermark, w: JsWatermark) {
|
|
450
|
+
if let Some(text) = w.text {
|
|
451
|
+
mark.text = text;
|
|
452
|
+
}
|
|
453
|
+
if let Some(color) = w.color.as_deref().and_then(parse_hex_color) {
|
|
454
|
+
mark.color = color;
|
|
455
|
+
}
|
|
456
|
+
if let Some(opacity) = w.opacity {
|
|
457
|
+
mark.opacity = opacity as f32;
|
|
458
|
+
}
|
|
459
|
+
if let Some(angle) = w.angle {
|
|
460
|
+
mark.angle_deg = angle as f32;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/// Parse a `#rrggbb` (or `rrggbb`) hex color into an opaque [`Rgba`]. Returns
|
|
465
|
+
/// `None` for any malformed string, leaving the preset color in place.
|
|
466
|
+
fn parse_hex_color(s: &str) -> Option<Rgba> {
|
|
467
|
+
let hex = s.strip_prefix('#').unwrap_or(s);
|
|
468
|
+
if hex.len() != 6 {
|
|
469
|
+
return None;
|
|
231
470
|
}
|
|
471
|
+
let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
|
|
472
|
+
let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
|
|
473
|
+
let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
|
|
474
|
+
Some(Rgba::new(r, g, b, 255))
|
|
232
475
|
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|