@zumer/snapdom-pdf 1.0.0 → 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/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)
@@ -630,11 +642,31 @@ async function measureArtifact(url, meta, opts, source = {}) {
630
642
  frameDoc.head.prepend(base)
631
643
  const svg = frameDoc.importNode(parsed.documentElement, true)
632
644
  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
645
  const fo = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'foreignObject')[0] ||
636
646
  svg.querySelector('foreignObject')
637
647
  const container = fo && [...fo.children].find(el => el.localName === 'div')
648
+ // On a screen that lays out on the device grid, snapdom lays the raster's copy out
649
+ // under `zoom: devicePixelRatio` on this container, with `scale(1 / zoom)` on the
650
+ // <g> around the foreignObject (layoutZoom, #508). Mounted inline under this page's
651
+ // own dpr that wrapper laid out at zoom x dpr, and the text layer took the scale but
652
+ // not the zoom, so on a Retina Mac every run came out at half its size with its
653
+ // baseline half an ascent high and the selection sat over the top of the words.
654
+ // Undone the way the core's svg file export undoes it (#552), which lays the clone
655
+ // out at the page's dpr, the grid the raster was laid out on. Pinned by
656
+ // test/verify.mjs `hidpi`.
657
+ const zoom = parseFloat(container?.style.zoom) || 1
658
+ if (zoom !== 1) {
659
+ container.style.removeProperty('zoom')
660
+ for (const name of ['x', 'y', 'width', 'height']) {
661
+ fo.setAttribute(name, String(Number(fo.getAttribute(name)) / zoom))
662
+ }
663
+ const group = fo.parentNode
664
+ if (group.localName === 'g') {
665
+ group.setAttribute('transform', group.getAttribute('transform').replace(/scale\([^)]*\)/, '').trim())
666
+ }
667
+ }
668
+ frameDoc.body.appendChild(svg)
669
+ if (frameDoc.fonts?.ready) await frameDoc.fonts.ready
638
670
  const root = container?.firstElementChild
639
671
  if (!root) throw new Error('[snapdom-pdf] the final SVG has no measurable capture root')
640
672
  const svgRect = svg.getBoundingClientRect()
@@ -650,6 +682,9 @@ async function measureArtifact(url, meta, opts, source = {}) {
650
682
  // The @font-face rules behind the text, read NOW: this CSSOM dies with the
651
683
  // frame, and the export that wants the bytes runs after it is gone.
652
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),
653
688
  intrinsic: {
654
689
  width: Number.isFinite(intrinsicW) && intrinsicW > 0 ? intrinsicW : meta.vbW,
655
690
  height: Number.isFinite(intrinsicH) && intrinsicH > 0 ? intrinsicH : meta.vbH,
@@ -698,7 +733,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
698
733
  watermark = null,
699
734
  fields = true,
700
735
  embedFonts = true,
701
- vectorText = false,
736
+ vectorText = true,
702
737
  encrypt: encryptSpec = null,
703
738
  meta: docMeta = null,
704
739
  } = options
@@ -746,7 +781,8 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
746
781
  if (!spec || spec.kind !== 'element') continue
747
782
  const band = await captureBand(spec.el, {
748
783
  scale: options.scale, dpr: options.dpr, backgroundColor: null, quality, codec,
749
- availW: provisionalW, captureOptions: options.captureOptions,
784
+ availW: provisionalW, fitW: options.rasterDensity == null ? provisionalW : 0,
785
+ captureOptions: options.captureOptions,
750
786
  }, encodeOpaque)
751
787
  capturedBands.set(where, band)
752
788
  }
@@ -761,6 +797,13 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
761
797
 
762
798
  const geo = pageBox({ page, orientation, margin, contentW, contentH, headerH, footerH, report })
763
799
  const { pageW, pageH, marginX, marginY, availW, availH, contentTop, k, scaledH } = geo
800
+ // A paper size that enlarges the capture to its printable width enlarged the
801
+ // pixels with it. The site's 340px demo card fills A4 at 2.15x, and its dpr 2
802
+ // capture came out at 89 dpi under text a reader zooms into. Rasterizing at the
803
+ // printed size keeps the capture's dpr per CSS px of paper (192 dpi there). A page
804
+ // that shrinks the capture keeps every pixel the capture had, and an absolute
805
+ // width/height is the caller's pixel budget. Pinned by test/verify.mjs `density`.
806
+ const magnify = options.rasterDensity == null ? Math.max(1, geo.drawScale) : 1
764
807
 
765
808
  // Viewport CSS px → content points.
766
809
  const toContentX = (vx) => (vx - rect.left) * k
@@ -811,9 +854,14 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
811
854
  let jpegRegions = 0
812
855
  let losslessRegions = 0
813
856
  const imageObjects = new WeakMap()
814
- 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) => {
815
863
  if (!raster) throw new Error('[snapdom-pdf] raster requested while image:false')
816
- const encoded = await raster(crop)
864
+ const encoded = await raster(crop, magnify, cleared ? glyphsOut : null)
817
865
  let saved = imageObjects.get(encoded)
818
866
  if (saved) return saved
819
867
  if (/DCTDecode/.test(encoded.dict)) jpegRegions++
@@ -975,7 +1023,74 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
975
1023
  }
976
1024
  }
977
1025
  let coverageFallbacks = 0
978
- const systemStacks = new Set()
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
+ }
979
1094
 
980
1095
  /**
981
1096
  * One short string of the PLUGIN's own text — a page number, a running head, a
@@ -1088,6 +1203,14 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1088
1203
  let unlinked = 0
1089
1204
  let vectorPainted = 0
1090
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
1091
1214
  // Painted images nobody named, on body and matter pages alike. Any one of them
1092
1215
  // withholds the PDF/UA-1 claim.
1093
1216
  let unnamedImages = layer.unnamedImages
@@ -1159,7 +1282,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1159
1282
  // canvas. Bound both stages with the same side/area ceilings as toCanvas.
1160
1283
  const intrinsicW = measured.intrinsic?.width > 0 ? measured.intrinsic.width : vbW
1161
1284
  const intrinsicH = measured.intrinsic?.height > 0 ? measured.intrinsic.height : vbH
1162
- const pixelFactor = options.scale * options.dpr
1285
+ const pixelFactor = options.scale * options.dpr * magnify
1163
1286
  const densityX = options.rasterDensity != null
1164
1287
  ? Math.max(intrinsicW / vbW, options.rasterDensity * options.dpr)
1165
1288
  : intrinsicW / vbW * pixelFactor
@@ -1272,7 +1395,25 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1272
1395
  // face that did not cover the run, a translucent or unresolved colour, a
1273
1396
  // word-spacing Type0 cannot express — stays as it was, shown by the raster
1274
1397
  // or, in an image-free export, lost and counted.
1275
- 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
+ }
1276
1417
  let tr = debugText ? 0 : 3
1277
1418
  let colorOp = ''
1278
1419
  // Letter-spacing rides `Tc`, NOT Tz: folding it into the horizontal scale
@@ -1289,8 +1430,11 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1289
1430
  natEff = natural + [...run.text].length * run.tracking
1290
1431
  }
1291
1432
  vectorPainted++
1292
- } else if (vectorText && !image && tr === 3) {
1433
+ } else if (options.vectorText === true && !image && tr === 3) {
1293
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.
1294
1438
  vectorMissed++
1295
1439
  }
1296
1440
  const tz = (natEff > 0 ? Math.max(1, Math.min(1000, (run.width / natEff) * 100)) : 100).toFixed(2)
@@ -1441,7 +1585,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1441
1585
  const regions = cropsFor(slice.top, slice.height)
1442
1586
  for (let j = 0; j < regions.length; j++) {
1443
1587
  const crop = regions[j]
1444
- const ref = await imageObject(crop)
1588
+ const ref = await imageObject(crop, true)
1445
1589
  const name = page === 'fit'
1446
1590
  ? `Im${j}`
1447
1591
  : `Ip${p}${j ? `_${j}` : ''}`
@@ -1482,7 +1626,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1482
1626
  const regions = cropsFor(b.top, height)
1483
1627
  for (let j = 0; j < regions.length; j++) {
1484
1628
  const crop = regions[j]
1485
- const ref = await imageObject(crop)
1629
+ const ref = await imageObject(crop, true)
1486
1630
  const name = `Ir${index}${j ? `_${j}` : ''}`
1487
1631
  pageXObjects.push(`/${name} ${ref.id} 0 R`)
1488
1632
  const contentY = (crop.y - offY) * k
@@ -1635,17 +1779,6 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1635
1779
  }
1636
1780
  const paginated = page !== 'fit'
1637
1781
 
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
1782
  /**
1650
1783
  * A cover or a colophon: your own element, captured, one to a page — and given
1651
1784
  * the SAME invisible text layer the body gets.
@@ -1662,7 +1795,7 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1662
1795
  const shot = await captureElement(el, {
1663
1796
  scale: options.scale, dpr: options.dpr, backgroundColor: null, quality, codec,
1664
1797
  captureOptions: options.captureOptions,
1665
- image,
1798
+ image, fitW: options.rasterDensity == null ? pageW : 0,
1666
1799
  }, image ? encodeOpaque : null)
1667
1800
  const subMeasured = await measureArtifact(shot.url, shot.meta, {
1668
1801
  formValues: measured.formValues !== false,
@@ -1998,13 +2131,25 @@ async function draw({ measured, raster, meta, options, report, flow = null }) {
1998
2131
  }
1999
2132
  if (vectorText && vectorPainted) {
2000
2133
  report(`${vectorPainted} text run(s) painted as real vector glyphs from the embedded fonts — ` +
2001
- '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.'))
2002
2137
  }
2003
2138
  if (vectorMissed) {
2004
- report(`${vectorMissed} text run(s) could not be painted as vector (RTL, no embedded face, or an ` +
2005
- '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. ' +
2006
2142
  'Keep image:true for those, or embed a covering font.')
2007
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
+ }
2008
2153
  if (cropped) {
2009
2154
  report(`${cropped} index line(s) show the heading's own pixels rather than typeset text — ` +
2010
2155
  'their script is outside base-14, and this plugin embeds no fonts. They stay searchable.')
@@ -2276,23 +2421,54 @@ export default function pdf(defaults = {}) {
2276
2421
  // asked for, and only re-exporting the SAME capture at a different quality,
2277
2422
  // codec or background rasterizes twice.
2278
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()
2279
2427
 
2280
2428
  const cropKey = (crop) => crop
2281
2429
  ? ['crop', crop.x, crop.y, crop.width, crop.height].map(String).join(':')
2282
2430
  : 'full'
2283
- const rasterFor = (options) => async (crop = null) => {
2431
+ // `magnify` is the page's enlargement of the capture (`draw`), 1 with an absolute size.
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) => {
2284
2440
  const key = JSON.stringify([
2285
- cropKey(crop), options.quality, options.backgroundColor, options.codec,
2441
+ cropKey(crop), magnify, options.quality, options.backgroundColor, options.codec,
2442
+ clear ? clear.key : null,
2286
2443
  ])
2287
- 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
+ }
2288
2448
  const promise = Promise.resolve().then(async () => {
2289
2449
  // Alpha is kept here; background flattening belongs to encodeImage.
2290
2450
  const canvas = await facade.canvas({
2291
2451
  backgroundColor: null,
2292
2452
  width: absoluteSize ? (crop?.width ?? meta.vbW) * captureDensity : null,
2293
2453
  height: absoluteSize ? (crop?.height ?? meta.vbH) * captureDensity : null,
2294
- scale: rasterScale,
2454
+ scale: rasterScale * magnify,
2295
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
+ } : {}),
2296
2472
  })
2297
2473
  return encodeImage(canvas, {
2298
2474
  quality: options.quality,
@@ -2304,6 +2480,8 @@ export default function pdf(defaults = {}) {
2304
2480
  promise.catch(() => { if (imageCache.get(key) === promise) imageCache.delete(key) })
2305
2481
  return promise
2306
2482
  }
2483
+ /** Whether this core can draw a revised copy of the capture (`editSvg`, PLUGIN_SPEC.md). */
2484
+ const clears = facade?.editSvg === true
2307
2485
  const measuredForCapture = () => {
2308
2486
  if (!measuredPromise) measuredPromise = measureArtifact(artifactURL, meta, pluginDefaults, source)
2309
2487
  return measuredPromise
@@ -2343,8 +2521,7 @@ export default function pdf(defaults = {}) {
2343
2521
  // the engine has no opinion about.
2344
2522
  for (const gone of ['mode', 'vector', 'scale', 'background', 'filename', 'compress']) {
2345
2523
  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.')
2524
+ report(`\`${gone}\` is not a PDF option (the package README lists them). Ignored.`)
2348
2525
  }
2349
2526
  }
2350
2527
 
@@ -2396,7 +2573,7 @@ export default function pdf(defaults = {}) {
2396
2573
  }
2397
2574
  notes.push(...measured.notes)
2398
2575
 
2399
- const raster = options.image === false ? null : rasterFor(options)
2576
+ const raster = options.image === false ? null : Object.assign(rasterFor(options), { clears })
2400
2577
  const { blob, stats } = await draw({ measured, raster, meta, options, report, flow })
2401
2578
  for (const n of notes) warn(n)
2402
2579
  onReport?.(buildReport({
@@ -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/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
  }