@zumer/snapdom-pdf 0.0.0-stage → 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.
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Front and back matter: a cover, a generated index, a closing page.
3
+ *
4
+ * These are the pages that are NOT the capture. A cover and a colophon are
5
+ * captured elements of your own — same engine, same fidelity, whatever CSS you
6
+ * put in them — placed one to a page. The index is the opposite: it is generated,
7
+ * because its content does not exist anywhere until pagination has happened, and
8
+ * it is drawn as REAL PDF TEXT so its links are live, its type is crisp at any
9
+ * zoom and it costs a few hundred bytes rather than another raster.
10
+ *
11
+ * The index is only possible at all because `nav.js` already had to find the
12
+ * headings and `index.js` already had to place them on pages. Nothing here reads
13
+ * the DOM: it is handed finished entries and lays them out.
14
+ *
15
+ * Front matter is deliberately OUTSIDE the page numbering. A cover that says
16
+ * "1 / 14" is a cover nobody would ship, and an index that counts itself makes
17
+ * every number in it disagree with the number printed on the page it names.
18
+ */
19
+
20
+ const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i
21
+
22
+ function rgb(colour) {
23
+ const m = HEX.exec(String(colour || '').trim())
24
+ if (!m) return null
25
+ let h = m[1]
26
+ if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2]
27
+ const n = parseInt(h, 16)
28
+ return [(n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255]
29
+ }
30
+
31
+ /**
32
+ * Content-stream ops that place a captured page image inside the page box:
33
+ * scaled to fit and centred, aspect preserved, margins ignored.
34
+ *
35
+ * Fit rather than fill, so nothing is ever cropped — a cover whose title is cut
36
+ * off is a worse failure than one with a band of paper down its side. Design the
37
+ * element at the page's aspect ratio and fit IS full bleed.
38
+ *
39
+ * @param {{name: string, pageW: number, pageH: number, aspect: number}} args
40
+ * `aspect` is height / width of the captured element.
41
+ */
42
+ export function fullPageOps({ name, pageW, pageH, aspect }) {
43
+ const ratio = aspect > 0 ? aspect : 1
44
+ let w = pageW
45
+ let h = w * ratio
46
+ if (h > pageH) { h = pageH; w = h / ratio }
47
+ return [
48
+ 'q',
49
+ `${w.toFixed(3)} 0 0 ${h.toFixed(3)} ${((pageW - w) / 2).toFixed(3)} ${((pageH - h) / 2).toFixed(3)} cm`,
50
+ `/${name} Do`,
51
+ 'Q',
52
+ ]
53
+ }
54
+
55
+ /**
56
+ * Normalise the `toc` option. `true` has to be the whole feature, because for
57
+ * most documents "put an index in" is the entire thought.
58
+ *
59
+ * @returns {{title: string, levels: number, size: number, font: string,
60
+ * indent: number, dots: boolean, colour: number[], leader: number[]}|null}
61
+ */
62
+ export function tocSpec(option) {
63
+ if (!option) return null
64
+ const o = option === true ? {} : (typeof option === 'string' ? { title: option } : option)
65
+ return {
66
+ title: o.title == null ? 'Contents' : String(o.title),
67
+ // Depth, not heading level: an index of a document that starts at h2 should
68
+ // still show two tiers, and depth is what the outline already nests by.
69
+ levels: Number.isFinite(o.levels) && o.levels > 0 ? Math.floor(o.levels) : 3,
70
+ size: Number.isFinite(o.size) && o.size > 0 ? o.size : 10,
71
+ font: o.font === 'serif' || o.font === 'mono' || o.font === 'sans'
72
+ ? o.font
73
+ // The document's own embedded face when the export has one; an explicit
74
+ // base-14 request keeps meaning exactly what it says.
75
+ : 'document',
76
+ indent: Number.isFinite(o.indent) ? o.indent : 14,
77
+ // The number as the index PRINTS it. Plain by default, which is the numeral
78
+ // the standard "3 / 12" page number carries — override it in step with
79
+ // `pageNumbers.format` if you renumber, or the two will disagree in print.
80
+ label: typeof o.label === 'function' ? o.label : (n) => String(n),
81
+ dots: o.dots !== false,
82
+ colour: rgb(o.color ?? o.colour) || [0.1, 0.11, 0.13],
83
+ leader: rgb(o.leaderColor ?? o.leaderColour) || [0.72, 0.74, 0.78],
84
+ }
85
+ }
86
+
87
+ /** Cut a title down until it fits, and say so with an ellipsis. */
88
+ export function fitText(text, room, measure) {
89
+ if (measure(text) <= room) return text
90
+ let lo = 0
91
+ let hi = text.length
92
+ while (lo < hi) {
93
+ const mid = Math.ceil((lo + hi) / 2)
94
+ if (measure(text.slice(0, mid) + '…') <= room) lo = mid
95
+ else hi = mid - 1
96
+ }
97
+ return lo > 0 ? text.slice(0, lo) + '…' : ''
98
+ }
99
+
100
+ /**
101
+ * Lay the index out into pages.
102
+ *
103
+ * @param {object} args
104
+ * @param {Array<{depth:number, title:string, dest:string, label:string}>} args.entries
105
+ * `dest` is a finished PDF destination array string and `label` the page number
106
+ * as it is PRINTED on the page it names — this file never computes either, so an
107
+ * index can never disagree with the page it points at.
108
+ * @param {(text: string, key: string, size: number) => ({str, font, width}|null)} args.pdfText
109
+ * @returns {Array<{ops: string[], annots: Array<{rect: number[], dest: string}>, fonts: Set, xobjects: Set}>}
110
+ * one entry per index page, in order.
111
+ */
112
+ export function tocLayout({ entries, spec, pdfText, drawTitle, marginX, availW, contentTop, availH }) {
113
+ const line = spec.size * 1.75
114
+ const headSize = spec.size * 1.8
115
+ const headRoom = spec.title.trim() ? headSize * 2.4 : 0
116
+
117
+ const pages = []
118
+ let page = null
119
+ let y = 0
120
+ let room = 0
121
+
122
+ const open = (first) => {
123
+ page = { ops: ['q'], annots: [], fonts: new Set(), xobjects: new Set() }
124
+ pages.push(page)
125
+ y = contentTop
126
+ room = availH
127
+ if (first && headRoom) {
128
+ const head = pdfText(spec.title, `${spec.font}-bold`, headSize)
129
+ if (head) {
130
+ page.fonts.add(head.font)
131
+ page.ops.push(`${spec.colour.map(c => c.toFixed(3)).join(' ')} rg`)
132
+ page.ops.push(`BT 0 Tr /${head.font.name} ${headSize.toFixed(3)} Tf 1 0 0 1 ` +
133
+ `${marginX.toFixed(3)} ${(y - headSize).toFixed(3)} Tm ${head.str} Tj ET`)
134
+ }
135
+ y -= headRoom
136
+ room -= headRoom
137
+ }
138
+ }
139
+ open(true)
140
+
141
+ for (const entry of entries) {
142
+ if (room < line) open(false)
143
+ const baseline = y - spec.size
144
+ const key = entry.depth === 0 ? `${spec.font}-bold` : spec.font
145
+ const label = pdfText(entry.label, spec.font, spec.size)
146
+ const labelW = label ? label.width : 0
147
+ const indent = entry.depth * spec.indent
148
+ const left = marginX + indent
149
+ // Room for the title is everything the number and one em of breathing space
150
+ // do not already claim.
151
+ const titleRoom = availW - indent - labelW - spec.size * 2
152
+
153
+ // How a title gets onto the page is the CALLER's problem, because the answer
154
+ // depends on the script: base-14 text where WinAnsi can address it, and a crop
155
+ // of the heading's own pixels where it cannot. This file owns the layout and
156
+ // knows nothing about rasters.
157
+ const drawn = titleRoom > 0
158
+ ? drawTitle({ entry, key, size: spec.size, x: left, baseline, room: titleRoom, colour: spec.colour })
159
+ : null
160
+ if (drawn) {
161
+ for (const f of drawn.fonts || []) page.fonts.add(f)
162
+ // A title drawn as a CROP of the page raster needs that raster in the index
163
+ // page's own resources — the fonts are not the only thing a line can borrow.
164
+ for (const x of drawn.xobjects || []) page.xobjects.add(x)
165
+ page.ops.push(...drawn.ops)
166
+ }
167
+ if (label) {
168
+ page.fonts.add(label.font)
169
+ page.ops.push(`BT 0 Tr /${label.font.name} ${spec.size} Tf 1 0 0 1 ` +
170
+ `${(marginX + availW - labelW).toFixed(3)} ${baseline.toFixed(3)} Tm ${label.str} Tj ET`)
171
+ }
172
+ // Leaders as a dashed rule rather than a run of full stops: a row of '.'
173
+ // glyphs is a row of glyphs an extractor returns as text, and an index whose
174
+ // copy-paste is "Introduction......3" is worse than one with no leader.
175
+ if (spec.dots && drawn && drawn.width > 0 && label) {
176
+ const from = left + drawn.width + spec.size * 0.6
177
+ const to = marginX + availW - labelW - spec.size * 0.6
178
+ if (to - from > spec.size) {
179
+ page.ops.push('q', `${spec.leader.map(c => c.toFixed(3)).join(' ')} RG`,
180
+ `0.7 w [0.7 ${(spec.size * 0.28).toFixed(2)}] 0 d 1 J`,
181
+ `${from.toFixed(3)} ${(baseline + spec.size * 0.25).toFixed(3)} m ` +
182
+ `${to.toFixed(3)} ${(baseline + spec.size * 0.25).toFixed(3)} l S`, 'Q')
183
+ }
184
+ }
185
+ // The whole line is the target, not just the words: an index nobody can hit
186
+ // without aiming is an index people scroll past.
187
+ if (entry.dest) {
188
+ page.annots.push({
189
+ rect: [marginX, baseline - spec.size * 0.3, marginX + availW, baseline + spec.size],
190
+ dest: entry.dest,
191
+ })
192
+ }
193
+
194
+ y -= line
195
+ room -= line
196
+ }
197
+
198
+ for (const p of pages) p.ops.push('Q')
199
+ return pages
200
+ }
@@ -0,0 +1,402 @@
1
+ /**
2
+ * Page furniture: the header and footer bands, and the page number.
3
+ *
4
+ * The two are drawn by different means on purpose. A header or footer is a piece
5
+ * of your page, so it is CAPTURED — same engine, same fidelity, whatever CSS you
6
+ * put in it. A page number is one short string that changes on every page, so it
7
+ * is drawn as real PDF text: crisp at any zoom, a few bytes, and selectable and
8
+ * searchable like the rest of the layer.
9
+ *
10
+ * Element bands are captured once before pagination. Their authoritative height
11
+ * comes from the final artifact's aspect ratio, so effects and render hooks cannot
12
+ * make the reserved strip disagree with what is drawn.
13
+ */
14
+ import { snapdom } from '@zumer/snapdom'
15
+
16
+ const positive = (value, fallback) => Number.isFinite(value) && value > 0 ? value : fallback
17
+ const nonNegative = (value, fallback) => Number.isFinite(value) && value >= 0 ? value : fallback
18
+
19
+ /**
20
+ * Cheap standalone estimate from an element's current box. The PDF exporter does
21
+ * not use this for pagination; captured artifact geometry is authoritative there.
22
+ *
23
+ * @param {Element|null} el
24
+ * @param {number} availW printable width in points
25
+ * @returns {number} height in points, 0 when there is no band
26
+ */
27
+ export function bandHeight(el, availW) {
28
+ if (!el || typeof el.getBoundingClientRect !== 'function' ||
29
+ !Number.isFinite(availW) || availW <= 0) return 0
30
+ const r = el.getBoundingClientRect()
31
+ if (!r.width || !r.height) return 0
32
+ return r.height * (availW / r.width)
33
+ }
34
+
35
+ /**
36
+ * Capture a band and hand back what `addStream` needs. Its height is derived from
37
+ * the FINAL artifact, not measured again from the live element: index.js captures
38
+ * bands before pageBox, and render hooks may change the artifact's aspect.
39
+ *
40
+ * The band rides the SAME scale and dpr as the page it sits on, so a header never
41
+ * looks softer or sharper than the content under it.
42
+ *
43
+ * @param {Element} el
44
+ * @param {{scale: number, dpr: number, quality: number,
45
+ * backgroundColor: string|null, availW: number, fitW?: number}} opts
46
+ */
47
+ export async function captureBand(el, options, encodeImage) {
48
+ const img = await captureElement(el, options, encodeImage)
49
+ const availW = positive(options.availW, 0)
50
+ const aspect = positive(img.aspect, 0)
51
+ return { ...img, heightPt: availW * aspect }
52
+ }
53
+
54
+ /**
55
+ * Capture any element as an image XObject, plus its own aspect ratio — which is
56
+ * all a cover, a closing page or an element watermark needs, none of which is
57
+ * bound to the printable width the way a band is.
58
+ *
59
+ * @returns {Promise<object>} what `addStream` needs, plus `aspect` (height/width).
60
+ */
61
+ export async function captureElement(el, {
62
+ scale, dpr, quality, backgroundColor, codec, captureOptions = {}, image = true, fitW = 0,
63
+ }, encodeImage) {
64
+ if (!el || el.nodeType !== 1) throw new TypeError('captureElement: expected an Element')
65
+ if (image && typeof encodeImage !== 'function') throw new TypeError('captureElement: encodeImage must be a function')
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)
71
+ const rasterDpr = positive(dpr, 1)
72
+ const source = {
73
+ baseURL: String(el.ownerDocument?.baseURI || document.baseURI),
74
+ documentURL: String(el.ownerDocument?.location?.href || el.ownerDocument?.baseURI || location.href),
75
+ documentLang: String(el.ownerDocument?.documentElement?.lang || ''),
76
+ }
77
+ const result = await snapdom(el, {
78
+ ...captureOptions,
79
+ outerShadows: captureOptions.outerShadows ?? false,
80
+ outerTransforms: captureOptions.outerTransforms ?? true,
81
+ scale: rasterScale, dpr: rasterDpr,
82
+ ...(backgroundColor ? { backgroundColor } : {}),
83
+ })
84
+ const meta = result.meta
85
+ if (!meta || !Number.isFinite(meta.vbW) || !Number.isFinite(meta.vbH)) {
86
+ throw new Error('captureElement: snapdom did not expose final render geometry')
87
+ }
88
+
89
+ const base = {
90
+ url: result.url,
91
+ meta,
92
+ vbW: meta.vbW,
93
+ vbH: meta.vbH,
94
+ offX: meta.contentX,
95
+ offY: meta.contentY,
96
+ aspect: meta.vbW > 0 ? meta.vbH / meta.vbW : 1,
97
+ source,
98
+ }
99
+ if (!image) return base
100
+
101
+ const canvas = await result.toCanvas({ backgroundColor: null })
102
+ const img = await encodeImage(canvas, { quality, background: backgroundColor, codec })
103
+
104
+ // Geometry is the immutable render contract returned by SnapDOM, so asymmetric
105
+ // bleed and transformed roots need no canvas-size heuristic here.
106
+ return {
107
+ ...img,
108
+ ...base,
109
+ }
110
+ }
111
+
112
+ const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i
113
+
114
+ /** `rg` wants three 0–1 components; anything unparseable stays the caller's grey. */
115
+ function rgb(colour) {
116
+ const m = HEX.exec(String(colour || '').trim())
117
+ if (!m) return null
118
+ let h = m[1]
119
+ if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2]
120
+ const n = parseInt(h, 16)
121
+ return [(n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255]
122
+ }
123
+
124
+ /**
125
+ * Normalise the `pageNumbers` option. `true` is the whole feature for most
126
+ * callers, so it has to mean something complete on its own.
127
+ */
128
+ export function numberSpec(option) {
129
+ if (!option) return null
130
+ const o = option === true ? {} : option
131
+ return {
132
+ format: typeof o.format === 'function' ? o.format : (page, pages) => `${page} / ${pages}`,
133
+ align: o.align === 'left' || o.align === 'right' ? o.align : 'center',
134
+ size: positive(o.size, 9),
135
+ font: o.font === 'serif' || o.font === 'mono' || o.font === 'sans'
136
+ ? o.font
137
+ // The document's own embedded face when the export has one; an explicit
138
+ // base-14 request keeps meaning exactly what it says.
139
+ : 'document',
140
+ colour: rgb(o.color ?? o.colour) || [0.36, 0.39, 0.47],
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Content-stream ops for one page's number, drawn in the bottom margin — below a
146
+ * footer band if there is one, so the two never fight over the same strip.
147
+ *
148
+ * @returns {{ops: string[], font: object}|null} null when the string is empty or
149
+ * unrepresentable, which is the caller's cue not to add a font resource.
150
+ */
151
+ export function numberOps({ spec, page, pages, pageW, marginX, marginY, availW, pdfText }) {
152
+ const str = String(spec.format(page, pages) ?? '')
153
+ if (!str.trim()) return null
154
+ const drawn = pdfText(str, spec.font, spec.size)
155
+ if (!drawn) return null
156
+ const { str: encoded, font, width } = drawn
157
+
158
+ const x = spec.align === 'left' ? marginX
159
+ : spec.align === 'right' ? marginX + availW - width
160
+ : marginX + (availW - width) / 2
161
+ // Sat in the middle of the bottom margin, on its own baseline.
162
+ const y = Math.max(2, marginY / 2 - spec.size * 0.35)
163
+
164
+ return {
165
+ font,
166
+ ops: [
167
+ 'q',
168
+ `${spec.colour.map(c => c.toFixed(3)).join(' ')} rg`,
169
+ // `0 Tr` is not redundant: the render mode is graphics state and survives ET,
170
+ // so the invisible layer drawn above would otherwise make this ghost too —
171
+ // present in the file, extractable, and painted by nobody.
172
+ `BT 0 Tr /${font.name} ${spec.size} Tf 1 0 0 1 ${x.toFixed(3)} ${y.toFixed(3)} Tm ${encoded} Tj ET`,
173
+ 'Q',
174
+ ],
175
+ }
176
+ }
177
+
178
+
179
+ /**
180
+ * Normalise a header or footer into one of two shapes.
181
+ *
182
+ * A string or an object of segments becomes REAL PDF TEXT — selectable, searchable
183
+ * and crisp at any zoom, which is what a running head almost always wants. An
184
+ * Element is captured instead, for the cases text cannot express: a logo, a rule in
185
+ * brand colours, a signature block.
186
+ *
187
+ * @returns {{kind:'text', …}|{kind:'element', el:Element}|null}
188
+ */
189
+ export function bandSpec(band) {
190
+ if (!band) return null
191
+ if (typeof band === 'object' && band.nodeType === 1) return { kind: 'element', el: band }
192
+ if (typeof band !== 'string' && typeof band !== 'function' && typeof band !== 'object') return null
193
+
194
+ const o = typeof band === 'string' || typeof band === 'function' ? { center: band } : band
195
+ const seg = (v) => (typeof v === 'function' ? v : v == null ? null : () => String(v))
196
+ const spec = {
197
+ kind: 'text',
198
+ left: seg(o.left), center: seg(o.center), right: seg(o.right),
199
+ size: positive(o.size, 9),
200
+ font: o.font === 'serif' || o.font === 'mono' || o.font === 'sans'
201
+ ? o.font
202
+ // The document's own embedded face when the export has one; an explicit
203
+ // base-14 request keeps meaning exactly what it says.
204
+ : 'document',
205
+ colour: rgb(o.color ?? o.colour) || [0.36, 0.39, 0.47],
206
+ rule: o.rule !== false,
207
+ gap: nonNegative(o.gap, 10),
208
+ }
209
+ return spec.left || spec.center || spec.right ? spec : null
210
+ }
211
+
212
+ /** How much of the page a text band takes, in points. */
213
+ export function textBandHeight(spec) {
214
+ return positive(spec && spec.size, 9) * 1.4 + nonNegative(spec && spec.gap, 10) + (spec && spec.rule ? 1 : 0)
215
+ }
216
+
217
+ /**
218
+ * Content-stream ops for a text band. The three segments are independent, so a
219
+ * left-aligned title and a right-aligned date never collide the way one centred
220
+ * string with padding would.
221
+ */
222
+ export function textBandOps({ spec, where, page, pages, pageH, marginX, marginY, availW, pdfText }) {
223
+ const height = textBandHeight(spec)
224
+ // The band occupies a strip against its margin; the rule always sits on the
225
+ // CONTENT side of the text, with the gap between them. Getting this the same way
226
+ // round for both put the footer's rule straight through its own words.
227
+ const top = where === 'header' ? pageH - marginY : marginY + height
228
+ const baseline = where === 'header'
229
+ ? top - spec.size
230
+ : top - spec.gap - spec.size * 0.8
231
+ const ruleY = where === 'header' ? top - height + spec.gap : top - 0.5
232
+
233
+ const ops = ['q', `${spec.colour.map(c => c.toFixed(3)).join(' ')} rg`]
234
+ const fonts = new Set()
235
+ for (const [key, align] of [['left', 'left'], ['center', 'center'], ['right', 'right']]) {
236
+ if (!spec[key]) continue
237
+ const str = String(spec[key](page, pages) ?? '')
238
+ if (!str.trim()) continue
239
+ const drawn = pdfText(str, spec.font, spec.size)
240
+ if (!drawn) continue
241
+ const { str: encoded, font, width } = drawn
242
+ const x = align === 'left' ? marginX
243
+ : align === 'right' ? marginX + availW - width
244
+ : marginX + (availW - width) / 2
245
+ // `0 Tr` explicitly: render mode is graphics state and survives ET, so the
246
+ // invisible layer drawn earlier would otherwise make this a ghost.
247
+ ops.push(`BT 0 Tr /${font.name} ${spec.size} Tf 1 0 0 1 ${x.toFixed(3)} ${baseline.toFixed(3)} Tm ${encoded} Tj ET`)
248
+ fonts.add(font)
249
+ }
250
+ if (!fonts.size) return null
251
+
252
+ if (spec.rule) {
253
+ ops.push(`${spec.colour.map(c => (c * 0.35 + 0.65).toFixed(3)).join(' ')} RG`,
254
+ '0.5 w', `${marginX} ${ruleY.toFixed(3)} m ${(marginX + availW).toFixed(3)} ${ruleY.toFixed(3)} l S`)
255
+ }
256
+ ops.push('Q')
257
+ return { ops, fonts: [...fonts] }
258
+ }
259
+
260
+ // ——— watermark ———
261
+ //
262
+ // The one piece of furniture that goes OVER the content rather than beside it,
263
+ // which is the whole point: a watermark under the page image would be invisible
264
+ // on any page with a background, and a watermark that can be covered is not one.
265
+
266
+ const clamp01 = (n, fallback) => (Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : fallback)
267
+
268
+ /**
269
+ * Normalise the `watermark` option. A bare string is the common case and has to
270
+ * mean something complete: grey, translucent, across the diagonal, sized to the
271
+ * page.
272
+ *
273
+ * @returns {{kind:'text'|'element', …}|null}
274
+ */
275
+ export function watermarkSpec(option) {
276
+ if (!option) return null
277
+ if (typeof option === 'object' && option.nodeType === 1) {
278
+ return { kind: 'element', el: option, opacity: 0.12, angle: 0, fit: 0.6 }
279
+ }
280
+ const o = typeof option === 'string' ? { text: option } : (option || {})
281
+ if (o.element && o.element.nodeType === 1) {
282
+ return {
283
+ kind: 'element', el: o.element,
284
+ opacity: clamp01(o.opacity, 0.12),
285
+ angle: Number.isFinite(o.angle) ? o.angle : 0,
286
+ fit: clamp01(o.fit, 0.6) || 0.6,
287
+ }
288
+ }
289
+ const text = o.text == null ? '' : String(o.text)
290
+ if (!text.trim()) return null
291
+ return {
292
+ kind: 'text', text,
293
+ // 0 means "as wide as the page will take", which is what a watermark almost
294
+ // always wants and what nobody wants to compute by hand for every page size.
295
+ size: Number.isFinite(o.size) && o.size > 0 ? o.size : 0,
296
+ angle: Number.isFinite(o.angle) ? o.angle : 45,
297
+ opacity: clamp01(o.opacity, 0.12),
298
+ colour: rgb(o.color ?? o.colour) || [0.45, 0.45, 0.5],
299
+ font: o.font === 'serif' || o.font === 'mono' || o.font === 'sans'
300
+ ? o.font
301
+ // The document's own embedded face when the export has one; an explicit
302
+ // base-14 request keeps meaning exactly what it says.
303
+ : 'document',
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Content-stream ops for the watermark, centred on the whole page — the MEDIA
309
+ * box, not the printable area: a watermark inside the margins reads as content.
310
+ *
311
+ * @param {object} args
312
+ * @param {string} args.gs name of the ExtGState carrying the opacity
313
+ * @param {string} [args.image] name of the XObject, for an element watermark
314
+ * @param {(text: string, key: string, size: number) => ({str, font, width}|null)} [args.pdfText]
315
+ * @returns {{ops: string[], font: object|null}|null}
316
+ */
317
+ export function watermarkOps({ spec, pageW, pageH, gs, image, imageAspect, pdfText }) {
318
+ const cx = pageW / 2
319
+ const cy = pageH / 2
320
+ const rad = (spec.angle * Math.PI) / 180
321
+ const cos = Math.cos(rad)
322
+ const sin = Math.sin(rad)
323
+
324
+ if (spec.kind === 'element') {
325
+ if (!image) return null
326
+ // Fit inside the page at `fit` of its smaller dimension, aspect preserved, so
327
+ // a wide stamp on a portrait page is not squashed to fit the width.
328
+ const w = Math.min(pageW, pageH / (imageAspect || 1)) * spec.fit
329
+ const h = w * (imageAspect || 1)
330
+ // A form XObject's unit square maps through `cm`, so the rotation has to be
331
+ // composed with the scale by hand rather than left to a text matrix.
332
+ return {
333
+ font: null,
334
+ ops: [
335
+ 'q', `/${gs} gs`,
336
+ `1 0 0 1 ${cx.toFixed(3)} ${cy.toFixed(3)} cm`,
337
+ `${cos.toFixed(5)} ${sin.toFixed(5)} ${(-sin).toFixed(5)} ${cos.toFixed(5)} 0 0 cm`,
338
+ `${w.toFixed(3)} 0 0 ${h.toFixed(3)} ${(-w / 2).toFixed(3)} ${(-h / 2).toFixed(3)} cm`,
339
+ `/${image} Do`, 'Q',
340
+ ],
341
+ }
342
+ }
343
+
344
+ // Auto size: the largest the string can be with its ROTATED extent still inside
345
+ // the page, which is what makes one option work on A4, on a receipt roll and on
346
+ // a landscape slide alike.
347
+ //
348
+ // Not the page's diagonal LENGTH — that is the trap. A 486 × 1938 page has a
349
+ // long diagonal and almost no width, and a string sized to that diagonal but
350
+ // laid at 45° runs off both sides: a rotated string of advance W spans W·|cos θ|
351
+ // across and W·|sin θ| down, so each axis caps W on its own and the smaller cap
352
+ // is the one that decides.
353
+ const unit = pdfText(spec.text, spec.font, 1)
354
+ if (!unit) return null
355
+ let size = spec.size
356
+ if (!size) {
357
+ const acrossX = Math.abs(cos) > 1e-6 ? (pageW * 0.9) / Math.abs(cos) : Infinity
358
+ const acrossY = Math.abs(sin) > 1e-6 ? (pageH * 0.9) / Math.abs(sin) : Infinity
359
+ const room = Math.min(acrossX, acrossY)
360
+ size = unit.width > 0 && Number.isFinite(room) ? room / unit.width : 24
361
+ }
362
+ const drawn = pdfText(spec.text, spec.font, size)
363
+ if (!drawn) return null
364
+ const width = drawn.width
365
+
366
+ // Centre the STRING on the page centre: back off half an advance along the
367
+ // rotated baseline, and about a third of a size along the rotated up-vector,
368
+ // which puts the x-height band on the centre rather than the baseline.
369
+ const x = cx - (width / 2) * cos + 0.35 * size * sin
370
+ const y = cy - (width / 2) * sin - 0.35 * size * cos
371
+
372
+ return {
373
+ font: drawn.font,
374
+ ops: [
375
+ 'q', `/${gs} gs`,
376
+ `${spec.colour.map(c => c.toFixed(3)).join(' ')} rg`,
377
+ // `0 Tr` explicitly — render mode survives ET, and the invisible text layer
378
+ // drawn before this would otherwise make the watermark a ghost too.
379
+ `BT 0 Tr /${drawn.font.name} ${size.toFixed(3)} Tf ` +
380
+ `${cos.toFixed(5)} ${sin.toFixed(5)} ${(-sin).toFixed(5)} ${cos.toFixed(5)} ` +
381
+ `${x.toFixed(3)} ${y.toFixed(3)} Tm ${drawn.str} Tj ET`,
382
+ 'Q',
383
+ ],
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Content-stream ops that place a captured band across the printable width.
389
+ *
390
+ * @param {'header'|'footer'} where
391
+ */
392
+ export function bandOps({ where, name, heightPt, pageH, marginX, marginY, availW }) {
393
+ const bottom = where === 'header'
394
+ ? pageH - marginY - heightPt
395
+ : marginY
396
+ return [
397
+ 'q',
398
+ `${availW.toFixed(3)} 0 0 ${heightPt.toFixed(3)} ${marginX.toFixed(3)} ${bottom.toFixed(3)} cm`,
399
+ `/${name} Do`,
400
+ 'Q',
401
+ ]
402
+ }