@zumer/snapdom-pdf 1.0.0 → 1.0.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # PDF changes
2
2
 
3
+ ## 1.0.1
4
+
5
+ > 9 November 2026
6
+
7
+ **Fixes**
8
+
9
+ - **pdf:** place the text layer correctly on hidpi screens [`05d87aa`](https://github.com/zumerlab/snapdom/commit/05d87aa81de0e03dd7c76e782626b629851b81ee)
10
+ - **pdf:** rasterize a capture enlarged to the paper at its printed size [`20add63`](https://github.com/zumerlab/snapdom/commit/20add63a27d31da61da1911001e1461ba4b7b99d)
11
+
12
+ **Refactoring**
13
+
14
+ - **pdf:** drop two locals nothing reads [`f49f5c1`](https://github.com/zumerlab/snapdom/commit/f49f5c1c050b83687d5a79365fca9ab4d280e4f4)
15
+
16
+ **Docs**
17
+
18
+ - **pdf:** rewrite the reference in plain words, capture the demo at dpr 2 [`b79e178`](https://github.com/zumerlab/snapdom/commit/b79e178f3f5fcd8b23c224ade730df830cf34d4a)
19
+ - **pdf:** fold the reference into the README [`e9f3a4f`](https://github.com/zumerlab/snapdom/commit/e9f3a4f8e0cde00e3a1bdab5f9ade5d06229346c)
20
+ - **site:** point the demos and docs at the published packages [`c57b2b3`](https://github.com/zumerlab/snapdom/commit/c57b2b38f3b57fc51e0cb7f64f8207ddad9421ef)
21
+
3
22
  ## 1.0.0
4
23
 
5
24
  > 9 November 2026
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![NPM version](https://img.shields.io/npm/v/@zumer/snapdom-pdf?style=flat-square&label=PDF)](https://www.npmjs.com/package/@zumer/snapdom-pdf)
4
4
  [![Core version](https://img.shields.io/npm/v/@zumer/snapdom?style=flat-square&label=SnapDOM)](https://www.npmjs.com/package/@zumer/snapdom)
5
5
 
6
- PDF export for [SnapDOM](https://snapdom.dev/): `pdf()` adds `toPdf()` to a capture, returning a PDF Blob with the capture's appearance, selectable and searchable text, links, pagination, repeated table headers, Unicode, transparency and optional form fields. Export options also cover headers, footers, metadata, tagging and encryption. MIT licensed. Landing page and live demo: [snapdom.dev/plugins/pdf](https://snapdom.dev/plugins/pdf/).
6
+ PDF export for [SnapDOM](https://snapdom.dev/): `pdf()` adds `toPdf()` to a capture and turns it into a real PDF, with the capture's appearance, selectable and searchable text, links, bookmarks, pages, repeated table headers and fillable fields. Headers, footers, metadata, tagging and encryption are export options. Everything runs in the browser and nothing is uploaded. MIT licensed. Landing page and live demo: [snapdom.dev/plugins/pdf](https://snapdom.dev/plugins/pdf/).
7
7
 
8
8
  ## Install
9
9
 
@@ -11,20 +11,207 @@ PDF export for [SnapDOM](https://snapdom.dev/): `pdf()` adds `toPdf()` to a capt
11
11
  npm install @zumer/snapdom@latest @zumer/snapdom-pdf@latest
12
12
  ```
13
13
 
14
- Requires SnapDOM 3.4.0 or newer within 3.x. Up to SnapDOM plugins 4.x the same exporter shipped as `@zumer/snapdom-plugins/pdf`; only the import changes.
14
+ It needs SnapDOM 3.4.0 or newer within 3.x. Up to SnapDOM plugins 4.x the same exporter shipped as `@zumer/snapdom-plugins/pdf`; only the import changes.
15
15
 
16
- ## Usage
16
+ Without a bundler, map both packages in an import map and serve the whole `@zumer/snapdom-pdf` folder, because its `index.js` imports files from `src/`.
17
+
18
+ ```html
19
+ <script type="importmap">
20
+ {
21
+ "imports": {
22
+ "@zumer/snapdom": "/vendor/snapdom.mjs",
23
+ "@zumer/snapdom-pdf": "/vendor/snapdom-pdf/index.js"
24
+ }
25
+ }
26
+ </script>
27
+ ```
28
+
29
+ ## Quick start
30
+
31
+ ```js
32
+ import { snapdom } from '@zumer/snapdom'
33
+ import { pdf } from '@zumer/snapdom-pdf'
34
+
35
+ snapdom.plugins(pdf())
36
+
37
+ const shot = await snapdom(document.querySelector('#report'))
38
+ const blob = await shot.toPdf({ page: 'a4', download: 'report.pdf' })
39
+ ```
40
+
41
+ Register the plugin before you capture. A capture made without it has no `toPdf()`. To use it on one capture only, pass it there: `snapdom(el, { plugins: [pdf()] })`.
42
+
43
+ `toPdf()` returns a PDF `Blob`. `download` also saves the file. `shot.to('pdf', options)` does the same as `toPdf(options)`. The types are in [index.d.ts](index.d.ts).
44
+
45
+ ## Options on pdf()
46
+
47
+ Five options decide what the plugin reads from the page while SnapDOM captures it, so they go on `pdf()` and not on `toPdf()`.
48
+
49
+ | Option | Default | What it does |
50
+ |---|---|---|
51
+ | `formValues` | `true` | Include the values typed in inputs and the selected option. Passwords become bullets. |
52
+ | `shadow` | `true` | Read text inside open shadow roots. |
53
+ | `breakAvoid` | `true` | Measure blocks so page breaks avoid cutting them. |
54
+ | `outline` | `true` | Turn headings into bookmarks. A selector string picks other elements; `false` turns it off. |
55
+ | `forms` | `true` | Measure form controls so the PDF can have fillable fields. |
56
+
57
+ Every other option works in either place. On `pdf()` it becomes the default for every export; in `toPdf()` it applies to that export and wins.
58
+
59
+ ## Pages
60
+
61
+ | Option | Default | What it does |
62
+ |---|---|---|
63
+ | `page` | `'fit'` | `'fit'` makes one page the size of the capture. Paper sizes: `'a3'` to `'a6'`, `'b4'`, `'b5'`, `'letter'`, `'legal'`, `'tabloid'`, `'executive'`, or `[width, height]` in points. |
64
+ | `orientation` | `'portrait'` | `'portrait'` or `'landscape'`. |
65
+ | `margin` | `24` | Margin on every side, in points. |
66
+ | `repeatHeaders` | `true` | Repeat a table's `<thead>` on each page the table continues to. |
67
+
68
+ Page breaks avoid table rows, list items, figures, quotes, images and anything with `break-inside: avoid`. CSS page breaks are respected. A block taller than a page still has to split.
69
+
70
+ ## Image and file size
71
+
72
+ What you see in the PDF is an image of the capture, with invisible text on top so it can be selected and searched.
73
+
74
+ | Option | Default | What it does |
75
+ |---|---|---|
76
+ | `image` | `true` | Draw the captured image. `false` makes a PDF with text only. |
77
+ | `codec` | `'auto'` | Try JPEG and lossless and keep the smaller file, per image. `'jpeg'` or `'flate'` forces one. |
78
+ | `quality` | `0.92` | JPEG quality. It only matters when JPEG wins, which on normal pages is rare. |
79
+ | `backgroundColor` | none | Fill transparent areas with a colour. Usually makes the file smaller. |
80
+
81
+ Sharpness and size come from the capture: `snapdom(el, { scale, dpr })`. Both multiply the image's pixels and leave the page layout alone. The image keeps that many pixels per CSS pixel at the size it is printed. A capture enlarged to fill the paper is drawn at the enlarged size, so it stays as sharp as on screen. `dpr` defaults to the screen of the machine that exports, so set it, for example to `2`, to get the same file everywhere.
82
+
83
+ ## Text and links
84
+
85
+ | Option | Default | What it does |
86
+ |---|---|---|
87
+ | `text` | `true` | Add the invisible text layer, so the text can be selected, searched and copied. |
88
+ | `links` | `true` | Make links clickable. Same-page anchors jump inside the PDF. |
89
+ | `debugText` | `false` | Paint the text layer red, to check where it sits. |
90
+
91
+ Links work for `http:`, `https:`, `mailto:` and `tel:`. Any other link is left out with a warning.
92
+
93
+ > Covering something with a box or a blur hides the pixels, not the text: it can still be selected in the PDF. To keep data out, remove or replace it before the capture.
94
+
95
+ ## Fonts and sharp text
96
+
97
+ | Option | Default | What it does |
98
+ |---|---|---|
99
+ | `embedFonts` | `true` | Embed the page's web fonts, only the letters the document uses. `'full'` embeds whole fonts; `false` none. |
100
+ | `vectorText` | `false` | Draw the text as real letters instead of pixels: sharp at any zoom. |
101
+
102
+ The PDF can only embed fonts the capture carries, so capture with `snapdom(el, { embedFonts: true })`. System fonts have no file to embed. Copying text works the same with or without embedded fonts.
103
+
104
+ `vectorText` needs embedded fonts. Right-to-left and complex scripts stay as image. With `image: false` it gives a very small text-only PDF, without borders, backgrounds or pictures.
105
+
106
+ ## Bookmarks and accessibility
107
+
108
+ | Option | Default | What it does |
109
+ |---|---|---|
110
+ | `outline` | `true` | Bookmarks from headings. Set it on `pdf()`. |
111
+ | `tagged` | `true` | Tag headings, paragraphs, lists, tables and figures for screen readers. |
112
+ | `lang` | from the page | Document language, for example `'en'` or `'es-MX'`. |
113
+
114
+ The PDF is marked accessible (PDF/UA-1) only when it qualifies: every font embedded, a language, a `meta.title`, alt text on every image and `fields: false`. There is no option to force it. When something is missing, the report says what.
115
+
116
+ ## Fillable forms
117
+
118
+ | Option | Default | What it does |
119
+ |---|---|---|
120
+ | `fields` | `true` | Turn form controls into fields you can fill in the PDF. `false` keeps their values as plain text. |
121
+
122
+ Text inputs, textareas, checkboxes, radio buttons and selects become fields with their name, value and label. Read-only, disabled, required and maxlength carry over. Password fields are written empty. Buttons, sliders, colour pickers and file inputs stay as image. The PDF never contains scripts or submit actions.
123
+
124
+ ## Header, footer and page numbers
125
+
126
+ | Option | Default | What it does |
127
+ |---|---|---|
128
+ | `header` | none | Text, a function, `{ left, center, right, size, font, color, rule, gap }` or an element. |
129
+ | `footer` | none | The same, at the bottom. |
130
+ | `pageNumbers` | `false` | `true` writes "1 / 4". `{ format, align, size, font, color }` changes it. |
17
131
 
18
132
  ```js
19
- import { snapdom } from '@zumer/snapdom';
20
- import { pdf } from '@zumer/snapdom-pdf';
133
+ await shot.toPdf({
134
+ page: 'a4',
135
+ header: { left: 'North Studio', right: 'Delivery report' },
136
+ pageNumbers: { format: (page, pages) => `Page ${page} of ${pages}` },
137
+ })
138
+ ```
139
+
140
+ These need a paper size and do nothing on `page: 'fit'`. Text is real PDF text. An element is captured as an image, so its text cannot be selected.
21
141
 
22
- const result = await snapdom(element, { plugins: [pdf()] });
23
- const blob = await result.toPdf({ page: 'a4', margin: 36 });
24
- await result.toPdf({ page: 'letter', download: 'report.pdf' });
142
+ ## Cover, contents, back page and watermark
143
+
144
+ | Option | Default | What it does |
145
+ |---|---|---|
146
+ | `cover` | none | An element captured as the first page. |
147
+ | `toc` | none | A table of contents from the headings. `true`, a title, or `{ title, levels, size, font, indent, dots, label, color, leaderColor }`. |
148
+ | `back` | none | An element captured as the last page. |
149
+ | `watermark` | none | Text or an element over every page. `{ text, opacity, angle, size, font, color }` or `{ element, opacity, angle, fit }`. |
150
+
151
+ Cover, contents and back page need a paper size. The watermark also works on `page: 'fit'`.
152
+
153
+ ## Metadata
154
+
155
+ | Option | Default | What it does |
156
+ |---|---|---|
157
+ | `meta` | none | `{ title, author, subject, keywords, creator, created, modified }`. Viewers show the title instead of the file name. |
158
+
159
+ Dates are written only when you pass them. Pass `new Date()` when you want today. The same page exported twice gives the same file, byte for byte.
160
+
161
+ ## Password
162
+
163
+ ```js
164
+ await shot.toPdf({
165
+ page: 'a4',
166
+ encrypt: { userPassword: 'ada-1815', ownerPassword: 'owner-key' },
167
+ })
25
168
  ```
26
169
 
27
- `toPdf()` returns a `Blob`; downloading is opt-in. Put capture-time measurement options on `pdf({ forms, outline, breakAvoid, shadow, formValues })` and paper size, orientation, margins, tagging, metadata, headers, footers, compression or encryption on `toPdf()`. Tagged output alone does not guarantee PDF/UA conformance: the exporter reports eligibility and blockers. Redact sensitive source content structurally before capture; covering pixels does not remove searchable text. See the [full reference](REFERENCE.md) and the [public types](index.d.ts).
170
+ `encrypt` protects the file with AES-256. `userPassword` is required. `ownerPassword` defaults to it. `permissions` takes `print`, `modify`, `copy`, `annotate`, `fillForms`, `assemble` and `printHighRes`, all `true` by default.
171
+
172
+ Only the password protects the file. Permissions are requests that a viewer may ignore. Encryption needs https or localhost, and an encrypted export is different every time.
173
+
174
+ ## Output
175
+
176
+ | Option | Default | What it does |
177
+ |---|---|---|
178
+ | `download` | `false` | A file name, or `true` for `snapdom.pdf`. The Blob is still returned. |
179
+ | `deflate` | `true` | Compress the PDF's internal streams. |
180
+
181
+ ## Progress, cancel and report
182
+
183
+ | Option | Default | What it does |
184
+ |---|---|---|
185
+ | `onProgress` | none | Called with `{ phase, done, total }` as pages are made. `total` is `null` until the page count is known. |
186
+ | `signal` | none | An `AbortSignal`. Aborting stops the export with an `AbortError`. |
187
+ | `onReport` | none | Called once the PDF is done, with what happened: pages, size, fields, fonts and warnings. |
188
+
189
+ ```js
190
+ await shot.toPdf({
191
+ page: 'a4',
192
+ onProgress: ({ done, total }) => bar.update(done, total),
193
+ signal: controller.signal,
194
+ onReport: (report) => console.log(report.pages, report.warnings),
195
+ })
196
+ ```
197
+
198
+ Each warning in the report has a `code`, such as `link-unresolved` or `text-clipped`, so a test can check for them without reading messages.
199
+
200
+ ## When something looks wrong
201
+
202
+ The plugin warns in the console with a `[snapdom-pdf]` prefix: a block split across pages, a link without a target, text cut off. The same warnings arrive in the report.
203
+
204
+ A grey box where an image should be means the capture could not read that image. It shows up in the capture's `result.warnings` as `image-fallback`. [Export a PDF with cross-origin images](https://snapdom.dev/how-to/pdf-cross-origin-images/) explains the fix.
205
+
206
+ If the PDF does not match the page, [open an issue](https://github.com/zumerlab/snapdom/issues) with a small example and we will fix it.
207
+
208
+ ## Limits
209
+
210
+ - Text is an image unless you use `vectorText`, so a deep zoom shows the capture's resolution.
211
+ - Closed shadow roots cannot be read.
212
+ - Date inputs are written in ISO format, not as the browser shows them.
213
+ - An element used as header, footer or watermark has no selectable text. A repeated table header has no links.
214
+ - The full test suite runs in Chromium. Firefox and WebKit are checked for the main features.
28
215
 
29
216
  ## Migrating from `pdf-image`
30
217
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zumer/snapdom-pdf",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "PDF export for SnapDOM: searchable, paginated documents with selectable text, links and optional form fields",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -16,7 +16,6 @@
16
16
  "index.d.ts",
17
17
  "src/",
18
18
  "README.md",
19
- "REFERENCE.md",
20
19
  "CHANGELOG.md"
21
20
  ],
22
21
  "keywords": [
package/src/furniture.js CHANGED
@@ -42,7 +42,7 @@ export function bandHeight(el, availW) {
42
42
  *
43
43
  * @param {Element} el
44
44
  * @param {{scale: number, dpr: number, quality: number,
45
- * backgroundColor: string|null, availW: number}} opts
45
+ * backgroundColor: string|null, availW: number, fitW?: number}} opts
46
46
  */
47
47
  export async function captureBand(el, options, encodeImage) {
48
48
  const img = await captureElement(el, options, encodeImage)
@@ -59,11 +59,15 @@ export async function captureBand(el, options, encodeImage) {
59
59
  * @returns {Promise<object>} what `addStream` needs, plus `aspect` (height/width).
60
60
  */
61
61
  export async function captureElement(el, {
62
- scale, dpr, quality, backgroundColor, codec, captureOptions = {}, image = true,
62
+ scale, dpr, quality, backgroundColor, codec, captureOptions = {}, image = true, fitW = 0,
63
63
  }, encodeImage) {
64
64
  if (!el || el.nodeType !== 1) throw new TypeError('captureElement: expected an Element')
65
65
  if (image && typeof encodeImage !== 'function') throw new TypeError('captureElement: encodeImage must be a function')
66
- const rasterScale = positive(scale, 1)
66
+ // `fitW` is the width in points the image is drawn at. Wider than the element's own
67
+ // box (CSS px x 0.75), the raster is enlarged to it the way the body's is (`magnify`
68
+ // in index.js), so a band or a cover is no softer than the page under it.
69
+ const boxW = fitW > 0 ? el.getBoundingClientRect().width * 0.75 : 0
70
+ const rasterScale = positive(scale, 1) * (boxW > 0 ? Math.max(1, fitW / boxW) : 1)
67
71
  const rasterDpr = positive(dpr, 1)
68
72
  const source = {
69
73
  baseURL: String(el.ownerDocument?.baseURI || document.baseURI),
package/src/index.js CHANGED
@@ -630,11 +630,31 @@ async function measureArtifact(url, meta, opts, source = {}) {
630
630
  frameDoc.head.prepend(base)
631
631
  const svg = frameDoc.importNode(parsed.documentElement, true)
632
632
  svg.style.cssText = `display:block;width:${meta.vbW}px;height:${meta.vbH}px;max-width:none;max-height:none;overflow:visible;`
633
- frameDoc.body.appendChild(svg)
634
- if (frameDoc.fonts?.ready) await frameDoc.fonts.ready
635
633
  const fo = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'foreignObject')[0] ||
636
634
  svg.querySelector('foreignObject')
637
635
  const container = fo && [...fo.children].find(el => el.localName === 'div')
636
+ // On a screen that lays out on the device grid, snapdom lays the raster's copy out
637
+ // under `zoom: devicePixelRatio` on this container, with `scale(1 / zoom)` on the
638
+ // <g> around the foreignObject (layoutZoom, #508). Mounted inline under this page's
639
+ // own dpr that wrapper laid out at zoom x dpr, and the text layer took the scale but
640
+ // not the zoom, so on a Retina Mac every run came out at half its size with its
641
+ // baseline half an ascent high and the selection sat over the top of the words.
642
+ // Undone the way the core's svg file export undoes it (#552), which lays the clone
643
+ // out at the page's dpr, the grid the raster was laid out on. Pinned by
644
+ // test/verify.mjs `hidpi`.
645
+ const zoom = parseFloat(container?.style.zoom) || 1
646
+ if (zoom !== 1) {
647
+ container.style.removeProperty('zoom')
648
+ for (const name of ['x', 'y', 'width', 'height']) {
649
+ fo.setAttribute(name, String(Number(fo.getAttribute(name)) / zoom))
650
+ }
651
+ const group = fo.parentNode
652
+ if (group.localName === 'g') {
653
+ group.setAttribute('transform', group.getAttribute('transform').replace(/scale\([^)]*\)/, '').trim())
654
+ }
655
+ }
656
+ frameDoc.body.appendChild(svg)
657
+ if (frameDoc.fonts?.ready) await frameDoc.fonts.ready
638
658
  const root = container?.firstElementChild
639
659
  if (!root) throw new Error('[snapdom-pdf] the final SVG has no measurable capture root')
640
660
  const svgRect = svg.getBoundingClientRect()
@@ -746,7 +766,8 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
746
766
  if (!spec || spec.kind !== 'element') continue
747
767
  const band = await captureBand(spec.el, {
748
768
  scale: options.scale, dpr: options.dpr, backgroundColor: null, quality, codec,
749
- availW: provisionalW, captureOptions: options.captureOptions,
769
+ availW: provisionalW, fitW: options.rasterDensity == null ? provisionalW : 0,
770
+ captureOptions: options.captureOptions,
750
771
  }, encodeOpaque)
751
772
  capturedBands.set(where, band)
752
773
  }
@@ -761,6 +782,13 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
761
782
 
762
783
  const geo = pageBox({ page, orientation, margin, contentW, contentH, headerH, footerH, report })
763
784
  const { pageW, pageH, marginX, marginY, availW, availH, contentTop, k, scaledH } = geo
785
+ // A paper size that enlarges the capture to its printable width enlarged the
786
+ // pixels with it. The site's 340px demo card fills A4 at 2.15x, and its dpr 2
787
+ // capture came out at 89 dpi under text a reader zooms into. Rasterizing at the
788
+ // printed size keeps the capture's dpr per CSS px of paper (192 dpi there). A page
789
+ // that shrinks the capture keeps every pixel the capture had, and an absolute
790
+ // width/height is the caller's pixel budget. Pinned by test/verify.mjs `density`.
791
+ const magnify = options.rasterDensity == null ? Math.max(1, geo.drawScale) : 1
764
792
 
765
793
  // Viewport CSS px → content points.
766
794
  const toContentX = (vx) => (vx - rect.left) * k
@@ -813,7 +841,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
813
841
  const imageObjects = new WeakMap()
814
842
  const imageObject = async (crop = null) => {
815
843
  if (!raster) throw new Error('[snapdom-pdf] raster requested while image:false')
816
- const encoded = await raster(crop)
844
+ const encoded = await raster(crop, magnify)
817
845
  let saved = imageObjects.get(encoded)
818
846
  if (saved) return saved
819
847
  if (/DCTDecode/.test(encoded.dict)) jpegRegions++
@@ -975,7 +1003,6 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
975
1003
  }
976
1004
  }
977
1005
  let coverageFallbacks = 0
978
- const systemStacks = new Set()
979
1006
 
980
1007
  /**
981
1008
  * One short string of the PLUGIN's own text — a page number, a running head, a
@@ -1159,7 +1186,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1159
1186
  // canvas. Bound both stages with the same side/area ceilings as toCanvas.
1160
1187
  const intrinsicW = measured.intrinsic?.width > 0 ? measured.intrinsic.width : vbW
1161
1188
  const intrinsicH = measured.intrinsic?.height > 0 ? measured.intrinsic.height : vbH
1162
- const pixelFactor = options.scale * options.dpr
1189
+ const pixelFactor = options.scale * options.dpr * magnify
1163
1190
  const densityX = options.rasterDensity != null
1164
1191
  ? Math.max(intrinsicW / vbW, options.rasterDensity * options.dpr)
1165
1192
  : intrinsicW / vbW * pixelFactor
@@ -1635,17 +1662,6 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1635
1662
  }
1636
1663
  const paginated = page !== 'fit'
1637
1664
 
1638
- /** One finished page from a list of ops — the same stream handling the body gets. */
1639
- const addPage = async (ops, { annots = [], fonts, xobjects = [] }) => {
1640
- const body = ops.join('\n')
1641
- const deflated = wantDeflate && canDeflate && !debugText
1642
- const contentId = doc.addStream(
1643
- deflated ? '/Filter /FlateDecode' : '',
1644
- deflated ? await deflate(body) : body
1645
- )
1646
- return doc.add(pageDict({ contentId, annots, fonts, xobjects }))
1647
- }
1648
-
1649
1665
  /**
1650
1666
  * A cover or a colophon: your own element, captured, one to a page — and given
1651
1667
  * the SAME invisible text layer the body gets.
@@ -1662,7 +1678,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1662
1678
  const shot = await captureElement(el, {
1663
1679
  scale: options.scale, dpr: options.dpr, backgroundColor: null, quality, codec,
1664
1680
  captureOptions: options.captureOptions,
1665
- image,
1681
+ image, fitW: options.rasterDensity == null ? pageW : 0,
1666
1682
  }, image ? encodeOpaque : null)
1667
1683
  const subMeasured = await measureArtifact(shot.url, shot.meta, {
1668
1684
  formValues: measured.formValues !== false,
@@ -2280,9 +2296,10 @@ export default function pdf(defaults = {}) {
2280
2296
  const cropKey = (crop) => crop
2281
2297
  ? ['crop', crop.x, crop.y, crop.width, crop.height].map(String).join(':')
2282
2298
  : 'full'
2283
- const rasterFor = (options) => async (crop = null) => {
2299
+ // `magnify` is the page's enlargement of the capture (`draw`), 1 with an absolute size.
2300
+ const rasterFor = (options) => async (crop = null, magnify = 1) => {
2284
2301
  const key = JSON.stringify([
2285
- cropKey(crop), options.quality, options.backgroundColor, options.codec,
2302
+ cropKey(crop), magnify, options.quality, options.backgroundColor, options.codec,
2286
2303
  ])
2287
2304
  if (imageCache.has(key)) return imageCache.get(key)
2288
2305
  const promise = Promise.resolve().then(async () => {
@@ -2291,7 +2308,7 @@ export default function pdf(defaults = {}) {
2291
2308
  backgroundColor: null,
2292
2309
  width: absoluteSize ? (crop?.width ?? meta.vbW) * captureDensity : null,
2293
2310
  height: absoluteSize ? (crop?.height ?? meta.vbH) * captureDensity : null,
2294
- scale: rasterScale,
2311
+ scale: rasterScale * magnify,
2295
2312
  ...(crop ? { crop } : {}),
2296
2313
  })
2297
2314
  return encodeImage(canvas, {
@@ -2343,8 +2360,7 @@ export default function pdf(defaults = {}) {
2343
2360
  // the engine has no opinion about.
2344
2361
  for (const gone of ['mode', 'vector', 'scale', 'background', 'filename', 'compress']) {
2345
2362
  if (gone in opts) {
2346
- report(`\`${gone}\` is not a PDF option — see the reference at ` +
2347
- 'https://snapdom.dev/pro/pdf/docs.html. Ignored.')
2363
+ report(`\`${gone}\` is not a PDF option (the package README lists them). Ignored.`)
2348
2364
  }
2349
2365
  }
2350
2366
 
@@ -23,7 +23,7 @@ under the same visibility, clip and transform rules as every text run — lives
23
23
  `src/text-layer.js`, because measurement is its job. What is in this folder is
24
24
  the part in between: planning and byte-shaping.
25
25
 
26
- Decisions that are settled (see the triage memory and REFERENCE.md):
26
+ Decisions that are settled (see the triage memory and the package README):
27
27
 
28
28
  - **The `pdfuaid` claim is earned, never configured.** Fonts embed from the
29
29
  capture's own `@font-face` (`fonts.js` + `pdf-writer/font.js`), subset to the
package/REFERENCE.md DELETED
@@ -1,520 +0,0 @@
1
- # SnapDOM PDF reference
2
-
3
- Version 1.0.0 reference. This is the canonical option and behaviour reference
4
- for the build beside it.
5
-
6
- SnapDOM PDF is a SnapDOM plugin. It does not expose a standalone `toPdf(element)`
7
- function. Register the `pdf()` factory before capture; the resulting capture
8
- then gains `toPdf()` and the generic `to('pdf')` export.
9
-
10
- ```js
11
- import { snapdom } from '@zumer/snapdom'
12
- import pdf from './snapdom-pdf.mjs'
13
-
14
- snapdom.plugins(pdf())
15
-
16
- const shot = await snapdom(document.querySelector('#report'), {
17
- scale: 2,
18
- dpr: 1,
19
- })
20
-
21
- const blob = await shot.toPdf({ page: 'a4' })
22
- ```
23
-
24
- See [README.md](./README.md) for the bundler and import-map installation
25
- recipes. Both builds export the same factory as the default export and as the
26
- named export `pdf`. The supported peer range is `@zumer/snapdom >=3.0.0 <4`.
27
- The plugin uses v3's immutable capture metadata, requested export options and
28
- pre-decode canvas crops. PDF declares `needs: 'render'` and uses the SVG path so
29
- the text layer and raster share one immutable artifact.
30
-
31
- ## The two option moments
32
-
33
- The plugin derives its geometry and document semantics lazily from SnapDOM's
34
- final serialized clone when the first PDF export runs, rather than reading the
35
- original live DOM. Five options control that capture model and therefore have
36
- to be fixed on `pdf()` before the capture is created:
37
-
38
- | Capture-time option | Default | Meaning |
39
- |---|---:|---|
40
- | `formValues` | `true` | Put `input`, `textarea` and selected `select` values in the text layer. Password values are replaced with bullets. |
41
- | `shadow` | `true` | Walk open shadow roots as a flattened tree. Closed roots are unreachable. |
42
- | `breakAvoid` | `true` | Measure rows, list items, figures and other atomic blocks so pagination can avoid splitting them. |
43
- | `outline` | `true` | Build bookmarks from `h1`–`h6` and `role="heading"`. A string is a custom CSS selector; `false` disables the outline. |
44
- | `forms` | `true` | Measure form controls (kind, name, value, options, geometry, painted style) so the export can write fillable fields. `false` skips the measurement entirely. |
45
-
46
- ```js
47
- snapdom.plugins(pdf({
48
- shadow: true,
49
- outline: 'h1, h2, [role="heading"]',
50
- page: 'a4', // an export default may also live here
51
- margin: 36,
52
- }))
53
-
54
- const shot = await snapdom(report)
55
- await shot.toPdf({ margin: 48 }) // overrides only this export
56
- ```
57
-
58
- Passing a capture-time option to `toPdf()` warns and ignores it. Every export
59
- option below may also be supplied to `pdf()` as a default; `toPdf()` wins.
60
-
61
- ## `toPdf()`
62
-
63
- ```ts
64
- shot.toPdf(options?: PdfExportOptions): Promise<Blob>
65
- shot.to('pdf', options?: PdfExportOptions): Promise<Blob>
66
- ```
67
-
68
- `download` is an optional side effect. A `Blob` with type `application/pdf` is
69
- returned in every case.
70
-
71
- ### Page and pagination
72
-
73
- | Option | Default | Meaning |
74
- |---|---:|---|
75
- | `page` | `'fit'` | `'fit'`; `a3`, `a4`, `a5`, `a6`, `b4`, `b5`, `letter`, `legal`, `tabloid`, `executive`; or `[width, height]` in PDF points. |
76
- | `orientation` | `'portrait'` | `'portrait'` or `'landscape'`. It has no effect on `'fit'`. |
77
- | `margin` | `24` | Points on all sides. It has no effect on `'fit'`. |
78
- | `repeatHeaders` | `true` | On paginated output, repeat a table's `<thead>` wherever that table continues. |
79
-
80
- `page: 'fit'` creates one page at the captured element's size. Other sizes scale
81
- the capture to the printable width and paginate vertically. Declared
82
- `break-before`/`break-after` values `always`, `page`, `left`, `right`, `recto`
83
- and `verso` create plain breaks when they do not create an empty page.
84
-
85
- Atomic blocks include table rows, list items, `dt`/`dd`, figures, blockquotes,
86
- replaced content, `break-inside: avoid` content and short leaf blocks. A block
87
- taller than a page still has to be split.
88
-
89
- Repeated `<thead>` pixels and text are re-stamped from the body capture. Links
90
- inside the repeated copy are not repeated. A header taller than half a page is
91
- left where it originally occurs and produces a warning.
92
-
93
- ### Raster
94
-
95
- | Option | Default | Meaning |
96
- |---|---:|---|
97
- | `image` | `true` | Draw the visible page raster. `false` skips rasterization and produces an image-free PDF while the enabled text, links and structure remain. Element headers, footers and watermarks are omitted because they are images. |
98
- | `codec` | `'auto'` | `'auto'` encodes JPEG and lossless Flate and keeps the smaller image. `'jpeg'` and `'flate'` pin the choice. |
99
- | `quality` | capture quality or `0.92` | Quality of the JPEG candidate, taken from the capture when the export does not set one. It reaches nothing when Flate wins, and on ordinary page artwork Flate wins until roughly 0.5. Measured on a 37-page report: `0.92`, `0.8` and `0.6` all produce a byte-identical 16.1 MB, `0.4` gives 13.7 MB and `0.2` gives 10.1 MB. An export whose lowered quality changed nothing says so. |
100
- | `backgroundColor` | capture background or `null` | Flatten this PDF export onto a colour. May be set on the capture, the plugin defaults or this export. |
101
-
102
- Resolution belongs to `snapdom(...)`: use `scale`, `dpr`, `width` and `height`
103
- there, not in `toPdf()`. On v3, an explicit width or height overrides `scale`;
104
- `dpr` still multiplies the raster resolution. Keep the capture aspect ratio when
105
- setting both dimensions. The exporter rasterizes page regions lazily and caches
106
- them on the capture for later exports. A different codec, quality or flattening
107
- choice may still require encoding work.
108
-
109
- **`dpr` is the same knob as `scale` here, and it defaults to the machine.**
110
- A PDF has no device to match, so neither option moves a point of geometry: the
111
- MediaBox, the text layer and every annotation are identical whatever they are
112
- set to. What they multiply is the page image's pixel count, and they multiply it
113
- together. Measured on an 8-page A4 report, `scale: 1, dpr: 2` and
114
- `scale: 2, dpr: 1` produce the same 1748px-wide raster and the same 3.18 MB
115
- file, against 1.63 MB at 1×1 and 6.93 MB at 2×2.
116
-
117
- The catch is the default. SnapDOM reads `dpr` from `window.devicePixelRatio`,
118
- which is right for a screenshot and surprising for a document: the same code
119
- exports 3.18 MB from a 2× laptop and 1.63 MB from a 1× monitor or a CI
120
- container, with no visible difference in the page and no warning. Set `dpr`
121
- explicitly on the capture (`1` for a light, screen-read file, `2` for one meant
122
- to be printed) and the export stops depending on who ran it.
123
-
124
- `codec: 'auto'` costs an extra encode. Pin a codec when latency matters more than
125
- choosing the smallest file. If `CompressionStream` is unavailable, `auto` uses
126
- JPEG and a requested `flate` warns before falling back to JPEG.
127
-
128
- Transparency uses a soft mask. `backgroundColor` removes that mask and usually
129
- produces a smaller file. Geometry comes from the same final serialized clone as
130
- the raster. Real removals/replacements made by `exclude`, `resolveNode`,
131
- `afterClone`, `clip`, or a geometry-preserving `afterRender` replacement of the
132
- final serialized tree/URL stay synchronized with the PDF layer. An `afterRender`
133
- replacement that changes the artifact's viewBox, root paint/layout attributes or
134
- intrinsic aspect/geometry incompatibly is rejected rather than exported with a
135
- misaligned layer. Uniform width/height scaling that preserves aspect is allowed.
136
-
137
- ### Text, links, navigation and accessibility
138
-
139
- | Option | Default | Meaning |
140
- |---|---:|---|
141
- | `text` | `true` | Emit selectable/searchable invisible text. |
142
- | `links` | `true` | Emit external URI and in-document link annotations. |
143
- | `tagged` | `true` | Emit a structure tree for headings, paragraphs, lists, tables, sections and figures. |
144
- | `lang` | DOM language or `null` | Set the PDF document language, such as `'en'` or `'es-MX'`. |
145
- | `embedFonts` | `true` | Embed the capture's `@font-face` binaries and point the text at them. |
146
- | `vectorText` | `false` | Paint eligible text as real vector glyphs instead of leaving it invisible over the raster. |
147
- | `debugText` | `false` | Paint the normally invisible layer in red and leave streams readable. |
148
-
149
- #### Embedded fonts
150
-
151
- The capture must CARRY its fonts for the export to embed them: pass
152
- `embedFonts: true` to `snapdom(…)` (the engine option that inlines `@font-face`
153
- into the capture), and the PDF side reads those rules, fetches each face the
154
- text actually painted with, and embeds a SUBSET of it: only the glyphs the
155
- document drew, renumbered into a dense space. On a Latin page a ~320 kB face
156
- travels as a few kB; the subset renders pixel-identical to the whole font
157
- (asserted by rendering both through pdf.js). A face travels once however many
158
- styles and pages use it, and the saving is declared per face (`font-embedded`).
159
-
160
- `embedFonts` on the PDF export controls this: `true` (default) subsets;
161
- `'full'` embeds the whole file unsubsetted (glyph ids stay the font's own);
162
- `false` embeds nothing. CFF/OpenType (`OTTO`) faces are always embedded whole
163
- (their charstrings are a different compiler), so `'full'` only differs for
164
- TrueType. The subsetter is fail-safe: a TrueType face it cannot subset falls
165
- back to a whole embed with an explicit `CIDToGIDMap`, never a corrupt glyph.
166
-
167
- #### Vector text
168
-
169
- By default the visible text is the raster: pixel-exact, but pixels. With
170
- `vectorText: true` the exporter PAINTS eligible runs as real vector glyphs from
171
- the embedded fonts, so the type is crisp at any zoom and the file is a fraction
172
- of the size. This is a different fidelity model from the pixel-exact capture,
173
- and it is opt-in for that reason.
174
-
175
- A run is painted only where no shaping stands between code points and glyphs: a
176
- left-to-right run, in a covering embedded face, with a resolved colour. RTL,
177
- complex scripts, uncovered characters and unresolved colours are NOT painted,
178
- because one CID per code point would place their glyphs wrong. Those runs stay
179
- on the raster; in an image-free export they are invisible and `vector-missed`
180
- says so.
181
-
182
- The two useful pairings:
183
-
184
- - `image: false, vectorText: true`: a small, fully-vector text PDF. Only the
185
- text and vector furniture travel; borders, checkboxes, background images and
186
- any un-paintable run are absent. Measured: the mega fixture is ~22 kB this way
187
- against ~420 kB with the raster.
188
- - `image: true, vectorText: true`: the raster plus crisp vector glyphs painted
189
- over it. Larger, but sharp under magnification.
190
-
191
- Interior glyph positions follow the embedded font's own advances scaled to the
192
- run's measured width (`Tz`), not the browser's kerned positions, so a heavily
193
- kerned pair can drift sub-pixel from the raster. Extraction is unchanged: the
194
- painted glyphs carry the same `/ToUnicode` as the invisible layer.
195
-
196
- Per run, the embedded face is used only when its real cmap covers every
197
- character of the run; a run it cannot carry falls back to the unembedded layer
198
- and is counted (`font-coverage`). System fonts have no bytes a page can hand
199
- over and travel by name as before. WOFF unpacks; WOFF2, TrueType collections
200
- and faces whose `OS/2 fsType` forbids embedding are refused with their reason
201
- (`font-fallback`). No shaping is performed, which is correct for the invisible
202
- layer, whose widths are pinned to the DOM measurement by `Tz`.
203
-
204
- Text extraction is byte-for-byte identical with and without embedding (asserted
205
- in the harness), because extraction runs off `/ToUnicode` either way.
206
-
207
- #### The earned PDF/UA-1 claim
208
-
209
- The exporter never takes a conformance claim as an option; it COMPUTES
210
- eligibility per export: every text-showing operation on an embedded face,
211
- `tagged` structure present, a document language, a `meta.title` to display, and
212
- no painted image without alternative text. When all of it holds, the XMP carries
213
- `pdfuaid:part 1` and the report says so (`ua-claimed`, `report.pdfua === true`).
214
- When fonts are clean but a blocker remains, the blockers are named
215
- (`ua-withheld`).
216
-
217
- Two blockers are worth knowing in advance. Fillable fields block the claim,
218
- because their editor-facing `/DA` types in unembedded Helvetica, so a
219
- UA-claiming export pairs with `fields: false`. A painted `<img>` or
220
- `role="img"` element with no accessible name blocks it too, because its pixels
221
- live in the page raster, which is an artifact, and there is no `/Alt` to
222
- announce: give it `alt`, `aria-label` or `title`, or `alt=""` when it is
223
- decorative.
224
-
225
- Text is measured from the final serialized clone, one run per word. Text
226
- transforms are applied; open shadow roots, visible form values and bidi logical
227
- order are included. Text hidden by layout, ancestor opacity or rectangular
228
- overflow clipping is excluded.
229
-
230
- Base-14 fonts carry WinAnsi text. Other scripts use an invisible Type0 font with
231
- a `/ToUnicode` map. Without `vectorText`, the visible type remains the SnapDOM
232
- raster.
233
-
234
- Headings become bookmarks and named destinations. A same-document `#fragment`
235
- link becomes a PDF destination; an unresolved or out-of-capture fragment gets no
236
- annotation and produces a warning. External annotations are restricted to
237
- `http:`, `https:`, `mailto:` and `tel:`. Malformed URLs and other schemes such
238
- as `javascript:`, `data:`, `blob:` and `file:` are ignored and reported. A
239
- custom `outline` selector is evaluated against the final flattened artifact, so
240
- matching open-shadow and slotted headings participate too.
241
-
242
- #### Redaction and semantic visibility
243
-
244
- Visual occlusion is not redaction. A rectangle above a secret, blur, or arbitrary
245
- overlap can hide pixels without removing the underlying text from the serialized
246
- document. Remove or replace confidential nodes/text with `exclude`,
247
- `resolveNode` or a clone/render hook. Do not use overlays or blur as a redaction
248
- mechanism.
249
-
250
- For known clipping, masking and filter geometry, the collector omits text and
251
- links when it cannot prove they are visible. This is fail-safe: difficult visual
252
- effects may lose selectable semantics instead of leaking content. An
253
- `afterRender` hook is synchronized only when it replaces the final serialized
254
- tree/URL while preserving its geometry. A purely visual overlay is not evidence
255
- that semantic content vanished, and an incompatible viewBox, root paint/layout
256
- or intrinsic-aspect change fails instead of guessing new coordinates.
257
-
258
- Tagged output improves reading order and structure. It becomes a **PDF/UA-1
259
- claim only when the export earns it** (see "The earned PDF/UA-1 claim" above);
260
- short of that, no `pdfuaid` identifier is written. Either way the tree is
261
- real: link annotations are tied in by
262
- `/Link` structure elements carrying `/OBJR` references, fillable fields by
263
- `/Form` elements, header cells carry `/Scope` (and spans), table row groups map
264
- to `THead`/`TBody`/`TFoot`, pages declare `/Tabs /S` so tab order follows the
265
- structure, and the parent tree resolves both marked content and annotations.
266
- Inline formatting elements are deliberately not expanded into a structure node
267
- each.
268
-
269
- ### Fillable form fields
270
-
271
- | Option | Default | Meaning |
272
- |---|---:|---|
273
- | `fields` | `true` | Emit measured form controls as real AcroForm fields: fillable, tabbable, extractable. `false` keeps their values in the invisible text layer instead. |
274
-
275
- A captured form should still BE a form. Text inputs, textareas, checkboxes,
276
- radio groups, and selects become widget annotations with their DOM name, value,
277
- options and checked state; `readonly`/`disabled` map to the read-only flag,
278
- `required` and `maxlength` travel too, and the accessible label (`aria-label`,
279
- `<label for>`, placeholder, title, in that order) becomes the field's tooltip,
280
- which is what a screen reader speaks. Radios group by their HTML `name`;
281
- duplicate non-radio names are uniquified with a suffix and reported.
282
-
283
- The page image yields each fielded control's area to its widget, and the
284
- widget's appearance follows one rule, dictated by macOS Preview: a field
285
- HOLDING A VALUE paints it as real text, laid out from the control's own
286
- measured runs so a textarea's wrap and an input's alignment are the page's
287
- rather than a guess, while an EMPTY field wears the control's own crop of the
288
- capture: border, corner radius and placeholder, pixel-exact. (Preview redraws a
289
- text field's value over any appearance carrying an image, so a valued field's
290
- crop would show the value twice there; text appearances render once everywhere:
291
- Preview, Quick Look, Chrome, pdf.js, Acrobat, and every print/flatten path.)
292
-
293
- What deliberately does not happen: a **password** field is written empty with
294
- the password flag set, because a field value is plain text in the file; the
295
- raster keeps its painted bullets. **Buttons, sliders, colour wells and file
296
- pickers** stay pixels; a control that only means something to a running page is
297
- not a field. **No JavaScript actions and no submit URLs** are ever written. A
298
- rotated or clip-cut control is reported and left as invisible text, and a
299
- control crossing a page break is clamped to one page and reported. With
300
- `image: false` the appearance is synthesized (background, border and a base-14
301
- value line), and a value outside WinAnsi sets `/NeedAppearances` so the viewer
302
- draws it.
303
-
304
- ### Document metadata, identity and page labels
305
-
306
- | Option | Default | Meaning |
307
- |---|---:|---|
308
- | `meta` | `null` | `{ title, author, subject, keywords, creator, created, modified }`: /Info plus a mirrored XMP packet. |
309
-
310
- `title` also sets `/ViewerPreferences << /DisplayDocTitle true >>`, so viewers
311
- show the document's name rather than its filename. `keywords` may be a string or
312
- an array. `created`/`modified` accept a `Date` or ISO-8601 string and are
313
- written ONLY when given: an invented "now" would break the byte-determinism
314
- promise, so pass `new Date()` yourself when you mean it. `/Producer` is always
315
- `snapdom-pdf` and is not an option.
316
-
317
- Every file carries a trailer `/ID` derived from its own content: identical
318
- unencrypted exports share an ID, different documents differ, and no clock is
319
- involved. Paginated documents with front matter get `/PageLabels` (cover and
320
- contents in lowercase roman, body decimal from 1), so the viewer's page field
321
- agrees with the printed folio and with the generated contents.
322
-
323
- ### Encryption
324
-
325
- | Option | Default | Meaning |
326
- |---|---:|---|
327
- | `encrypt` | `null` | `{ userPassword, ownerPassword, permissions }`: encrypt the file with AES-256 (standard security handler, revision 6). |
328
-
329
- The exported file is the delivery: it gets downloaded, attached, and forwarded.
330
- `encrypt` is what makes that file unreadable once it has left, and it is the
331
- only protection here that is not advisory.
332
-
333
- ```js
334
- await shot.toPdf({
335
- page: 'a4',
336
- encrypt: { userPassword: 'ada-1815', ownerPassword: 'owner-key' },
337
- })
338
- ```
339
-
340
- `userPassword` is **required and must be non-empty**, and an export that omits
341
- it throws rather than producing a file. A PDF whose user password is `''` is
342
- genuinely encrypted (the bytes are unreadable to a text editor), and every
343
- viewer in the world still opens it without asking. That is the exact shape of a
344
- document somebody believes is protected and is not. `ownerPassword` defaults to
345
- the user password; it exists to lift the permission flags for whoever holds it.
346
-
347
- **AES-256 and nothing older.** RC4 and revisions 2–4 are not offered at any
348
- setting. A 40-bit key falls in seconds, 128-bit RC4 is not far behind, and both
349
- need MD5, which the platform does not provide. Writing one by hand to ship a
350
- weaker product is not a trade this exporter makes. Everything used here comes
351
- from the browser's own `crypto.subtle`, so the plugin carries no cipher code and
352
- no dependency. Encryption therefore needs a **secure context**: https, or
353
- localhost. Encrypting a 14 MB document costs about 34 ms.
354
-
355
- | | |
356
- |---|---|
357
- | `/Filter /Standard /V 5 /R 6`, `/CFM /AESV3`, 256-bit key | ISO 32000-2 §7.6.4 |
358
- | Header stays `%PDF-1.7`; the catalog declares `/ADBE /ExtensionLevel 3` | the shape readers learned before ISO 32000-2 |
359
- | Every stream and every string is encrypted, `/Metadata` included | strings inside content streams ride the stream |
360
-
361
- #### Permissions are a request, not a protection
362
-
363
- `permissions` accepts `print`, `modify`, `copy`, `annotate`, `fillForms`,
364
- `assemble` and `printHighRes`; each defaults to `true`, and setting one to
365
- `false` clears its `/P` bit. Understand what that buys: a flag is something a
366
- viewer *may* honour and any other tool can ignore. The password is what protects
367
- the document; the flags only express intent to software that has already been
368
- given the key. The export says so in the report when any of them is set.
369
-
370
- Extraction for accessibility is deliberately not exposed. PDF 2.0 deprecates
371
- that bit (a conforming reader must always allow it), and PDF/UA requires an
372
- encrypted file to keep permitting it, so an exporter whose selling point is an
373
- extractable text layer has no business offering to switch it off. A UA-claiming
374
- export and an encrypted one are compatible for exactly that reason.
375
-
376
- #### Encrypted exports are not deterministic
377
-
378
- The file key, the salts and every IV are random, drawn from
379
- `crypto.getRandomValues` for each export. Encrypting the same document twice with
380
- the same password gives two different files that open to the same content, so
381
- two encrypted files never reveal that their contents match. Unencrypted exports
382
- stay byte-deterministic.
383
-
384
- ### Progress, cancellation and the report
385
-
386
- | Option | Default | Meaning |
387
- |---|---:|---|
388
- | `onProgress` | `null` | `({ phase, done, total })` per step: `measure`, `page` (with counts), `matter`, `assemble`. |
389
- | `signal` | `null` | An `AbortSignal`; aborting rejects with `AbortError` between pages. |
390
- | `onReport` | `null` | Receives the structured diagnostics report once the Blob is finished. |
391
-
392
- The report is `{ warnings, counts, pages, bytes, fields, annotations,
393
- fontsEmbedded, pdfua, vectorText }`, where each warning is `{ code, message }`,
394
- `counts` tallies by code and `vectorText` counts the runs painted as glyphs.
395
- Codes are a stable contract (`text-clipped`, `link-unresolved`, `field-skipped`,
396
- `layout-split`, …) so a CI step can gate on "no annotations lost" without
397
- parsing prose. Identical unencrypted exports produce identical reports; the
398
- console keeps warning regardless, so nothing changes for callers who ignore all
399
- of this.
400
-
401
- ### Header, footer and page numbers
402
-
403
- | Option | Default | Meaning |
404
- |---|---:|---|
405
- | `header` | `null` | A string/function, a text-band object, or an Element. |
406
- | `footer` | `null` | The same along the bottom. |
407
- | `pageNumbers` | `false` | `true` or `{ format, align, size, font, color }`. |
408
-
409
- Text bands accept `{ left, center, right, size, font, color, rule, gap }`.
410
- Segments may be strings or `(page, pages) => value`. `font` is `document`,
411
- `sans`, `serif` or `mono`; colours are three- or six-digit hex values.
412
- `document`, the default, is the body's own embedded face when the export has
413
- one, so a running head is set in the same type as the report it runs over, in
414
- real embedded glyphs; per string it falls back to base-14 sans when nothing is
415
- embedded or the face lacks a character. An explicit `sans`/`serif`/`mono` keeps
416
- meaning base-14. Base-14 furniture remains limited to WinAnsi scripts.
417
-
418
- Text-band defaults are `size: 9`, `font: 'document'`, `rule: true` and
419
- `gap: 10`. Page numbers default to `(page, pages) => page + ' / ' + pages`,
420
- centred at size 9 in the document face. `colour` is accepted as an alias for
421
- `color`; prefer `color` in new code.
422
-
423
- An Element band captures its capturable content and styles, but it is a picture
424
- without its own selectable layer; scripts are not executed by the measurement
425
- sandbox. Header, footer and numbers reserve space and only apply to paginated
426
- page sizes. With `image: false`, Element bands are omitted with a warning; text
427
- bands and page numbers still work.
428
-
429
- ### Cover, generated contents, closing page and watermark
430
-
431
- | Option | Default | Meaning |
432
- |---|---:|---|
433
- | `cover` | `null` | An Element captured as the first page. |
434
- | `toc` | `null` | `true`, a title string, or `{ title, levels, size, font, indent, dots, label, color, leaderColor }`. |
435
- | `back` | `null` | An Element captured as the last page. |
436
- | `watermark` | `null` | A string, Element, text-watermark object or element-watermark object. |
437
-
438
- Cover and back are scaled to fit a whole page without cropping and receive a
439
- selectable text layer. The generated contents comes from the same outline as
440
- the bookmarks; each row links to the body destination. Its page numbers refer
441
- to body pages, excluding cover and contents pages. When a custom
442
- `pageNumbers.format` changes numbering, use `toc.label` to keep both in step.
443
-
444
- Text watermarks accept `{ text, opacity, angle, size, font, color }`; omitting
445
- `size` auto-fits the rotated text. Element watermarks accept
446
- `{ element, opacity, angle, fit }`. Watermarks draw over every page and also work
447
- with `page: 'fit'`. With `image: false`, an Element watermark is omitted, while
448
- text watermarks still work. Cover, contents and back require a paginated page
449
- size; image-free cover/back pages retain their measured text, links and structure
450
- but not their visible raster.
451
-
452
- Contents default to title `Contents`, three outline depths, size 10, the
453
- document face, 14-point indentation and leaders enabled. Text watermarks default
454
- to 12% opacity and 45 degrees; Element watermarks default to 12% opacity, no
455
- rotation and a 0.6 fit. `colour`/`leaderColour` are accepted aliases for
456
- `color`/`leaderColor`.
457
-
458
- ### Output
459
-
460
- | Option | Default | Meaning |
461
- |---|---:|---|
462
- | `deflate` | `true` | Compress PDF content streams. `debugText` leaves them readable. |
463
- | `download` | `false` | A filename, or `true` for `snapdom.pdf`. `.pdf` is appended when absent. |
464
-
465
- Use `deflate`, not SnapDOM's `compress`; use `download`, not SnapDOM's
466
- `filename`. `compress`, `filename`, PDF-side `scale`, legacy `background`,
467
- `mode` and `vector` are not PDF options and are reported when passed.
468
-
469
- ## Errors and warnings
470
-
471
- Register the plugin before capture. A capture made without it has no `toPdf()`
472
- helper, and its generic `to('pdf')` has no PDF exporter to run. An available PDF
473
- export rejects an incompatible SnapDOM contract, invalid or empty capture
474
- geometry, an incompatible final-artifact viewBox/root paint-layout/intrinsic
475
- aspect, invalid orientation/margins/custom page geometry, and invalid active
476
- image codec/quality.
477
- An unknown string paper name warns and falls back to A4 for untyped JavaScript
478
- callers. Other fidelity losses are reported under `[snapdom-pdf]`, including:
479
-
480
- - page breaks that split atomic blocks or declared breaks that cannot be used;
481
- - text or links clipped, invisible, outside the page, or under unsupported 3D geometry;
482
- - unresolved internal links and invalid custom outline selectors;
483
- - missing language on tagged output;
484
- - a repeated table header too tall to repeat;
485
- - a requested contents page with no headings;
486
- - Base-14 page furniture that cannot represent its script;
487
- - invalid or translucent flattening colours and unavailable Flate compression;
488
- - malformed links or URI schemes outside the safe allowlist.
489
-
490
- Every one of these is also a structured diagnostic with a stable code in the
491
- report handed to `onReport`, so a build can gate on them instead of reading the
492
- console.
493
-
494
- ## Known limits
495
-
496
- - Visible text is raster by default, so zooming beyond capture resolution exposes pixels. `vectorText` paints eligible runs as glyphs, never RTL or complex scripts.
497
- - `textarea` wrapping is greedy and can drift for hyphenation, CJK, unbreakable strings and `line-height: normal`.
498
- - Date-like controls contribute their ISO value rather than the locale-painted value. Multi-row selects contribute no value.
499
- - Closed shadow roots are unreachable.
500
- - Upright glyphs in vertical writing modes are placed square; sideways runs are supported.
501
- - Ambiguous clipping, masking and filter geometry is omitted fail-safe, so some visibly painted text may not be selectable.
502
- - Native `<select>` insets were measured on Chromium and can differ in other engines.
503
- - Rotated links use an axis-aligned PDF rectangle.
504
- - Captured header/footer Elements have no selectable text layer.
505
- - `image: false` omits Element headers, footers and watermarks; cover/back pages
506
- keep semantics but lose their visible raster.
507
- - Only `<thead>` repeats, and its repeated copy has no repeated link annotations.
508
-
509
- ## Browser status
510
-
511
- The exporter is a browser ESM module. The complete PDF fixture suite runs in
512
- Chromium through `npm run test:pdf`. The monorepo also tests registration,
513
- searchable text, frozen capture state and redaction in Chromium and WebKit.
514
- Firefox is not yet verified in this branch: its runner failed to connect.
515
- The complete complex-layout matrix is not verified in every engine; known
516
- engine-sensitive limits remain listed above.
517
-
518
- The exporter runs locally in the page and returns a Blob. It does not upload the
519
- PDF. SnapDOM may still fetch the page resources or use a proxy if the application
520
- configured one.