@zumer/snapdom-pdf 1.0.1 → 1.0.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/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # PDF changes
2
2
 
3
+ ## 1.0.2
4
+
5
+ > 24 November 2026
6
+
7
+ **Features**
8
+
9
+ - **pdf:** WOFF2 fonts embed, and text is painted only from a file that holds its glyphs [`9644f96`](https://github.com/zumerlab/snapdom/commit/9644f969972bd942d2a767ccc70876adc916b00c)
10
+ - **pdf:** a word painted as glyphs is in the file once [`88c831e`](https://github.com/zumerlab/snapdom/commit/88c831e4c0d07acb5a37749b15ff7fa88a2e100d)
11
+ - **pdf:** text is painted as real glyphs by default [`9c525aa`](https://github.com/zumerlab/snapdom/commit/9c525aacdefb31320542b208df6aa1891ee5e2ec)
12
+
13
+ **Refactoring**
14
+
15
+ - the vector engine writes no PDF; the PDF plugin owns all of it [`acaff7d`](https://github.com/zumerlab/snapdom/commit/acaff7d76e12661a67ae8e1214b71c69f753bcc1)
16
+ - one engine per product; the PDF plugin does not use the vector engine [`de4f795`](https://github.com/zumerlab/snapdom/commit/de4f79529174793e2800cd3517b40769d9be59d0)
17
+
18
+ **Chores**
19
+
20
+ - **pdf,vector:** require SnapDOM 3.8.3 [`548afe4`](https://github.com/zumerlab/snapdom/commit/548afe42db29c19ce6c2a1eeddd84f6c86aa1117)
21
+ - release each package from its workspace instead of sixteen root aliases [`37f6b34`](https://github.com/zumerlab/snapdom/commit/37f6b341e842f6480786b663a3bc1123de393659)
22
+
3
23
  ## 1.0.1
4
24
 
5
25
  > 9 November 2026
package/README.md CHANGED
@@ -11,7 +11,7 @@ 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
- 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.
14
+ It needs SnapDOM 3.8.3 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
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
17
 
@@ -97,11 +97,23 @@ Links work for `http:`, `https:`, `mailto:` and `tel:`. Any other link is left o
97
97
  | Option | Default | What it does |
98
98
  |---|---|---|
99
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. |
100
+ | `vectorText` | `true` | Draw the text as real letters instead of pixels: sharp at any zoom and a lighter file. `false` keeps all the text in the image. |
101
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.
102
+ The PDF can only embed fonts the capture carries, so capture with `snapdom(el, { embedFonts: true })`. Web fonts in TTF, OTF, WOFF and WOFF2 embed. System fonts have no file to embed. Copying text works the same with or without embedded fonts.
103
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.
104
+ Text is drawn as real letters wherever the page's own font file can draw it, which needs embedded fonts. The rest stays as image, so the page always looks as it does on screen. These stay as image:
105
+
106
+ - right-to-left and complex scripts;
107
+ - a variable font at a weight other than the one its file was saved in;
108
+ - bold or italic the browser fakes because the page loaded no file for it;
109
+ - translucent or outlined text;
110
+ - small caps, tabular or old-style figures and other `font-feature-settings`;
111
+ - a word the browser hyphenated, and a word with a letter the font lacks;
112
+ - any text in a system font: the browser does not hand over its file.
113
+
114
+ The letters that are drawn leave the page image, so each one is in the file once: the PDF gets lighter and the text has no soft edge around it. Underlines, shadows and backgrounds stay in the image. A text that cannot be taken out of the image, such as the value of a form control, is not drawn and stays as image. This needs a `@zumer/snapdom` newer than 3.8.2; with an older one the letters are drawn over the image.
115
+
116
+ With `image: false` it gives a very small text-only PDF, without borders, backgrounds or pictures.
105
117
 
106
118
  ## Bookmarks and accessibility
107
119
 
@@ -207,7 +219,7 @@ If the PDF does not match the page, [open an issue](https://github.com/zumerlab/
207
219
 
208
220
  ## Limits
209
221
 
210
- - Text is an image unless you use `vectorText`, so a deep zoom shows the capture's resolution.
222
+ - Text in a system font is an image, so a deep zoom shows the capture's resolution. Text in a web font is drawn as letters.
211
223
  - Closed shadow roots cannot be read.
212
224
  - Date inputs are written in ISO format, not as the browser shows them.
213
225
  - An element used as header, footer or watermark has no selectable text. A repeated table header has no links.
package/index.d.ts CHANGED
@@ -180,7 +180,7 @@ export interface PdfReport {
180
180
  * configurable; the `ua-withheld` warning names the blockers when false.
181
181
  */
182
182
  pdfua: boolean
183
- /** Text runs `vectorText` painted as real glyphs. 0 when it is off. */
183
+ /** Text runs painted as real glyphs. 0 when `vectorText` is off or no font could paint any. */
184
184
  vectorText: number
185
185
  }
186
186
 
@@ -222,10 +222,19 @@ export interface PdfExportOptions {
222
222
  /**
223
223
  * Paint eligible text as real vector glyphs from the embedded fonts instead
224
224
  * of leaving it invisible over the raster, crisp at any zoom. Only faithful
225
- * where no shaping intervenes (left-to-right runs in an embedded face), so
226
- * RTL and uncovered runs stay on the raster. Pair with `image: false` for a
227
- * tiny, fully-vector text PDF; with `image: true` the glyphs overpaint the
228
- * raster. Default false.
225
+ * where no shaping intervenes (left-to-right runs in an embedded face) and
226
+ * the font file holds the design the page drew, so these stay on the raster:
227
+ * RTL and uncovered runs, a variable font off the weight its file was saved
228
+ * in, a bold or italic the browser faked, translucent or outlined text, small
229
+ * caps and other glyph substitutions, a word the browser hyphenated.
230
+ *
231
+ * With `image: true` a painted word is drawn once: the page image is
232
+ * rasterized without its glyph fill (underline, shadow and background stay),
233
+ * which is where most of the file's weight goes. A paintable run that cannot
234
+ * be taken out of the image — a form control's value — is then left as image.
235
+ * Needs a core with `ctx.exports.editSvg`; on an older one the glyphs
236
+ * overpaint the raster. Pair with `image: false` for a tiny, fully-vector
237
+ * text PDF. Default true; `false` leaves every glyph in the page image.
229
238
  */
230
239
  vectorText?: boolean
231
240
  cover?: Element | null
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@zumer/snapdom-pdf",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
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": {
7
7
  "bump:dry": "npx @zumerbox/bump -d",
8
- "bump": "npx @zumerbox/bump && npx @zumerbox/changelog"
8
+ "bump": "npx @zumerbox/bump && npx @zumerbox/changelog",
9
+ "release": "git add package.json CHANGELOG.md ../../package-lock.json && git commit -m \"Bumped pdf version\" && git push"
9
10
  },
10
11
  "exports": {
11
12
  ".": "./index.js"
@@ -41,7 +42,7 @@
41
42
  "url": "https://github.com/sponsors/tinchox5"
42
43
  },
43
44
  "peerDependencies": {
44
- "@zumer/snapdom": "^3.4.0"
45
+ "@zumer/snapdom": "^3.8.3"
45
46
  },
46
47
  "devDependencies": {
47
48
  "@zumer/snapdom": "file:../.."
package/src/index.js CHANGED
@@ -31,8 +31,8 @@
31
31
  * Requires the SnapDOM plugin contract that exposes immutable capture metadata,
32
32
  * raw export options and pre-decode canvas crops (SnapDOM v3).
33
33
  */
34
- // `src/writer/` is the byte-level half, and it is this product's own source. It
35
- // was a package shared with a sibling product once, which is why it still knows
34
+ // `src/writer/` is the byte-level half, and the only copy of it. It was a
35
+ // package shared with the vector engine once, which is why it still knows
36
36
  // nothing about text layers or page models and why `setWarnPrefix` exists — that
37
37
  // is what makes a warning raised down there say `[snapdom-pdf]` to the person who
38
38
  // bought this. Nothing of it reaches the buyer as a separate file; it is bundled.
@@ -47,6 +47,7 @@ import { buildStructure } from './tagged.js'
47
47
  import { createEmbeddedFont } from './writer/font.js'
48
48
  import { metaSpec, infoDict, xmpPacket } from './mega/meta.js'
49
49
  import { collectFaceRules, resolveFaces } from './mega/fonts.js'
50
+ import { withoutGlyphs, wrapperIsInert } from './page-image.js'
50
51
  import { buildReport, reportSpec } from './mega/diag.js'
51
52
  import { flowSpec } from './mega/flow.js'
52
53
  import { pageLabels } from './mega/labels.js'
@@ -356,12 +357,23 @@ function runBox(run) {
356
357
  function clipMeasurement(layer, blocks, repeats, nav, frame, notes) {
357
358
  const runs = []
358
359
  const owners = []
360
+ // A word that loses a run to the capture window is no longer whole: the
361
+ // glyphs of that run exist only in the page image, so the word must stay there.
362
+ const sources = []
363
+ const cut = new Set()
359
364
  let clippedRuns = 0
360
365
  for (let i = 0; i < layer.runs.length; i++) {
361
- if (!contains(frame, runBox(layer.runs[i]))) { clippedRuns++; continue }
366
+ const source = (layer.sources && layer.sources[i]) || null
367
+ if (!contains(frame, runBox(layer.runs[i]))) {
368
+ clippedRuns++
369
+ if (source) cut.add(source)
370
+ continue
371
+ }
362
372
  runs.push(layer.runs[i])
363
373
  owners.push(layer.owners[i])
374
+ sources.push(source)
364
375
  }
376
+ for (let i = 0; i < sources.length; i++) if (cut.has(sources[i])) sources[i] = null
365
377
  if (clippedRuns) {
366
378
  notes.push(`${clippedRuns} text run(s) crossing the snapdom clip edge were omitted ` +
367
379
  'from the searchable layer so clipped text cannot leak through extraction.')
@@ -376,7 +388,7 @@ function clipMeasurement(layer, blocks, repeats, nav, frame, notes) {
376
388
  const bottom = Math.min(frame.bottom, box.bottom)
377
389
  links.push({ ...link, x: left, y: top, width: right - left, height: bottom - top })
378
390
  }
379
- layer = { ...layer, runs, owners, links }
391
+ layer = { ...layer, runs, owners, links, sources }
380
392
 
381
393
  blocks = blocks.flatMap(b => {
382
394
  const top = Math.max(frame.top, b.top)
@@ -670,6 +682,9 @@ async function measureArtifact(url, meta, opts, source = {}) {
670
682
  // The @font-face rules behind the text, read NOW: this CSSOM dies with the
671
683
  // frame, and the export that wants the bytes runs after it is gone.
672
684
  fontRules: collectFaceRules(frameDoc),
685
+ // Whether wrapping a text node could move anything, also only readable now
686
+ // (`page-image.js`): the stylesheets that would react die with the frame.
687
+ wrapperInert: wrapperIsInert(frameDoc),
673
688
  intrinsic: {
674
689
  width: Number.isFinite(intrinsicW) && intrinsicW > 0 ? intrinsicW : meta.vbW,
675
690
  height: Number.isFinite(intrinsicH) && intrinsicH > 0 ? intrinsicH : meta.vbH,
@@ -718,7 +733,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
718
733
  watermark = null,
719
734
  fields = true,
720
735
  embedFonts = true,
721
- vectorText = false,
736
+ vectorText = true,
722
737
  encrypt: encryptSpec = null,
723
738
  meta: docMeta = null,
724
739
  } = options
@@ -839,9 +854,14 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
839
854
  let jpegRegions = 0
840
855
  let losslessRegions = 0
841
856
  const imageObjects = new WeakMap()
842
- const imageObject = async (crop = null) => {
857
+ let glyphsOut = null
858
+ // `cleared` asks for the page image without the text this export paints as
859
+ // glyphs (`glyphsOut`, below). Only the page's own pixels take it: a crop that
860
+ // stands in for typeset text — an index line, an empty field's face — is
861
+ // there precisely to show the letters.
862
+ const imageObject = async (crop = null, cleared = false) => {
843
863
  if (!raster) throw new Error('[snapdom-pdf] raster requested while image:false')
844
- const encoded = await raster(crop, magnify)
864
+ const encoded = await raster(crop, magnify, cleared ? glyphsOut : null)
845
865
  let saved = imageObjects.get(encoded)
846
866
  if (saved) return saved
847
867
  if (/DCTDecode/.test(encoded.dict)) jpegRegions++
@@ -1004,6 +1024,74 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1004
1024
  }
1005
1025
  let coverageFallbacks = 0
1006
1026
 
1027
+ /**
1028
+ * Whether a body run will be painted as real glyphs — `drawRun`'s own verdict,
1029
+ * reachable before any page is drawn because the page image needs it first.
1030
+ * The two must agree to the run: a text node is taken out of the image on this
1031
+ * answer, and only `drawRun` puts its glyphs back.
1032
+ */
1033
+ const paintsAsGlyphs = (run, faces) => {
1034
+ if (!vectorText || !run.color || run.rtl || !run.text || run.fk < 0) return false
1035
+ const face = faces[run.fk]
1036
+ if (!face || (faces.approx && faces.approx[run.fk])) return false
1037
+ for (const ch of run.text) {
1038
+ if (!face.parsed.cmap.has(ch.codePointAt(0))) return false
1039
+ }
1040
+ return true
1041
+ }
1042
+
1043
+ // The words the page image can do without: every run they produced is
1044
+ // painted as glyphs, on this export, by the rule above. A word with one run
1045
+ // that is not — a fragment the face lacks, a value that became a field — stays
1046
+ // in the image, and whatever of it is painted goes over it as it always did.
1047
+ //
1048
+ // With that list in hand a run is painted only if its word left the image, so
1049
+ // nothing on the page is drawn twice: a paintable run that cannot be taken
1050
+ // out — a form control's value, which is no text node, or a word with a
1051
+ // fragment that is not painted — stays in the image, as pixels.
1052
+ //
1053
+ // `raster.clears` is false on a core that cannot draw a revised image, and
1054
+ // `wrapperInert` when the capture's own CSS could react to the wrapping. Either
1055
+ // way nothing is cleared and painted runs go over the image, as they used to.
1056
+ const clearing = !!(image && text && vectorText && raster && raster.clears && measured.wrapperInert)
1057
+ const clearedRuns = new Set()
1058
+ if (clearing && layer.sources && layer.textNodes) {
1059
+ const whole = new Map()
1060
+ for (let i = 0; i < layer.runs.length; i++) {
1061
+ const source = layer.sources[i]
1062
+ if (!source) continue
1063
+ const painted = !suppressedRuns.has(i) && paintsAsGlyphs(layer.runs[i], bodyFaces)
1064
+ whole.set(source, whole.get(source) !== false && painted)
1065
+ }
1066
+ for (let i = 0; i < layer.runs.length; i++) {
1067
+ if (layer.sources[i] && whole.get(layer.sources[i])) clearedRuns.add(layer.runs[i])
1068
+ }
1069
+ const spans = new Map()
1070
+ let words = 0
1071
+ for (const [source, painted] of whole) {
1072
+ if (!painted) continue
1073
+ if (!spans.has(source.node)) spans.set(source.node, [])
1074
+ spans.get(source.node).push([source.from, source.to])
1075
+ words++
1076
+ }
1077
+ if (words) {
1078
+ const order = [...spans.keys()].sort((a, b) => a - b)
1079
+ for (const node of order) spans.get(node).sort((a, b) => a[0] - b[0])
1080
+ glyphsOut = {
1081
+ spans,
1082
+ words,
1083
+ total: layer.textNodes,
1084
+ // The encoded image is cached on the capture, across exports; an export
1085
+ // that paints different text must not be handed this one's image.
1086
+ key: order.map(node => `${node}:${spans.get(node).map(([a, b]) => `${a}-${b}`).join('.')}`).join(','),
1087
+ // Set by the raster once a revised image was really drawn. A core that
1088
+ // predates `editSvg` never sets it, and the export then says what it
1089
+ // did: painted over the image, as before.
1090
+ applied: false,
1091
+ }
1092
+ }
1093
+ }
1094
+
1007
1095
  /**
1008
1096
  * One short string of the PLUGIN's own text — a page number, a running head, a
1009
1097
  * watermark, a line of the generated index — encoded and measured.
@@ -1115,6 +1203,14 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1115
1203
  let unlinked = 0
1116
1204
  let vectorPainted = 0
1117
1205
  let vectorMissed = 0
1206
+ // Runs an embedded face could have painted, held back because the file does
1207
+ // not hold the design the page drew (a variable font off its default, a faked
1208
+ // bold or italic). One sentence per distinct reason, however many runs.
1209
+ let vectorHeld = 0
1210
+ const vectorHeldWhy = new Set()
1211
+ // Runs a face could paint, left in the page image because their word cannot
1212
+ // be taken out of it and painting them would draw them twice.
1213
+ let vectorKept = 0
1118
1214
  // Painted images nobody named, on body and matter pages alike. Any one of them
1119
1215
  // withholds the PDF/UA-1 claim.
1120
1216
  let unnamedImages = layer.unnamedImages
@@ -1299,7 +1395,25 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1299
1395
  // face that did not cover the run, a translucent or unresolved colour, a
1300
1396
  // word-spacing Type0 cannot express — stays as it was, shown by the raster
1301
1397
  // or, in an image-free export, lost and counted.
1302
- const paint = vectorText && embeddedUsed && run.color && !run.rtl
1398
+ //
1399
+ // And only where the file holds the glyphs the page PAINTED. A face embeds
1400
+ // whenever its file is readable, but a variable font off its default
1401
+ // instance, or a bold or italic the engine faked from the regular file, is
1402
+ // drawn by the page in a design the file does not contain (`faces.approx`).
1403
+ // Painting it would put regular letters where the page shows bold ones.
1404
+ const paintable = vectorText && embeddedUsed && run.color && !run.rtl
1405
+ const approx = paintable && run.fk >= 0 && faces.approx ? faces.approx[run.fk] : null
1406
+ // Painted once: over a page image that can give text up, only a run whose
1407
+ // word DID leave it is painted (`clearedRuns`). A cover or a colophon is
1408
+ // drawn from its own capture, which is not revised, and keeps the old rule.
1409
+ const twice = clearing && faces === bodyFaces && !clearedRuns.has(run)
1410
+ const paint = paintable && !approx && !twice
1411
+ if (approx) {
1412
+ vectorHeld++
1413
+ vectorHeldWhy.add(approx)
1414
+ } else if (paintable && twice) {
1415
+ vectorKept++
1416
+ }
1303
1417
  let tr = debugText ? 0 : 3
1304
1418
  let colorOp = ''
1305
1419
  // Letter-spacing rides `Tc`, NOT Tz: folding it into the horizontal scale
@@ -1316,8 +1430,11 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1316
1430
  natEff = natural + [...run.text].length * run.tracking
1317
1431
  }
1318
1432
  vectorPainted++
1319
- } else if (vectorText && !image && tr === 3) {
1433
+ } else if (options.vectorText === true && !image && tr === 3) {
1320
1434
  // Nothing will show this run: no raster beneath it, and it was not painted.
1435
+ // Counted only for a caller who ASKED for painted text. Painting is the
1436
+ // default now, and an image-free export that never mentioned it is the
1437
+ // searchable-layer-only file it always was, which has nothing to report.
1321
1438
  vectorMissed++
1322
1439
  }
1323
1440
  const tz = (natEff > 0 ? Math.max(1, Math.min(1000, (run.width / natEff) * 100)) : 100).toFixed(2)
@@ -1468,7 +1585,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1468
1585
  const regions = cropsFor(slice.top, slice.height)
1469
1586
  for (let j = 0; j < regions.length; j++) {
1470
1587
  const crop = regions[j]
1471
- const ref = await imageObject(crop)
1588
+ const ref = await imageObject(crop, true)
1472
1589
  const name = page === 'fit'
1473
1590
  ? `Im${j}`
1474
1591
  : `Ip${p}${j ? `_${j}` : ''}`
@@ -1509,7 +1626,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1509
1626
  const regions = cropsFor(b.top, height)
1510
1627
  for (let j = 0; j < regions.length; j++) {
1511
1628
  const crop = regions[j]
1512
- const ref = await imageObject(crop)
1629
+ const ref = await imageObject(crop, true)
1513
1630
  const name = `Ir${index}${j ? `_${j}` : ''}`
1514
1631
  pageXObjects.push(`/${name} ${ref.id} 0 R`)
1515
1632
  const contentY = (crop.y - offY) * k
@@ -2014,13 +2131,25 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
2014
2131
  }
2015
2132
  if (vectorText && vectorPainted) {
2016
2133
  report(`${vectorPainted} text run(s) painted as real vector glyphs from the embedded fonts — ` +
2017
- 'crisp at any zoom' + (image ? ', over the raster.' : ', and the raster is off.'))
2134
+ 'crisp at any zoom' + (!image ? ', and the raster is off.'
2135
+ : glyphsOut?.applied ? `, and ${glyphsOut.words} word(s) of them left out of the page image.`
2136
+ : ', over the raster.'))
2018
2137
  }
2019
2138
  if (vectorMissed) {
2020
- report(`${vectorMissed} text run(s) could not be painted as vector (RTL, no embedded face, or an ` +
2021
- 'unresolved colour) and there is no raster to show them — they are searchable but not visible. ' +
2139
+ report(`${vectorMissed} text run(s) could not be painted as vector (RTL, no embedded face, an ` +
2140
+ 'unresolved colour, or a face whose file does not hold the design the page drew) and there is ' +
2141
+ 'no raster to show them — they are searchable but not visible. ' +
2022
2142
  'Keep image:true for those, or embed a covering font.')
2023
2143
  }
2144
+ if (vectorKept) {
2145
+ report(`${vectorKept} text run(s) left as image instead of painted as vector glyphs, because they ` +
2146
+ 'cannot be taken out of the page image and would be drawn twice — the value of a form control, ' +
2147
+ 'or a word with a part that is not painted (clipped, hyphenated by the browser, missing from the font).')
2148
+ }
2149
+ if (vectorHeld) {
2150
+ report(`${vectorHeld} text run(s) left as image instead of painted as vector glyphs, because the ` +
2151
+ `font file does not hold the design the page drew — ${[...vectorHeldWhy].join('; ')}.`)
2152
+ }
2024
2153
  if (cropped) {
2025
2154
  report(`${cropped} index line(s) show the heading's own pixels rather than typeset text — ` +
2026
2155
  'their script is outside base-14, and this plugin embeds no fonts. They stay searchable.')
@@ -2292,16 +2421,30 @@ export default function pdf(defaults = {}) {
2292
2421
  // asked for, and only re-exporting the SAME capture at a different quality,
2293
2422
  // codec or background rasterizes twice.
2294
2423
  const imageCache = new Map()
2424
+ // Which cached images were drawn from a revised SVG, so a later export
2425
+ // served from the cache still knows what its page image holds.
2426
+ const imageApplied = new Set()
2295
2427
 
2296
2428
  const cropKey = (crop) => crop
2297
2429
  ? ['crop', crop.x, crop.y, crop.width, crop.height].map(String).join(':')
2298
2430
  : 'full'
2299
2431
  // `magnify` is the page's enlargement of the capture (`draw`), 1 with an absolute size.
2300
- const rasterFor = (options) => async (crop = null, magnify = 1) => {
2432
+ // The revised SVG per source text. The core hands over one of two strings —
2433
+ // the artifact, or the artifact with its compressed assets restored — once
2434
+ // per region, and re-parsing a page of markup for every crop of it is the
2435
+ // whole cost of this feature paid forty times.
2436
+ const revised = new Map()
2437
+ // `clear` is the export's list of text nodes to draw without their glyphs
2438
+ // (`page-image.js`); null draws the capture as captured.
2439
+ const rasterFor = (options) => async (crop = null, magnify = 1, clear = null) => {
2301
2440
  const key = JSON.stringify([
2302
2441
  cropKey(crop), magnify, options.quality, options.backgroundColor, options.codec,
2442
+ clear ? clear.key : null,
2303
2443
  ])
2304
- if (imageCache.has(key)) return imageCache.get(key)
2444
+ if (imageCache.has(key)) {
2445
+ if (clear && imageApplied.has(key)) clear.applied = true
2446
+ return imageCache.get(key)
2447
+ }
2305
2448
  const promise = Promise.resolve().then(async () => {
2306
2449
  // Alpha is kept here; background flattening belongs to encodeImage.
2307
2450
  const canvas = await facade.canvas({
@@ -2310,6 +2453,22 @@ export default function pdf(defaults = {}) {
2310
2453
  height: absoluteSize ? (crop?.height ?? meta.vbH) * captureDensity : null,
2311
2454
  scale: rasterScale * magnify,
2312
2455
  ...(crop ? { crop } : {}),
2456
+ ...(clear ? {
2457
+ editSvg: (svg) => {
2458
+ let memo = revised.get(svg)
2459
+ if (!memo || memo.key !== clear.key) {
2460
+ if (revised.size > 3) revised.clear()
2461
+ memo = { key: clear.key, out: withoutGlyphs(svg, clear.spans, clear.total) }
2462
+ revised.set(svg, memo)
2463
+ }
2464
+ const out = memo.out
2465
+ if (out) {
2466
+ clear.applied = true
2467
+ imageApplied.add(key)
2468
+ }
2469
+ return out
2470
+ },
2471
+ } : {}),
2313
2472
  })
2314
2473
  return encodeImage(canvas, {
2315
2474
  quality: options.quality,
@@ -2321,6 +2480,8 @@ export default function pdf(defaults = {}) {
2321
2480
  promise.catch(() => { if (imageCache.get(key) === promise) imageCache.delete(key) })
2322
2481
  return promise
2323
2482
  }
2483
+ /** Whether this core can draw a revised copy of the capture (`editSvg`, PLUGIN_SPEC.md). */
2484
+ const clears = facade?.editSvg === true
2324
2485
  const measuredForCapture = () => {
2325
2486
  if (!measuredPromise) measuredPromise = measureArtifact(artifactURL, meta, pluginDefaults, source)
2326
2487
  return measuredPromise
@@ -2412,7 +2573,7 @@ export default function pdf(defaults = {}) {
2412
2573
  }
2413
2574
  notes.push(...measured.notes)
2414
2575
 
2415
- const raster = options.image === false ? null : rasterFor(options)
2576
+ const raster = options.image === false ? null : Object.assign(rasterFor(options), { clears })
2416
2577
  const { blob, stats } = await draw({ measured, raster, meta, options, report, flow })
2417
2578
  for (const n of notes) warn(n)
2418
2579
  onReport?.(buildReport({
package/src/mega/fonts.js CHANGED
@@ -9,8 +9,8 @@
9
9
  * unicode-range subset that covers what this style paints
10
10
  * rule → bytes a data: URI inlined by snapdom, or the src URL fetched
11
11
  * force-cache (the page already downloaded it to paint)
12
- * bytes → sfnt WOFF unpacks; WOFF2, collections and license-restricted
13
- * faces refuse, each with its reason
12
+ * bytes → sfnt WOFF unpacks and WOFF2 is rebuilt; collections and
13
+ * license-restricted faces refuse, each with its reason
14
14
  *
15
15
  * Whatever survives becomes ONE parsed face per underlying file, shared by
16
16
  * every style that matched it. Whatever does not is a named diagnostic, never
@@ -24,9 +24,11 @@
24
24
  * textLength contract) would throw away a page of embeddable Latin over one
25
25
  * stray dingbat.
26
26
  *
27
- * The sibling vector product solves the same problem the same way — same rule
28
- * reading, same matching order — so the two channels embed the same file for
29
- * the same page or disagree loudly, never quietly.
27
+ * A face that embeds is not always the face the page PAINTED. A variable font
28
+ * is one file holding a range of designs, and a PDF draws only the one it was
29
+ * saved in; a bold or an italic the page never loaded is the regular file,
30
+ * fattened or slanted by the engine. `substitution` says so per style, and the
31
+ * export keeps such text in the page image instead of painting the wrong glyphs.
30
32
  */
31
33
 
32
34
  import { sfntFromBytes, parseFont } from '../writer/font.js'
@@ -195,6 +197,94 @@ function coversAll(rule, points) {
195
197
  return true
196
198
  }
197
199
 
200
+ /**
201
+ * The variation axes of an sfnt (`fvar`): [{tag, min, def, max}], empty for a
202
+ * static font and for a table too short to be read.
203
+ */
204
+ export function variationAxes(sfnt) {
205
+ const u16 = (at) => (sfnt[at] << 8) | sfnt[at + 1]
206
+ const u32 = (at) => ((sfnt[at] << 24) | (sfnt[at + 1] << 16) | (sfnt[at + 2] << 8) | sfnt[at + 3]) >>> 0
207
+ const fixed = (at) => (u32(at) | 0) / 65536
208
+ const out = []
209
+ const numTables = u16(4)
210
+ for (let i = 0; i < numTables; i++) {
211
+ const entry = 12 + i * 16
212
+ if (entry + 16 > sfnt.length) return out
213
+ if (u32(entry) !== 0x66766172) continue // 'fvar'
214
+ const table = u32(entry + 8)
215
+ if (table + 16 > sfnt.length) return out
216
+ const axes = table + u16(table + 4)
217
+ const count = u16(table + 8)
218
+ const size = u16(table + 10)
219
+ for (let a = 0; a < count; a++) {
220
+ const axis = axes + a * size
221
+ if (size < 16 || axis + 16 > sfnt.length) return out
222
+ out.push({
223
+ tag: String.fromCharCode(sfnt[axis], sfnt[axis + 1], sfnt[axis + 2], sfnt[axis + 3]),
224
+ min: fixed(axis + 4), def: fixed(axis + 8), max: fixed(axis + 12),
225
+ })
226
+ }
227
+ return out
228
+ }
229
+ return out
230
+ }
231
+
232
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
233
+
234
+ /** At and above this weight an engine fattens a face that is lighter than it. */
235
+ const BOLD = 600
236
+
237
+ /**
238
+ * Why the glyphs in the file are NOT the glyphs the page painted for this
239
+ * style, or null when they are.
240
+ *
241
+ * Three things stand between a file and the paint. A variable font is drawn at
242
+ * the instance the style asks for, and the file read as a plain font is only
243
+ * its default instance. A weight the family does not carry is faked by
244
+ * emboldening the nearest face, and an italic it does not carry by slanting the
245
+ * upright one — unless `font-synthesis` forbids it. Everything here is read
246
+ * from the rule that won and the file behind it, never guessed from a name.
247
+ *
248
+ * @param {{weight: string, style: string}} rule the @font-face that matched
249
+ * @param {{weight: number, italic: boolean, stretch?: number, tuned?: boolean,
250
+ * fakeBold?: boolean, fakeItalic?: boolean}} fk
251
+ * @param {Array<{tag: string, min: number, def: number, max: number}>} axes
252
+ * @returns {string|null}
253
+ */
254
+ export function substitution(rule, fk, axes) {
255
+ const [lo, hi] = weightRange(rule.weight)
256
+ const ruleItalic = /^(italic|oblique)/.test((rule.style || 'normal').trim())
257
+ const axis = (tag) => axes.find(a => a.tag === tag && a.max > a.min) || null
258
+
259
+ if (axes.some(a => a.max > a.min) && fk.tuned) {
260
+ return 'the page sets font-variation-settings on a variable font, and a PDF draws only the design the file was saved in'
261
+ }
262
+ const wght = axis('wght')
263
+ if (wght) {
264
+ const drawn = clamp(clamp(fk.weight, lo, hi), wght.min, wght.max)
265
+ if (drawn !== wght.def) {
266
+ return `it is a variable font the page draws at weight ${drawn}, and a PDF draws only the weight the file was saved in (${wght.def})`
267
+ }
268
+ }
269
+ if (fk.weight >= BOLD && hi < BOLD && fk.fakeBold !== false) {
270
+ return 'the page has no bold file for it, so the browser fattens the regular one; the file holds only the regular glyphs'
271
+ }
272
+ if (fk.italic && (axis('slnt') || axis('ital'))) {
273
+ return 'it is a variable font the page slants along an axis, and a PDF draws only the upright design the file was saved in'
274
+ }
275
+ if (fk.italic && !ruleItalic && fk.fakeItalic !== false) {
276
+ return 'the page has no italic file for it, so the browser slants the upright one; the file holds only the upright glyphs'
277
+ }
278
+ const wdth = axis('wdth')
279
+ if (wdth && clamp(fk.stretch ?? 100, wdth.min, wdth.max) !== wdth.def) {
280
+ return 'it is a variable font the page draws at another width, and a PDF draws only the width the file was saved in'
281
+ }
282
+ if (axis('opsz')) {
283
+ return 'it is a variable font with an optical-size axis that follows the font size, and a PDF draws only the size the file was saved in'
284
+ }
285
+ return null
286
+ }
287
+
198
288
  async function fetchBytes(url, timeout) {
199
289
  const controller = typeof AbortController === 'function' ? new AbortController() : null
200
290
  const timer = controller && timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null
@@ -218,8 +308,12 @@ async function fetchBytes(url, timeout) {
218
308
  * @param {Array<object>} rules `collectFaceRules` output, captured at measure
219
309
  * @param {Map} cache capture-lifetime: url/data-uri → {parsed, sfnt}|{error}
220
310
  * @param {(msg: string) => void} report
221
- * @returns {Promise<Array<{parsed, sfnt, label}|null>>} parallel to fontKeys;
222
- * entries are SHARED where two keys resolved to one file.
311
+ * @returns {Promise<Array<{parsed, sfnt, label}|null> & {approx: Array<string|null>}>}
312
+ * parallel to fontKeys; entries are SHARED where two keys resolved to one
313
+ * file. `approx`, parallel too, is null where the file's glyphs are what the
314
+ * page painted for that key and otherwise the sentence saying why they are
315
+ * not (`substitution`): such a face still embeds, and still must not be
316
+ * painted with.
223
317
  */
224
318
  export async function resolveFaces(fontKeys, pointsOfFk, rules, cache, report) {
225
319
  const byFamily = new Map()
@@ -231,11 +325,13 @@ export async function resolveFaces(fontKeys, pointsOfFk, rules, cache, report) {
231
325
 
232
326
  const faceByUrl = new Map()
233
327
  const out = []
328
+ out.approx = []
234
329
  const failed = new Map() // one sentence per distinct failure, however many keys hit it
235
330
 
236
331
  for (let i = 0; i < fontKeys.length; i++) {
237
332
  const fk = fontKeys[i]
238
333
  out.push(null)
334
+ out.approx.push(null)
239
335
  const points = pointsOfFk[i] || new Set()
240
336
  for (const name of splitTop(fk.stack, ',').map(unquote)) {
241
337
  if (!name || GENERIC.has(name.toLowerCase())) continue
@@ -249,8 +345,13 @@ export async function resolveFaces(fontKeys, pointsOfFk, rules, cache, report) {
249
345
  const label = `"${winner.family}" ${fk.weight}${fk.italic ? ' italic' : ''}`
250
346
 
251
347
  let face = null
348
+ let why = null
252
349
  for (const url of srcCandidates(winner.src, winner.base)) {
253
- if (faceByUrl.has(url)) { face = faceByUrl.get(url); break }
350
+ if (faceByUrl.has(url)) {
351
+ face = faceByUrl.get(url)
352
+ why = substitution(winner, fk, face.axes)
353
+ break
354
+ }
254
355
  let entry = cache.get(url)
255
356
  if (!entry) {
256
357
  const bytes = /^data:/i.test(url) ? dataUriBytes(url) : await fetchBytes(url, 8000)
@@ -262,19 +363,25 @@ export async function resolveFaces(fontKeys, pointsOfFk, rules, cache, report) {
262
363
  entry = { error: container.error }
263
364
  } else {
264
365
  const parsed = parseFont(container.sfnt)
265
- entry = parsed.error ? { error: parsed.error } : { parsed, sfnt: container.sfnt }
366
+ entry = parsed.error
367
+ ? { error: parsed.error }
368
+ : { parsed, sfnt: container.sfnt, axes: variationAxes(container.sfnt) }
266
369
  }
267
370
  }
268
371
  cache.set(url, entry)
269
372
  }
270
373
  if (!entry.error) {
271
- face = { parsed: entry.parsed, sfnt: entry.sfnt, label }
374
+ face = { parsed: entry.parsed, sfnt: entry.sfnt, label, axes: entry.axes || [] }
272
375
  faceByUrl.set(url, face)
376
+ why = substitution(winner, fk, face.axes)
273
377
  break
274
378
  }
275
379
  failed.set(`${label}: ${entry.error}`, true)
276
380
  }
277
- if (face) out[i] = face
381
+ if (face) {
382
+ out[i] = face
383
+ out.approx[i] = why && `"${winner.family}" ${fk.weight}${fk.italic ? ' italic' : ''}: ${why}`
384
+ }
278
385
  break // first non-generic family with rules decides, matching the browser
279
386
  }
280
387
  }