diff --git a/docs/api.md b/docs/api.md index 5e93fc9..a42fb0c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -626,6 +626,29 @@ const shaper: Shaper = { - **Subsets**: `subsetFont` keeps the glyphs given and what they are made of, renumbered from 0 (glyph 0 stays), with a character map for the `chars` passed as a third argument. TrueType outlines are copied; PostScript ones (CFF, also CID-keyed) keep their charstrings and subroutines, and come as an OTF and as the bare CFF table (`cff`) a PDF embeds. `font.embeddable` is false for a font whose license forbids embedding. - **Limits**: `FONT_LIMITS` (a file of 64 MB, 128 MB unpacked, 2,000,000 layout records). A file that is not a font, is damaged or is past a limit throws a `FontError` that says which. Not read: fonts embedded in a document, CFF2 outlines, the other instances of a variable font, bitmap and color glyphs. WOFF2 needs a runtime whose `DecompressionStream` unpacks Brotli: Node 26, Bun 1.4 and Firefox 157 do, Chromium 156 does not. There a WOFF2 file is refused with a `FontError` that says so (`font:error`, `onError`) and its text goes to the next font of the list, so declare TTF, OTF or WOFF files for text that has to be measured in Chrome. +### PDF output + +A presentation is written as a PDF file by the library itself: no browser, no print dialog, no dependency, in the worker or on a server (`new Engine(emit)`). Its text is set in the font files of `fonts.set` and embedded as subsets, with the text of their glyphs, so it can be selected, copied and searched. Spreadsheets (#47) and documents (#48) follow. + +```ts +await doc.call('fonts.set', fonts) // the files text is set in (see "Reading font files") +const pdf = await doc.call('pdf') // a Blob, application/pdf: every slide but the hidden ones +await doc.call('pdf', { slides: [0, 2], title: 'Q3' }) // these slides; hidden ones only with `hidden: true`, even when named +doc.on('warning', ({ text }) => {}) // what could not be drawn as it is, once each +const svg = await doc.call('pptx.svg', 0) // a slide as an SVG picture, drawn as the PDF draws it + +// without a document: pages of drawing commands, and the backends that paint them +import { slidePage, writePdf, pageToSvg, svgItems, FontBook } from '@p10node/office-engine/core' +const page = await slidePage(slideModel, { fonts: new FontBook(fonts), part: async (name) => bytesOf(name) }) +const bytes = await writePdf([page], { title: 'Deck', onWarning: console.warn }) +``` + +- **Pages**: a slide is a page at the slide's size; shapes, preset and custom outlines, solid and gradient fills, picture fills, outlines with their dashes and arrowheads, flips and rotation, pictures with their crop and shape, tables (rows grow to their text), charts (the viewer's chart, as shapes and text) and text boxes are placed as the viewer places them. One page of the outline per slide title. +- **Text**: lines broken, aligned and spaced as the viewer's CSS does (`pre-wrap`, a unitless `line-height`), bullets in their hanging indent, underline, strikethrough, highlight, superscript and subscript, links, vertical text. Text no declared file serves is set in Helvetica (the PDF's own font, Windows-1252 characters only) and a warning names the font, so a server should declare its font files: Carlito, Caladea and Liberation stand in for Calibri, Cambria, Arial and Times New Roman. +- **Fonts' licenses**: a font that may not be embedded, or only as bitmaps, has its text set in Helvetica with a warning; one that may not be subset is embedded whole (but a CJK font keyed by CID, whose glyphs are not its characters, is set in Helvetica too). A damaged font file falls back the same way and the rest of the file is written. +- **Pictures**: JPEG copied as it is, PNG and GIF with their transparency, SVG as shapes and text. EMF, WMF, TIFF, BMP and WebP are left out with a warning. A picture is unpacked to at most 64 million pixels, an SVG picture draws at most 100,000 elements and 1,000,000 path segments (counted as drawn, references included); one past them, or one that cannot be read, is left out with a warning. +- **Not yet**: shadows and other effects, pattern fills (drawn in their foreground color), tiled pictures (stretched), text columns, autofit that shrinks text (the file's own scale is used) or grows the shape to its text, notes pages, SmartArt and OLE objects. + ## Standalone packages Diagrams and Markdown without the viewer (no DOM needed, no dependency): [`@p10node/diagram`](../packages/diagram), [`@p10node/mermaid`](../packages/mermaid), [`@p10node/plantuml`](../packages/plantuml), [`@p10node/graphviz`](../packages/graphviz), [`@p10node/markdown`](../packages/markdown). diff --git a/docs/features.md b/docs/features.md index 562cf9f..ace13ed 100644 --- a/docs/features.md +++ b/docs/features.md @@ -12,6 +12,7 @@ - **DOCX pages** are cut the way Word cuts them, with the lines the browser lays out: a paragraph that does not fit the rest of a page goes on at the top of the next one (split between two lines, the same lines as when whole; a justified paragraph's last line on the first page stays justified), a table between two rows, its header rows (`w:tblHeader`) repeated at the top of each following page; a merged cell cut by the page end goes on as an empty cell. Keep rules choose the cut: widow / orphan control (on unless the paragraph, its style or the document defaults turn it off), keep lines together, keep with next (a chain of headings goes with the first lines after it; a chain taller than a page is cut like any text). Only one line or one row taller than a page makes its page taller. Text columns are filled the same way, column after column - **Fonts**: the host can supply font files (`fonts`: URLs or bytes, loaded with the `FontFace` API when a document uses the family); a declared fallback serves the fonts named before it (Carlito for Calibri, Caladea for Cambria, Liberation for Arial, Times New Roman and Courier New). DOCX pages are measured once those fonts are loaded (at most 3 s, not past a failure; a font that comes later has the pages measured again); a late web font of the page also has the pages measured again; XLSX fits its numbers again. No font file ships with the library, and fonts embedded in a document are not read. See [API](api.md#fonts) - **Font files read without a browser** (core API): glyph widths, kerning, ligatures and line metrics from TTF, OTF, TTC, WOFF and WOFF2 files, the file a text is set in chosen as CSS chooses, each result marked exact or not (and why); subsets to embed, with the text of their glyphs for a PDF; a host's shaping engine for the scripts that need one. In the worker (`fonts.set`, `fonts.measure`) and on a server. See [API](api.md#reading-font-files) +- **PDF output without a browser** (core API): a presentation written as a PDF file by the library itself, in the worker or on a server: slides laid out as pages of drawing commands, text set in the host's font files and embedded as subsets that can be copied and searched, JPEG / PNG / GIF / SVG pictures, charts, links and an outline. Spreadsheets and documents follow. See [API](api.md#pdf-output) ## Format support diff --git a/src/core/draw/glyphs.ts b/src/core/draw/glyphs.ts new file mode 100644 index 0000000..4e4b3f9 --- /dev/null +++ b/src/core/draw/glyphs.ts @@ -0,0 +1,20 @@ +/** What each glyph of a text command stands for: copy, search and the SVG backend's characters. */ +import type { DrawItem } from './types' + +type Text = Extract + +/** + * For each glyph, the text it stands for: its cluster's characters (to the next cluster's start) for the first glyph + * of a cluster, nothing for the others. (Worked out each time it is asked for: a command can be changed between two + * exports.) + */ +export function glyphTexts(it: Text): string[] { + const starts = [...new Set(it.clusters)].sort((a, b) => a - b) + const end = new Map(starts.map((c, k) => [c, starts[k + 1] ?? it.text.length])) + const seen = new Set() + return it.clusters.map((c) => { + if (seen.has(c)) return '' + seen.add(c) + return it.text.slice(c, end.get(c)) + }) +} diff --git a/src/core/draw/image.ts b/src/core/draw/image.ts new file mode 100644 index 0000000..c4fbcf5 --- /dev/null +++ b/src/core/draw/image.ts @@ -0,0 +1,358 @@ +/** + * Pictures read for a backend that draws pixels it is given (a PDF): a JPEG's size and color space, PNG and GIF + * unpacked to 8-bit color and alpha. No DOM, no dependency: inflate is the runtime's `DecompressionStream`. + */ +import { sniffImage } from '../legacy/odf/odp-media' + +export { sniffImage } + +/** pixels past which a picture is not unpacked: 1 GB of RGBA would be too much for one page */ +export const MAX_PIXELS = 64 * 1024 * 1024 + +export class ImageError extends Error { + constructor(message: string) { + super(message) + this.name = 'ImageError' + } +} + +const be16 = (b: Uint8Array, i: number) => (b[i] << 8) | b[i + 1] +const be32 = (b: Uint8Array, i: number) => ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0 +const le16 = (b: Uint8Array, i: number) => b[i] | (b[i + 1] << 8) + +export interface JpegInfo { + w: number + h: number + /** 1 gray, 3 YCbCr / RGB, 4 CMYK */ + components: number + /** Adobe's CMYK is stored inverted */ + adobe: boolean +} + +/** a JPEG's size and color components, from its frame header; null when it has none */ +export function jpegInfo(b: Uint8Array): JpegInfo | null { + let adobe = false + for (let i = 2, steps = 0; i + 9 < b.length && steps < 10000; steps++) { + if (b[i] !== 0xff) { + i++ + continue + } + const m = b[i + 1] + if (m === 0xff) { + i++ + continue + } + if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { + i += 2 + continue + } + const len = be16(b, i + 2) + if (m === 0xee && String.fromCharCode(b[i + 4], b[i + 5], b[i + 6], b[i + 7], b[i + 8]) === 'Adobe') adobe = true + if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) { + const h = be16(b, i + 5) + const w = be16(b, i + 7) + const components = b[i + 9] + if (!w || !h || ![1, 3, 4].includes(components)) return null + return { w, h, components, adobe } + } + i += 2 + len + } + return null +} + +/** pixels as a PDF takes them: 8-bit gray or RGB, and an 8-bit alpha when some are not opaque */ +export interface Pixels { + w: number + h: number + /** 1 gray, 3 RGB */ + channels: 1 | 3 + color: Uint8Array + alpha?: Uint8Array +} + +/** what a picture's data may unpack to past what its pixels take */ +const SLACK = 1024 * 1024 + +/** + * Inflated: the first `limit` bytes are kept. The stream is read to its end, so a damaged one (its checksum missing + * or wrong) is refused; so is one that unpacks to more than `SLACK` bytes past what is needed, which are not unpacked. + */ +async function inflate(data: Uint8Array, limit: number): Promise { + const reader = new Blob([data as Uint8Array]).stream().pipeThrough(new DecompressionStream('deflate')).getReader() + const out = new Uint8Array(limit) + let size = 0 + let past = 0 + try { + while (past <= SLACK) { + const { done, value } = await reader.read() + if (done) break + const keep = Math.min(value.length, limit - size) + out.set(value.subarray(0, keep), size) + size += keep + past += value.length - keep + } + } catch { + throw new ImageError('A PNG whose pixels are damaged') + } finally { + void reader.cancel().catch(() => {}) + } + if (past > SLACK) throw new ImageError('A PNG whose data is much longer than its pixels') + return out.subarray(0, size) +} + +/** a PNG unpacked: every bit depth and color type, palettes and their transparency, interlaced or not */ +export async function decodePng(b: Uint8Array): Promise { + if (b.length < 33 || be32(b, 12) !== 0x49484452) throw new ImageError('Not a PNG file') + const w = be32(b, 16) + const h = be32(b, 20) + const depth = b[24] + const type = b[25] + const interlaced = b[28] === 1 + if (!w || !h || w * h > MAX_PIXELS) throw new ImageError(`A PNG of ${w} × ${h} pixels is not drawn`) + const samples = ({ 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 } as Record)[type] + if (!samples || ![1, 2, 4, 8, 16].includes(depth)) throw new ImageError('A PNG of a kind that is not read') + let palette: Uint8Array | undefined + let trns: Uint8Array | undefined + const idat: Uint8Array[] = [] + for (let i = 8; i + 12 <= b.length; ) { + const len = be32(b, i) + const t = be32(b, i + 4) + if (i + 12 + len > b.length) break + const body = b.subarray(i + 8, i + 8 + len) + if (t === 0x504c5445) palette = body + else if (t === 0x74524e53) trns = body + else if (t === 0x49444154) idat.push(body) + else if (t === 0x49454e44) break + i += 12 + len + } + let size = 0 + for (const c of idat) size += c.length + const all = new Uint8Array(size) + size = 0 + for (const c of idat) all.set(c, size), (size += c.length) + const bpp = Math.max(1, (samples * depth) >> 3) + // the passes of Adam7: x0, y0, dx, dy + const passes = interlaced ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] : [[0, 0, 1, 1]] + // the bytes the pixels take, each row with its filter byte: no more is unpacked + let need = 0 + for (const [x0, y0, dx, dy] of passes) { + const pw = Math.ceil((w - x0) / dx) + const ph = Math.ceil((h - y0) / dy) + if (pw > 0 && ph > 0) need += ph * (1 + Math.ceil((pw * samples * depth) / 8)) + } + const raw = await inflate(all, need) + const gray = type === 0 || type === 4 + const channels = gray ? 1 : 3 + const color = new Uint8Array(w * h * channels) + const alpha = new Uint8Array(w * h).fill(255) + let hasAlpha = false + const maxv = (1 << depth) - 1 + let at = 0 + for (const [x0, y0, dx, dy] of passes) { + const pw = Math.ceil((w - x0) / dx) + const ph = Math.ceil((h - y0) / dy) + if (pw <= 0 || ph <= 0) continue + const stride = Math.ceil((pw * samples * depth) / 8) + let prev = new Uint8Array(stride) + for (let row = 0; row < ph; row++) { + if (at + 1 + stride > raw.length) throw new ImageError('A PNG whose pixels end early') + const filter = raw[at] + const line = raw.slice(at + 1, at + 1 + stride) + at += 1 + stride + unfilter(filter, line, prev, bpp) + prev = line + const y = y0 + row * dy + for (let col = 0; col < pw; col++) { + const x = x0 + col * dx + const p = y * w + x + /** a sample as stored (16 bits for a 16-bit picture: transparency keys are compared on all of them) */ + const sample = (k: number): number => { + const n = col * samples + k + if (depth === 8) return line[n] + if (depth === 16) return (line[n * 2] << 8) | line[n * 2 + 1] + const bit = n * depth + return (line[bit >> 3] >> (8 - depth - (bit & 7))) & maxv + } + /** a sample as 8 bits */ + const full = (v: number) => (depth === 16 ? v >> 8 : depth === 8 ? v : Math.round((v * 255) / maxv)) + if (type === 3) { + const k = sample(0) + color[p * 3] = palette?.[k * 3] ?? 0 + color[p * 3 + 1] = palette?.[k * 3 + 1] ?? 0 + color[p * 3 + 2] = palette?.[k * 3 + 2] ?? 0 + if (trns && k < trns.length && trns[k] !== 255) (alpha[p] = trns[k]), (hasAlpha = true) + } else if (gray) { + const v = sample(0) + color[p] = full(v) + if (type === 4) { + alpha[p] = full(sample(1)) + if (alpha[p] !== 255) hasAlpha = true + } else if (trns && trns.length >= 2 && v === be16(trns, 0)) (alpha[p] = 0), (hasAlpha = true) + } else { + const r = sample(0) + const g = sample(1) + const bl = sample(2) + color[p * 3] = full(r) + color[p * 3 + 1] = full(g) + color[p * 3 + 2] = full(bl) + if (type === 6) { + alpha[p] = full(sample(3)) + if (alpha[p] !== 255) hasAlpha = true + } else if (trns && trns.length >= 6 && r === be16(trns, 0) && g === be16(trns, 2) && bl === be16(trns, 4)) (alpha[p] = 0), (hasAlpha = true) + } + } + } + } + return { w, h, channels, color, ...(hasAlpha ? { alpha } : {}) } +} + +function unfilter(filter: number, line: Uint8Array, prev: Uint8Array, bpp: number) { + const n = line.length + switch (filter) { + case 1: + for (let i = bpp; i < n; i++) line[i] = (line[i] + line[i - bpp]) & 255 + break + case 2: + for (let i = 0; i < n; i++) line[i] = (line[i] + prev[i]) & 255 + break + case 3: + for (let i = 0; i < n; i++) line[i] = (line[i] + (((i >= bpp ? line[i - bpp] : 0) + prev[i]) >> 1)) & 255 + break + case 4: + for (let i = 0; i < n; i++) { + const a = i >= bpp ? line[i - bpp] : 0 + const b = prev[i] + const c = i >= bpp ? prev[i - bpp] : 0 + const p = a + b - c + const pa = Math.abs(p - a) + const pb = Math.abs(p - b) + const pc = Math.abs(p - c) + line[i] = (line[i] + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)) & 255 + } + break + } +} + +/** a GIF's first frame unpacked, on its logical screen (transparent around it) */ +export function decodeGif(b: Uint8Array): Pixels { + if (b.length < 13 || String.fromCharCode(b[0], b[1], b[2]) !== 'GIF') throw new ImageError('Not a GIF file') + const w = le16(b, 6) + const h = le16(b, 8) + if (!w || !h || w * h > MAX_PIXELS) throw new ImageError(`A GIF of ${w} × ${h} pixels is not drawn`) + let i = 13 + let global: Uint8Array | undefined + if (b[10] & 0x80) { + const n = 3 << ((b[10] & 7) + 1) + global = b.subarray(i, i + n) + i += n + } + let transparent = -1 + const color = new Uint8Array(w * h * 3) + const alpha = new Uint8Array(w * h) + while (i < b.length) { + const block = b[i++] + if (block === 0x21) { + const label = b[i++] + if (label === 0xf9 && b[i] >= 4 && b[i + 1] & 1) transparent = b[i + 4] + while (i < b.length && b[i]) i += b[i] + 1 + i++ + } else if (block === 0x2c) { + const fx = le16(b, i) + const fy = le16(b, i + 2) + const fw = le16(b, i + 4) + const fh = le16(b, i + 6) + // (the frame's pixels are unpacked before they are cut to the screen: as many as a picture may have) + if (fw * fh > MAX_PIXELS) throw new ImageError(`A GIF frame of ${fw} × ${fh} pixels is not drawn`) + const flags = b[i + 8] + i += 9 + let table = global + if (flags & 0x80) { + const n = 3 << ((flags & 7) + 1) + table = b.subarray(i, i + n) + i += n + } + const minCode = b[i++] + const data: number[] = [] + while (i < b.length && b[i]) { + for (let k = 1; k <= b[i] && i + k < b.length; k++) data.push(b[i + k]) + i += b[i] + 1 + } + const idx = lzw(data, minCode, fw * fh) + const rows = (flags & 0x40 ? interlacedRows(fh) : null) ?? Array.from({ length: fh }, (_, r) => r) + for (let k = 0; k < idx.length; k++) { + const row = rows[Math.floor(k / fw)] + const x = fx + (k % fw) + const y = fy + row + if (x >= w || y >= h) continue + const c = idx[k] + if (c === transparent) continue + const p = y * w + x + color[p * 3] = table?.[c * 3] ?? 0 + color[p * 3 + 1] = table?.[c * 3 + 1] ?? 0 + color[p * 3 + 2] = table?.[c * 3 + 2] ?? 0 + alpha[p] = 255 + } + break + } else break + } + return { w, h, channels: 3, color, ...(alpha.every((a) => a === 255) ? {} : { alpha }) } +} + +function interlacedRows(h: number): number[] { + const out: number[] = [] + for (const [start, step] of [[0, 8], [4, 8], [2, 4], [1, 2]]) for (let r = start; r < h; r += step) out.push(r) + return out +} + +function lzw(data: number[], minCode: number, count: number): Uint8Array { + const out = new Uint8Array(count) + if (minCode < 2 || minCode > 11) return out + const clear = 1 << minCode + const end = clear + 1 + let size = minCode + 1 + const prefix = new Int32Array(4096) + const suffix = new Uint8Array(4096) + const first = new Uint8Array(4096) + let next = end + 1 + let old = -1 + let n = 0 + let bits = 0 + let acc = 0 + const stack = new Uint8Array(4097) + for (let k = 0; k < clear; k++) (prefix[k] = -1), (suffix[k] = k), (first[k] = k) + for (let p = 0; p < data.length && n < count; ) { + while (bits < size && p < data.length) (acc |= data[p++] << bits), (bits += 8) + if (bits < size) break + const code = acc & ((1 << size) - 1) + acc >>>= size + bits -= size + if (code === clear) { + size = minCode + 1 + next = end + 1 + old = -1 + continue + } + if (code === end) break + let c = code + let top = 0 + if (code >= next) { + if (old < 0) break + stack[top++] = first[old] + c = old + } + while (c >= 0 && top < 4097) { + stack[top++] = suffix[c] + c = c < clear ? -1 : prefix[c] + } + while (top && n < count) out[n++] = stack[--top] + if (old >= 0 && next < 4096) { + prefix[next] = old + suffix[next] = code === next ? first[old] : first[code] + first[next] = first[old] + next++ + if (next === 1 << size && size < 12) size++ + } + old = code + } + return out +} diff --git a/src/core/draw/path.ts b/src/core/draw/path.ts new file mode 100644 index 0000000..4feb3d5 --- /dev/null +++ b/src/core/draw/path.ts @@ -0,0 +1,332 @@ +/** SVG path data, transforms and CSS colors as drawing commands take them. */ +import type { Matrix, Rgba, Seg } from './types' + +export const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0] + +/** `m` then `n`: a point is transformed by `m` first */ +export function multiply(m: Matrix, n: Matrix): Matrix { + return [m[0] * n[0] + m[1] * n[2], m[0] * n[1] + m[1] * n[3], m[2] * n[0] + m[3] * n[2], m[2] * n[1] + m[3] * n[3], m[4] * n[0] + m[5] * n[2] + n[4], m[4] * n[1] + m[5] * n[3] + n[5]] +} + +export const translate = (x: number, y: number): Matrix => [1, 0, 0, 1, x, y] +export const scale = (sx: number, sy = sx): Matrix => [sx, 0, 0, sy, 0, 0] +/** degrees clockwise (y down), about (cx, cy) */ +export function rotate(deg: number, cx = 0, cy = 0): Matrix { + const r = (deg * Math.PI) / 180 + const c = Math.cos(r) + const s = Math.sin(r) + return [c, s, -s, c, cx - c * cx + s * cy, cy - s * cx - c * cy] +} + +/** the matrix that undoes `m`; null for one that flattens (a scale of 0) */ +export function invert(m: Matrix): Matrix | null { + const det = m[0] * m[3] - m[1] * m[2] + if (!det || !Number.isFinite(det)) return null + return [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det] +} + +export const apply = (m: Matrix, x: number, y: number): [number, number] => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]] + +export function transformPath(d: Seg[], m: Matrix): Seg[] { + return d.map((s) => { + if (s.k === 'Z') return s + if (s.k === 'C') { + const [x1, y1] = apply(m, s.x1, s.y1) + const [x2, y2] = apply(m, s.x2, s.y2) + const [x, y] = apply(m, s.x, s.y) + return { k: 'C', x1, y1, x2, y2, x, y } + } + const [x, y] = apply(m, s.x, s.y) + return { k: s.k, x, y } + }) +} + +export const rectPath = (x: number, y: number, w: number, h: number): Seg[] => [ + { k: 'M', x, y }, + { k: 'L', x: x + w, y }, + { k: 'L', x: x + w, y: y + h }, + { k: 'L', x, y: y + h }, + { k: 'Z' }, +] + +/** κ: control points of a quarter circle as a cubic curve */ +const K = 0.5522847498 + +export function ellipsePath(cx: number, cy: number, rx: number, ry: number): Seg[] { + const ox = rx * K + const oy = ry * K + return [ + { k: 'M', x: cx + rx, y: cy }, + { k: 'C', x1: cx + rx, y1: cy + oy, x2: cx + ox, y2: cy + ry, x: cx, y: cy + ry }, + { k: 'C', x1: cx - ox, y1: cy + ry, x2: cx - rx, y2: cy + oy, x: cx - rx, y: cy }, + { k: 'C', x1: cx - rx, y1: cy - oy, x2: cx - ox, y2: cy - ry, x: cx, y: cy - ry }, + { k: 'C', x1: cx + ox, y1: cy - ry, x2: cx + rx, y2: cy - oy, x: cx + rx, y: cy }, + { k: 'Z' }, + ] +} + +export function roundRectPath(x: number, y: number, w: number, h: number, rx: number, ry = rx): Seg[] { + rx = Math.min(Math.abs(rx), w / 2) + ry = Math.min(Math.abs(ry), h / 2) + if (!rx || !ry) return rectPath(x, y, w, h) + const ox = rx * (1 - K) + const oy = ry * (1 - K) + return [ + { k: 'M', x: x + rx, y }, + { k: 'L', x: x + w - rx, y }, + { k: 'C', x1: x + w - ox, y1: y, x2: x + w, y2: y + oy, x: x + w, y: y + ry }, + { k: 'L', x: x + w, y: y + h - ry }, + { k: 'C', x1: x + w, y1: y + h - oy, x2: x + w - ox, y2: y + h, x: x + w - rx, y: y + h }, + { k: 'L', x: x + rx, y: y + h }, + { k: 'C', x1: x + ox, y1: y + h, x2: x, y2: y + h - oy, x, y: y + h - ry }, + { k: 'L', x, y: y + ry }, + { k: 'C', x1: x, y1: y + oy, x2: x + ox, y2: y, x: x + rx, y }, + { k: 'Z' }, + ] +} + +/** the box a path's points (control points included) lie in: [x0, y0, x1, y1], null for none */ +export function bounds(d: Seg[]): [number, number, number, number] | null { + let x0 = Infinity + let y0 = Infinity + let x1 = -Infinity + let y1 = -Infinity + const at = (x: number, y: number) => { + if (x < x0) x0 = x + if (x > x1) x1 = x + if (y < y0) y0 = y + if (y > y1) y1 = y + } + for (const s of d) { + if (s.k === 'Z') continue + if (s.k === 'C') at(s.x1, s.y1), at(s.x2, s.y2) + at(s.x, s.y) + } + return x0 <= x1 ? [x0, y0, x1, y1] : null +} + +/** the largest number of path segments read from one path: a crafted file cannot make one take the memory */ +export const MAX_SEGMENTS = 200_000 + +const NUM = /[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/y +const SPACE = /[\s,]*/y + +/** + * SVG path data (`M L H V C S Q T A Z`, relative and absolute) as moves, lines and cubic curves. What follows an error + * is dropped, as SVG renders a path up to its first error. + */ +export function parsePath(d: string): Seg[] { + const out: Seg[] = [] + let i = 0 + const skip = () => { + SPACE.lastIndex = i + SPACE.exec(d) + i = SPACE.lastIndex + } + const num = (): number | null => { + skip() + NUM.lastIndex = i + const m = NUM.exec(d) + if (!m) return null + i = NUM.lastIndex + return Number(m[0]) + } + const flag = (): number | null => { + skip() + const c = d[i] + if (c !== '0' && c !== '1') return null + i++ + return c === '1' ? 1 : 0 + } + let x = 0 + let y = 0 + let sx = 0 + let sy = 0 + // the last control point, for S and T + let cx = 0 + let cy = 0 + let prev = '' + let cmd = '' + while (out.length < MAX_SEGMENTS) { + skip() + if (i >= d.length) break + const c = d[i] + if (/[MLHVCSQTAZmlhvcsqtaz]/.test(c)) { + cmd = c + i++ + } else if (!cmd || cmd === 'Z' || cmd === 'z') break + const rel = cmd === cmd.toLowerCase() + const ox = rel ? x : 0 + const oy = rel ? y : 0 + const C = cmd.toUpperCase() + if (C === 'Z') { + out.push({ k: 'Z' }) + x = sx + y = sy + prev = 'Z' + continue + } + if (C === 'M' || C === 'L' || C === 'T') { + const a = num() + const b = a === null ? null : num() + if (b === null) break + if (C === 'T') { + const [qx, qy] = prev === 'Q' || prev === 'T' ? [2 * x - cx, 2 * y - cy] : [x, y] + quad(out, x, y, qx, qy, ox + a!, oy + b) + cx = qx + cy = qy + } else out.push({ k: C === 'M' ? 'M' : 'L', x: ox + a!, y: oy + b }) + x = ox + a! + y = oy + b + if (C === 'M') { + sx = x + sy = y + // numbers after a move are lines + cmd = rel ? 'l' : 'L' + } + prev = C + continue + } + if (C === 'H' || C === 'V') { + const a = num() + if (a === null) break + if (C === 'H') x = (rel ? x : 0) + a + else y = (rel ? y : 0) + a + out.push({ k: 'L', x, y }) + prev = C + continue + } + if (C === 'C' || C === 'S') { + const n: number[] = [] + for (let k = C === 'C' ? 6 : 4; k > 0; k--) { + const v = num() + if (v === null) break + n.push(v) + } + if (n.length < (C === 'C' ? 6 : 4)) break + const [x1, y1] = C === 'C' ? [ox + n[0], oy + n[1]] : prev === 'C' || prev === 'S' ? [2 * x - cx, 2 * y - cy] : [x, y] + const r = C === 'C' ? 2 : 0 + const x2 = ox + n[r] + const y2 = oy + n[r + 1] + x = ox + n[r + 2] + y = oy + n[r + 3] + out.push({ k: 'C', x1, y1, x2, y2, x, y }) + cx = x2 + cy = y2 + prev = C + continue + } + if (C === 'Q') { + const n: number[] = [] + for (let k = 4; k > 0; k--) { + const v = num() + if (v === null) break + n.push(v) + } + if (n.length < 4) break + quad(out, x, y, ox + n[0], oy + n[1], ox + n[2], oy + n[3]) + cx = ox + n[0] + cy = oy + n[1] + x = ox + n[2] + y = oy + n[3] + prev = 'Q' + continue + } + // A rx ry rotation large-arc sweep x y + const rx = num() + const ry = rx === null ? null : num() + const rot = ry === null ? null : num() + const large = rot === null ? null : flag() + const sweep = large === null ? null : flag() + const ex = sweep === null ? null : num() + const ey = ex === null ? null : num() + if (ey === null) break + arc(out, x, y, rx!, ry!, rot!, !!large, !!sweep, ox + ex!, oy + ey) + x = ox + ex! + y = oy + ey + prev = 'A' + } + return out +} + +function quad(out: Seg[], x0: number, y0: number, qx: number, qy: number, x: number, y: number) { + out.push({ k: 'C', x1: x0 + (2 / 3) * (qx - x0), y1: y0 + (2 / 3) * (qy - y0), x2: x + (2 / 3) * (qx - x), y2: y + (2 / 3) * (qy - y), x, y }) +} + +/** an SVG elliptical arc as cubic curves (SVG 1.1, F.6.5) */ +export function arc(out: Seg[], x0: number, y0: number, rx: number, ry: number, deg: number, large: boolean, sweep: boolean, x: number, y: number) { + rx = Math.abs(rx) + ry = Math.abs(ry) + if ((x0 === x && y0 === y) || !rx || !ry) { + if (x0 !== x || y0 !== y) out.push({ k: 'L', x, y }) + return + } + const phi = (deg * Math.PI) / 180 + const cos = Math.cos(phi) + const sin = Math.sin(phi) + const dx = (x0 - x) / 2 + const dy = (y0 - y) / 2 + const x1 = cos * dx + sin * dy + const y1 = -sin * dx + cos * dy + const lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry) + if (lambda > 1) { + rx *= Math.sqrt(lambda) + ry *= Math.sqrt(lambda) + } + const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1 + const den = rx * rx * y1 * y1 + ry * ry * x1 * x1 + const co = (large === sweep ? -1 : 1) * Math.sqrt(Math.max(0, num / den)) + const cxp = (co * rx * y1) / ry + const cyp = (-co * ry * x1) / rx + const cx = cos * cxp - sin * cyp + (x0 + x) / 2 + const cy = sin * cxp + cos * cyp + (y0 + y) / 2 + const angle = (ux: number, uy: number, vx: number, vy: number) => { + const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + return a + } + const t1 = angle(1, 0, (x1 - cxp) / rx, (y1 - cyp) / ry) + let dt = angle((x1 - cxp) / rx, (y1 - cyp) / ry, (-x1 - cxp) / rx, (-y1 - cyp) / ry) + if (!sweep && dt > 0) dt -= 2 * Math.PI + else if (sweep && dt < 0) dt += 2 * Math.PI + const n = Math.max(1, Math.ceil(Math.abs(dt) / (Math.PI / 2) - 1e-9)) + const step = dt / n + const k = (4 / 3) * Math.tan(step / 4) + let t = t1 + const pt = (a: number): [number, number] => [cx + rx * Math.cos(a) * cos - ry * Math.sin(a) * sin, cy + rx * Math.cos(a) * sin + ry * Math.sin(a) * cos] + const tangent = (a: number): [number, number] => [-rx * Math.sin(a) * cos - ry * Math.cos(a) * sin, -rx * Math.sin(a) * sin + ry * Math.cos(a) * cos] + for (let i = 0; i < n; i++) { + const [ax, ay] = pt(t) + const [tx0, ty0] = tangent(t) + const t2 = t + step + const [bx, by] = i === n - 1 ? [x, y] : pt(t2) + const [tx1, ty1] = tangent(t2) + out.push({ k: 'C', x1: ax + k * tx0, y1: ay + k * ty0, x2: bx - k * tx1, y2: by - k * ty1, x: bx, y: by }) + t = t2 + } +} + +const NAMED: Record = { + black: '000000', white: 'ffffff', red: 'ff0000', green: '008000', blue: '0000ff', yellow: 'ffff00', gray: '808080', grey: '808080', + silver: 'c0c0c0', maroon: '800000', purple: '800080', fuchsia: 'ff00ff', lime: '00ff00', olive: '808000', navy: '000080', teal: '008080', + aqua: '00ffff', orange: 'ffa500', lightgray: 'd3d3d3', lightgrey: 'd3d3d3', darkgray: 'a9a9a9', darkgrey: 'a9a9a9', +} + +/** a CSS color (`#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()` / `rgba()`, a few names) as numbers; null for none, `transparent` or anything else */ +export function parseColor(v: string | undefined | null): Rgba | null { + if (!v) return null + let s = v.trim().toLowerCase() + if (NAMED[s]) s = '#' + NAMED[s] + let m = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(s) + if (m) { + let h = m[1] + if (h.length <= 4) h = h.replace(/./g, '$&$&') + return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1 } + } + m = /^rgba?\(\s*([-.\d]+)%?[\s,]+([-.\d]+)%?[\s,]+([-.\d]+)%?(?:[\s,/]+([-.\d]+)(%?))?\s*\)$/.exec(s) + if (m) { + const c = (n: string) => Math.max(0, Math.min(255, Math.round(Number(n)))) + const a = m[4] === undefined ? 1 : Number(m[4]) / (m[5] ? 100 : 1) + return { r: c(m[1]), g: c(m[2]), b: c(m[3]), a: Number.isFinite(a) ? Math.max(0, Math.min(1, a)) : 1 } + } + return null +} diff --git a/src/core/draw/stdfont.ts b/src/core/draw/stdfont.ts new file mode 100644 index 0000000..b18e8d2 --- /dev/null +++ b/src/core/draw/stdfont.ts @@ -0,0 +1,68 @@ +/** + * Helvetica as every PDF reader has it: text no declared font file serves is set in it, in Windows-1252 codes (a + * character outside them is a question mark). Widths are Adobe's, in 1/1000 em. + */ +import type { StdFont } from './types' + +/** U+0020 to U+007E */ +const REGULAR = [ + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, + 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, + 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, +] +const BOLD = [ + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, + 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, + 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, +] + +/** Windows-1252 0x80-0x9F (0 where it has no character) */ +const HIGH = [ + 0x20ac, 0, 0x201a, 0x192, 0x201e, 0x2026, 0x2020, 0x2021, 0x2c6, 0x2030, 0x160, 0x2039, 0x152, 0, 0x17d, 0, + 0, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x2dc, 0x2122, 0x161, 0x203a, 0x153, 0, 0x17e, 0x178, +] +const CODE = new Map(HIGH.map((cp, i) => [cp, 0x80 + i] as [number, number]).filter(([cp]) => cp)) + +/** widths of the codes past ASCII that are not a letter with a mark (whose width is its letter's) */ +const OTHER: Record = { + 0x80: [556, 556], 0x82: [222, 278], 0x83: [556, 556], 0x84: [333, 500], 0x85: [1000, 1000], 0x86: [556, 556], 0x87: [556, 556], 0x88: [333, 333], + 0x89: [1000, 1000], 0x8b: [333, 333], 0x8c: [1000, 1000], 0x91: [222, 278], 0x92: [222, 278], 0x93: [333, 500], 0x94: [333, 500], 0x95: [350, 350], + 0x96: [556, 556], 0x97: [1000, 1000], 0x98: [333, 333], 0x99: [1000, 1000], 0x9b: [333, 333], 0x9c: [944, 944], 0xa0: [278, 278], 0xa1: [333, 333], + 0xa2: [556, 556], 0xa3: [556, 556], 0xa4: [556, 556], 0xa5: [556, 556], 0xa6: [260, 280], 0xa7: [556, 556], 0xa8: [333, 333], 0xa9: [737, 737], + 0xaa: [370, 370], 0xab: [556, 556], 0xac: [584, 584], 0xad: [333, 333], 0xae: [737, 737], 0xaf: [333, 333], 0xb0: [400, 400], 0xb1: [584, 584], + 0xb2: [333, 333], 0xb3: [333, 333], 0xb4: [333, 333], 0xb5: [556, 611], 0xb6: [537, 556], 0xb7: [278, 278], 0xb8: [333, 333], 0xb9: [333, 333], + 0xba: [365, 365], 0xbb: [556, 556], 0xbc: [834, 834], 0xbd: [834, 834], 0xbe: [834, 834], 0xbf: [611, 611], 0xc6: [1000, 1000], 0xd0: [722, 722], + 0xd7: [584, 584], 0xd8: [778, 778], 0xde: [667, 667], 0xdf: [611, 611], 0xe6: [889, 889], 0xf0: [556, 611], 0xf7: [584, 584], 0xf8: [611, 611], + 0xfe: [556, 611], +} + +export const stdFont = (bold?: boolean, italic?: boolean): StdFont => (bold ? (italic ? 'Helvetica-BoldOblique' : 'Helvetica-Bold') : italic ? 'Helvetica-Oblique' : 'Helvetica') + +/** the Windows-1252 code of a character; 0x3f (?) for one it has none for */ +export function stdCode(cp: number): number { + if ((cp >= 0x20 && cp <= 0x7e) || (cp >= 0xa0 && cp <= 0xff)) return cp + return CODE.get(cp) ?? (cp === 0x2011 || cp === 0x2010 ? 0x2d : cp === 0x202f ? 0xa0 : 0x3f) +} + +/** the character of a Windows-1252 code */ +export const stdChar = (code: number): string => String.fromCharCode(code >= 0x80 && code < 0xa0 ? HIGH[code - 0x80] || 0x3f : code) + +const widths = new Map() + +/** a code's width in 1/1000 em */ +export function stdWidth(code: number, bold: boolean): number { + if (code >= 0x20 && code <= 0x7e) return (bold ? BOLD : REGULAR)[code - 0x20] + const other = OTHER[code] + if (other) return other[bold ? 1 : 0] + const key = `${bold ? 1 : 0}${code}` + let w = widths.get(key) + if (w === undefined) { + // a letter with a mark is as wide as its letter + const base = stdChar(code).normalize('NFD').charCodeAt(0) + w = base >= 0x20 && base <= 0x7e ? (bold ? BOLD : REGULAR)[base - 0x20] : 556 + widths.set(key, w) + } + return w +} + +export const isBold = (f: StdFont) => f.startsWith('Helvetica-Bold') diff --git a/src/core/draw/svg-in.ts b/src/core/draw/svg-in.ts new file mode 100644 index 0000000..eed567b --- /dev/null +++ b/src/core/draw/svg-in.ts @@ -0,0 +1,388 @@ +/** + * SVG pictures read as drawing commands: the charts and diagrams the engine draws (`Svg` of diagram/svg.ts writes a + * small, fixed set of elements), and SVG pictures in documents as far as they keep to the same set. Read: `svg`, + * `g`, `rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`, `path`, `text` (one line, its font, size, weight, + * style, anchor, underline), `image` (data: URLs of PNG / JPEG / GIF), `use` of those, presentation attributes and + * simple `style`, transforms, linear and radial gradients, clip paths; a pattern paints with its first color. Scripts, + * CSS style sheets, filters, masks and external references are not followed. + */ +import type { FontBook } from '../font/book' +import { parseXml, type XEl } from '../xml' +import { bounds, ellipsePath, multiply, parseColor, parsePath, rectPath, roundRectPath, transformPath, IDENTITY } from './path' +import { sniffImage } from './image' +import { textLine } from './text' +import type { DrawItem, Matrix, Paint, Rgba, Seg, Stop, StrokeStyle } from './types' + +/** + * Elements read from one picture, and path segments drawn, at most: counted as drawn, so `use` repeating `use`s + * cannot multiply a small file into more (a crafted file cannot make one take the memory) + */ +export const MAX_SVG_ELEMENTS = 100_000 +export const MAX_SVG_SEGMENTS = 1_000_000 + +export interface SvgReadOptions { + /** the size the picture is drawn at (default its own) */ + width?: number + height?: number + onMissing?: (font: string) => void +} + +interface Style { + fill: string + stroke: string + strokeWidth: number + dash?: number[] + cap?: 'butt' | 'round' | 'square' + join?: 'miter' | 'round' | 'bevel' + fillOpacity: number + strokeOpacity: number + fillRule: 'nonzero' | 'evenodd' + font: string + fontSize: number + bold: boolean + italic: boolean + anchor: 'start' | 'middle' | 'end' + underline: boolean +} + +const ROOT: Style = { + fill: '#000000', + stroke: 'none', + strokeWidth: 1, + fillOpacity: 1, + strokeOpacity: 1, + fillRule: 'nonzero', + font: 'Helvetica, Arial, sans-serif', + fontSize: 16, + bold: false, + italic: false, + anchor: 'start', + underline: false, +} + +const local = (n: string) => n.replace(/^.*:/, '') + +const num = (v: string | undefined, dflt = 0): number => { + if (v === undefined) return dflt + const x = parseFloat(v) + return Number.isFinite(x) ? x : dflt +} + +/** a length that may be a percentage of `of` */ +const len = (v: string | undefined, of: number, dflt = 0): number => (v !== undefined && v.trim().endsWith('%') ? (num(v) / 100) * of : num(v, dflt)) + +/** `transform="…"` as a matrix */ +export function parseTransform(v: string | undefined): Matrix { + let m: Matrix = IDENTITY + if (!v) return m + const re = /(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g + for (let x = re.exec(v); x; x = re.exec(v)) { + const a = x[2].split(/[\s,]+/).filter(Boolean).map(Number) + let t: Matrix = IDENTITY + switch (x[1]) { + case 'matrix': + if (a.length >= 6) t = [a[0], a[1], a[2], a[3], a[4], a[5]] + break + case 'translate': + t = [1, 0, 0, 1, a[0] || 0, a[1] || 0] + break + case 'scale': + t = [a[0] ?? 1, 0, 0, a[1] ?? a[0] ?? 1, 0, 0] + break + case 'rotate': { + const r = ((a[0] || 0) * Math.PI) / 180 + const c = Math.cos(r) + const s = Math.sin(r) + const cx = a[1] || 0 + const cy = a[2] || 0 + t = [c, s, -s, c, cx - c * cx + s * cy, cy - s * cx - c * cy] + break + } + case 'skewX': + t = [1, 0, Math.tan(((a[0] || 0) * Math.PI) / 180), 1, 0, 0] + break + case 'skewY': + t = [1, Math.tan(((a[0] || 0) * Math.PI) / 180), 0, 1, 0, 0] + break + } + if (t.some((k) => !Number.isFinite(k))) continue + // the functions apply right to left: the last one first + m = multiply(t, m) + } + return m +} + +/** Reads an SVG picture as drawing commands with (0, 0) at its top left. */ +export async function svgItems(svg: string, book: FontBook, opts: SvgReadOptions = {}): Promise { + const root = parseXml(svg) + if (local(root.n) !== 'svg') throw new Error('Not an SVG picture') + const ids = new Map() + let count = 0 + const index = (el: XEl) => { + if (++count > MAX_SVG_ELEMENTS) throw new Error(`An SVG picture of more than ${MAX_SVG_ELEMENTS} elements is not drawn`) + if (el.a.id) ids.set(el.a.id, el) + for (const c of el.c) index(c) + } + index(root) + const vb = (root.a.viewBox ?? '').split(/[\s,]+/).map(Number) + const hasVb = vb.length === 4 && vb.every(Number.isFinite) && vb[2] > 0 && vb[3] > 0 + const ownW = len(root.a.width, 0, hasVb ? vb[2] : 300) || (hasVb ? vb[2] : 300) + const ownH = len(root.a.height, 0, hasVb ? vb[3] : 150) || (hasVb ? vb[3] : 150) + const W = opts.width ?? ownW + const H = opts.height ?? ownH + // the viewBox stretched to the size (preserveAspectRatio none: the engine draws at the size it is asked for) + const m: Matrix = hasVb ? [W / vb[2], 0, 0, H / vb[3], vb[0] ? (-vb[0] * W) / vb[2] : 0, vb[1] ? (-vb[1] * H) / vb[3] : 0] : [W / ownW, 0, 0, H / ownH, 0, 0] + const reader = new SvgReader(ids, book, opts, hasVb ? vb[2] : ownW, hasVb ? vb[3] : ownH) + const items = await reader.children(root, ROOT, 0) + return [{ t: 'group', transform: m, clip: rectPath(hasVb ? vb[0] : 0, hasVb ? vb[1] : 0, hasVb ? vb[2] : ownW, hasVb ? vb[3] : ownH), items }] +} + +const tooLarge = () => new Error(`An SVG picture of more than ${MAX_SVG_ELEMENTS} elements or ${MAX_SVG_SEGMENTS} path segments is not drawn`) + +class SvgReader { + /** elements and path segments drawn so far */ + private drawn = 0 + private segments = 0 + /** the ids a `use` is drawing: one that refers back to itself is drawn once */ + private using = new Set() + + constructor( + private ids: Map, + private book: FontBook, + private opts: SvgReadOptions, + private vw: number, + private vh: number, + ) {} + + async children(el: XEl, st: Style, depth: number): Promise { + const out: DrawItem[] = [] + if (depth > 64) return out + for (const c of el.c) out.push(...(await this.element(c, st, depth + 1))) + return out + } + + private style(el: XEl, parent: Style): Style { + const a: Record = { ...el.a } + // style="a: b; c: d" over the attributes + for (const decl of (el.a.style ?? '').split(';')) { + const k = decl.indexOf(':') + if (k > 0) a[decl.slice(0, k).trim()] = decl.slice(k + 1).trim() + } + const s = { ...parent } + if (a.fill) s.fill = a.fill + if (a.stroke) s.stroke = a.stroke + if (a['stroke-width']) s.strokeWidth = len(a['stroke-width'], Math.hypot(this.vw, this.vh) / Math.SQRT2, 1) + if (a['stroke-dasharray']) s.dash = a['stroke-dasharray'] === 'none' ? undefined : a['stroke-dasharray'].split(/[\s,]+/).map(Number).filter((v) => Number.isFinite(v) && v >= 0) + if (a['stroke-linecap'] === 'round' || a['stroke-linecap'] === 'square' || a['stroke-linecap'] === 'butt') s.cap = a['stroke-linecap'] + if (a['stroke-linejoin'] === 'round' || a['stroke-linejoin'] === 'bevel' || a['stroke-linejoin'] === 'miter') s.join = a['stroke-linejoin'] + if (a['fill-opacity']) s.fillOpacity = Math.max(0, Math.min(1, num(a['fill-opacity'], 1))) + if (a['stroke-opacity']) s.strokeOpacity = Math.max(0, Math.min(1, num(a['stroke-opacity'], 1))) + if (a['fill-rule'] === 'evenodd' || a['fill-rule'] === 'nonzero') s.fillRule = a['fill-rule'] + if (a['font-family']) s.font = a['font-family'] + if (a['font-size']) s.fontSize = num(a['font-size'], s.fontSize) + if (a['font-weight']) s.bold = a['font-weight'] === 'bold' || a['font-weight'] === 'bolder' || num(a['font-weight'], 400) >= 600 + if (a['font-style']) s.italic = a['font-style'] === 'italic' || a['font-style'] === 'oblique' + if (a['text-anchor'] === 'middle' || a['text-anchor'] === 'end' || a['text-anchor'] === 'start') s.anchor = a['text-anchor'] + if (a['text-decoration']) s.underline = a['text-decoration'].includes('underline') + return s + } + + /** a paint: a color, a gradient, a pattern's first color */ + private paint(v: string, opacity: number, box: [number, number, number, number] | null, el: XEl): Paint | null { + if (!v || v === 'none' || v === 'transparent') return null + const ref = /^url\(\s*['"]?#([^'")\s]+)['"]?\s*\)/.exec(v) + if (ref) { + const def = this.ids.get(ref[1]) + if (!def) return null + const kind = local(def.n) + if (kind === 'linearGradient' || kind === 'radialGradient') return this.gradient(def, opacity, box) + if (kind === 'pattern') { + // a pattern paints with its first fill: its background + const first = def.c.find((c) => c.a.fill && c.a.fill !== 'none') + const c = parseColor(first?.a.fill) + return c ? { t: 'color', color: { ...c, a: c.a * opacity } } : null + } + return null + } + const c = v === 'currentColor' ? parseColor(el.a.color) ?? { r: 0, g: 0, b: 0, a: 1 } : parseColor(v) + return c ? { t: 'color', color: { ...c, a: c.a * opacity } } : null + } + + private gradient(def: XEl, opacity: number, box: [number, number, number, number] | null): Paint | null { + // stops may come from the gradient it refers to + let stopsEl = def + for (let k = 0; k < 8 && !stopsEl.c.some((c) => local(c.n) === 'stop'); k++) { + const href = (stopsEl.a.href ?? stopsEl.a['xlink:href'] ?? '').replace(/^#/, '') + const next = this.ids.get(href) + if (!next) break + stopsEl = next + } + const stops: Stop[] = [] + for (const s of stopsEl.c) { + if (local(s.n) !== 'stop') continue + const st: Record = { ...s.a } + for (const decl of (s.a.style ?? '').split(';')) { + const k = decl.indexOf(':') + if (k > 0) st[decl.slice(0, k).trim()] = decl.slice(k + 1).trim() + } + const c = parseColor(st['stop-color'] ?? '#000') + if (!c) continue + const at = Math.max(0, Math.min(1, st.offset?.trim().endsWith('%') ? num(st.offset) / 100 : num(st.offset))) + stops.push({ at: Math.max(at, stops[stops.length - 1]?.at ?? 0), color: { ...c, a: c.a * num(st['stop-opacity'], 1) * opacity } }) + } + if (!stops.length) return null + if (stops.length === 1) return { t: 'color', color: stops[0].color } + const user = def.a.gradientUnits === 'userSpaceOnUse' + // objectBoundingBox: fractions of the shape's box + const [x0, y0, x1, y1] = box ?? [0, 0, 1, 1] + const bw = x1 - x0 + const bh = y1 - y0 + const X = (v: string | undefined, d: string) => (user ? len(v ?? d, this.vw) : x0 + (v?.trim().endsWith('%') ? num(v) / 100 : num(v ?? d.replace('%', ''), 0) / (d.endsWith('%') && v === undefined ? 100 : 1)) * bw) + const Y = (v: string | undefined, d: string) => (user ? len(v ?? d, this.vh) : y0 + (v?.trim().endsWith('%') ? num(v) / 100 : num(v ?? d.replace('%', ''), 0) / (d.endsWith('%') && v === undefined ? 100 : 1)) * bh) + if (local(def.n) === 'linearGradient') return { t: 'linear', x0: X(def.a.x1, '0%'), y0: Y(def.a.y1, '0%'), x1: X(def.a.x2, '100%'), y1: Y(def.a.y2, '0%'), stops } + const cx = X(def.a.cx, '50%') + const cy = Y(def.a.cy, '50%') + const r = user ? len(def.a.r ?? '50%', Math.hypot(this.vw, this.vh) / Math.SQRT2) : (def.a.r?.trim().endsWith('%') ? num(def.a.r) / 100 : def.a.r ? num(def.a.r) : 0.5) * Math.hypot(bw, bh) / Math.SQRT2 + return { t: 'radial', cx, cy, r, fx: def.a.fx ? X(def.a.fx, '50%') : cx, fy: def.a.fy ? Y(def.a.fy, '50%') : cy, stops } + } + + private shapePath(el: XEl): Seg[] | null { + const a = el.a + switch (local(el.n)) { + case 'rect': { + const w = len(a.width, this.vw) + const h = len(a.height, this.vh) + if (w <= 0 || h <= 0) return null + const x = len(a.x, this.vw) + const y = len(a.y, this.vh) + const rx = a.rx ?? a.ry + const ry = a.ry ?? a.rx + return rx ? roundRectPath(x, y, w, h, len(rx, this.vw), len(ry, this.vh)) : rectPath(x, y, w, h) + } + case 'circle': { + const r = len(a.r, Math.hypot(this.vw, this.vh) / Math.SQRT2) + return r > 0 ? ellipsePath(len(a.cx, this.vw), len(a.cy, this.vh), r, r) : null + } + case 'ellipse': { + const rx = len(a.rx, this.vw) + const ry = len(a.ry, this.vh) + return rx > 0 && ry > 0 ? ellipsePath(len(a.cx, this.vw), len(a.cy, this.vh), rx, ry) : null + } + case 'line': + return [{ k: 'M', x: len(a.x1, this.vw), y: len(a.y1, this.vh) }, { k: 'L', x: len(a.x2, this.vw), y: len(a.y2, this.vh) }] + case 'polyline': + case 'polygon': { + const p = (a.points ?? '').split(/[\s,]+/).filter(Boolean).map(Number) + const d: Seg[] = [] + for (let i = 0; i + 1 < p.length; i += 2) d.push({ k: i ? 'L' : 'M', x: p[i], y: p[i + 1] }) + if (local(el.n) === 'polygon' && d.length) d.push({ k: 'Z' }) + return d.length ? d : null + } + case 'path': + return a.d ? parsePath(a.d) : null + } + return null + } + + private clip(el: XEl): { clip?: Seg[]; clipRule?: 'evenodd' } { + const ref = /^url\(\s*['"]?#([^'")\s]+)['"]?\s*\)/.exec(el.a['clip-path'] ?? '') + const def = ref && this.ids.get(ref[1]) + if (!def || local(def.n) !== 'clipPath') return {} + const d: Seg[] = [] + let evenodd = false + for (const c of def.c) { + const p = this.shapePath(c) + if (!p) continue + // (a clip's segments count as drawn: each element it clips draws them) + if ((this.segments += p.length) > MAX_SVG_SEGMENTS) throw tooLarge() + const t = parseTransform(c.a.transform) + d.push(...(t === IDENTITY ? p : transformPath(p, t))) + if (c.a['clip-rule'] === 'evenodd') evenodd = true + } + return d.length ? { clip: d, ...(evenodd ? { clipRule: 'evenodd' as const } : {}) } : { clip: [] } + } + + private async element(el: XEl, parent: Style, depth: number): Promise { + if (++this.drawn > MAX_SVG_ELEMENTS) throw tooLarge() + const name = local(el.n) + if (name === 'defs' || name === 'clipPath' || name === 'linearGradient' || name === 'radialGradient' || name === 'pattern' || name === 'style' || name === 'script' || name === 'title' || name === 'desc' || name === 'metadata' || name === 'mask' || name === 'filter' || name === 'symbol' || name === 'marker') return [] + if (el.a.display === 'none' || el.a.visibility === 'hidden') return [] + const st = this.style(el, parent) + const transform = parseTransform(el.a.transform) + const opacity = Math.max(0, Math.min(1, num(el.a.opacity, 1))) + let items: DrawItem[] = [] + if (name === 'g' || name === 'svg' || name === 'a' || name === 'switch') items = await this.children(el, st, depth) + else if (name === 'use') { + const id = (el.a.href ?? el.a['xlink:href'] ?? '').replace(/^#/, '') + const ref = this.ids.get(id) + if (ref && depth < 32 && !this.using.has(id)) { + this.using.add(id) + try { + items = await this.element(ref, st, depth + 1) + } finally { + this.using.delete(id) + } + const dx = num(el.a.x) + const dy = num(el.a.y) + if (dx || dy) items = [{ t: 'group', transform: [1, 0, 0, 1, dx, dy], items }] + } + } else if (name === 'text') items = await this.text(el, st) + else if (name === 'image') items = this.image(el) + else { + const d = this.shapePath(el) + if (d && (this.segments += d.length) > MAX_SVG_SEGMENTS) throw tooLarge() + if (d && d.length) { + const box = bounds(d) + const fill = name === 'line' ? null : this.paint(st.fill, st.fillOpacity, box, el) + const sp = this.paint(st.stroke, st.strokeOpacity, box, el) + const stroke: StrokeStyle | undefined = sp && st.strokeWidth > 0 ? { paint: sp, width: st.strokeWidth, ...(st.dash?.length && st.dash.some((v) => v > 0) ? { dash: st.dash } : {}), ...(st.cap ? { cap: st.cap } : {}), ...(st.join ? { join: st.join } : {}) } : undefined + if (fill || stroke) items = [{ t: 'path', d, ...(fill ? { fill } : {}), ...(st.fillRule === 'evenodd' ? { rule: 'evenodd' as const } : {}), ...(stroke ? { stroke } : {}) }] + } + } + if (!items.length) return [] + const clip = this.clip(el) + if (clip.clip && !clip.clip.length) return [] + if (transform === IDENTITY && !clip.clip && opacity >= 1) return items + return [{ t: 'group', ...(transform !== IDENTITY ? { transform } : {}), ...clip, ...(opacity < 1 ? { opacity } : {}), items }] + } + + private async text(el: XEl, st: Style): Promise { + // one line: the element's text and its tspans', at the element's place + const text = textOf(el).replace(/\s+/g, ' ').trim() + if (!text) return [] + const fill = this.paint(st.fill, st.fillOpacity, null, el) + const color: Rgba = fill?.t === 'color' ? fill.color : fill ? (fill.stops[0]?.color ?? { r: 0, g: 0, b: 0, a: 1 }) : { r: 0, g: 0, b: 0, a: 0 } + if (color.a <= 0) return [] + const x = num(el.a.x?.split(/[\s,]+/)[0]) + const y = num(el.a.y?.split(/[\s,]+/)[0]) + const line = await textLine(this.book, text, { font: st.font, size: st.fontSize, bold: st.bold, italic: st.italic, color, underline: st.underline }, { onMissing: this.opts.onMissing }) + const dx = st.anchor === 'middle' ? -line.width / 2 : st.anchor === 'end' ? -line.width : 0 + return [{ t: 'group', transform: [1, 0, 0, 1, x + dx, y], items: line.items }] + } + + private image(el: XEl): DrawItem[] { + const href = el.a.href ?? el.a['xlink:href'] ?? '' + const m = /^data:([^;,]*)(;base64)?,(.*)$/s.exec(href) + if (!m || !m[2]) return [] + let bytes: Uint8Array + try { + const bin = atob(m[3].replace(/\s+/g, '')) + bytes = new Uint8Array(bin.length) + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) + } catch { + return [] + } + const kind = sniffImage(bytes) + if (kind !== 'png' && kind !== 'jpeg' && kind !== 'gif') return [] + const w = len(el.a.width, this.vw) + const h = len(el.a.height, this.vh) + if (w <= 0 || h <= 0) return [] + return [{ t: 'image', image: { bytes, type: `image/${kind}` }, x: len(el.a.x, this.vw), y: len(el.a.y, this.vh), w, h }] + } +} + +function textOf(el: XEl): string { + let s = el.t ?? '' + for (const c of el.c) if (local(c.n) === 'tspan' || local(c.n) === 'a') s += textOf(c) + return s +} diff --git a/src/core/draw/svg.ts b/src/core/draw/svg.ts new file mode 100644 index 0000000..847f339 --- /dev/null +++ b/src/core/draw/svg.ts @@ -0,0 +1,93 @@ +/** + * A page of drawing commands as an SVG picture: for tests (compared with the viewer's own rendering) and thumbnails. + * Text is written as text at the place of each of its characters, in the font's family, so a picture shows the same + * where the fonts are installed; pictures are embedded as data: URLs. + */ +import { esc } from '../diagram/svg' +import { glyphTexts } from './glyphs' +import type { DrawItem, Page, Paint, Rgba, Seg } from './types' + +const n = (v: number) => String(Math.round(v * 100) / 100) + +const color = (c: Rgba) => `rgb(${c.r},${c.g},${c.b})` + +function pathData(d: Seg[]): string { + return d + .map((s) => (s.k === 'Z' ? 'Z' : s.k === 'C' ? `C${n(s.x1)} ${n(s.y1)} ${n(s.x2)} ${n(s.y2)} ${n(s.x)} ${n(s.y)}` : `${s.k}${n(s.x)} ${n(s.y)}`)) + .join('') +} + +function base64(b: Uint8Array): string { + let s = '' + for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000)) + return btoa(s) +} + +export interface SvgOptions { + /** embed pictures (default true); false leaves their place empty */ + images?: boolean +} + +/** `page` as a self-contained SVG document */ +export function pageToSvg(page: Page, opts: SvgOptions = {}): string { + const defs: string[] = [] + let id = 0 + /** a paint as the value of `attr` (fill, stroke), with its opacity */ + const paint = (p: Paint, attr: 'fill' | 'stroke'): string => { + if (p.t === 'color') return ` ${attr}="${color(p.color)}"${p.color.a < 1 ? ` ${attr}-opacity="${n(p.color.a)}"` : ''}` + const key = `g${++id}` + const stops = p.stops.map((s) => ``).join('') + if (p.t === 'linear') defs.push(`${stops}`) + else defs.push(`${stops}`) + return ` ${attr}="url(#${key})"` + } + const item = (it: DrawItem): string => { + switch (it.t) { + case 'path': { + const fill = it.fill ? paint(it.fill, 'fill') : ' fill="none"' + const s = it.stroke + let stroke = '' + if (s && s.width > 0) { + stroke = `${paint(s.paint, 'stroke')} stroke-width="${n(s.width)}"${s.dash?.length ? ` stroke-dasharray="${s.dash.map(n).join(' ')}"` : ''}${s.cap && s.cap !== 'butt' ? ` stroke-linecap="${s.cap}"` : ''}${s.join && s.join !== 'miter' ? ` stroke-linejoin="${s.join}"` : ''}` + } + return `` + } + case 'text': { + // each glyph's first character at the glyph's place + const xs: string[] = [] + let chars = '' + let x = it.x + const texts = glyphTexts(it) + it.glyphs.forEach((_, i) => { + for (const ch of texts[i]) { + xs.push(n(x + (it.dx?.[i] ?? 0))) + chars += ch + } + x += it.advances[i] + }) + const family = typeof it.font === 'string' ? 'Helvetica, Arial, sans-serif' : `'${it.font.names.family.replace(/['\\]/g, '')}'` + const bold = typeof it.font === 'string' ? it.font.includes('Bold') : it.font.weight >= 600 || it.synthetic?.bold + const italic = typeof it.font === 'string' ? it.font.includes('Oblique') : it.font.italic || it.synthetic?.italic + return `${esc(chars)}` + } + case 'image': + if (opts.images === false) return '' + return `` + case 'group': { + let clip = '' + if (it.clip) { + const key = `c${++id}` + defs.push(``) + clip = ` clip-path="url(#${key})"` + } + // the clip is in the group's coordinates: a transform goes on a group of its own around it + const inner = `${it.items.map(item).join('')}` + return it.transform ? `${inner}` : inner + } + case 'link': + return '' + } + } + const body = page.items.map(item).join('') + return `${defs.length ? `${defs.join('')}` : ''}${body}` +} diff --git a/src/core/draw/text.ts b/src/core/draw/text.ts new file mode 100644 index 0000000..ae1e289 --- /dev/null +++ b/src/core/draw/text.ts @@ -0,0 +1,476 @@ +/** + * Paragraphs laid out in a box without a browser: text measured in the host's font files (`FontBook`), lines broken + * where CSS breaks them (`white-space: pre-wrap`, `overflow-wrap: break-word`), aligned, spaced as CSS spaces lines + * of a unitless `line-height`, and drawn as glyph runs. Text no file serves is set in Helvetica. Slides, sheets and + * documents all lay out their text with it. + */ +import type { FontBook } from '../font/book' +import type { Font } from '../font/font' +import { stdCode, stdFont, stdWidth } from './stdfont' +import { rectPath } from './path' +import type { DrawItem, Rgba, StdFont } from './types' + +export interface RunStyle { + /** a CSS font-family list (`cssFont()`) */ + font: string + /** px */ + size: number + bold?: boolean + italic?: boolean + color: Rgba + underline?: boolean + strike?: boolean + /** raised (positive) or lowered, in percent of the size: drawn smaller, as superscript or subscript */ + baseline?: number + highlight?: Rgba + caps?: boolean + href?: string +} + +export interface ParaRun { + text: string + style: RunStyle + /** a line break */ + br?: boolean +} + +export interface ParaSpec { + runs: ParaRun[] + align: 'left' | 'center' | 'right' | 'justify' + /** px: the left margin of every line, and how far the first line starts from it (negative: a hanging indent) */ + marL: number + indent: number + /** `line-height` as a multiple of each run's size (default 1.2), or in px */ + lineMult?: number + linePx?: number + /** px above and below */ + before: number + after: number + bullet?: { text: string; style: RunStyle } + /** the size of an empty paragraph's line (px) */ + emptySize: number +} + +export interface LayoutOptions { + /** break lines at the width (default true) */ + wrap?: boolean + /** told of text no font file serves (set in Helvetica) */ + onMissing?: (font: string) => void +} + +/** a measured piece of a run: glyphs from one font, positions in px, clusters in the run's text */ +interface Piece { + font: Font | StdFont + glyphs: number[] + advances: number[] + dx?: number[] + dy?: number[] + clusters: number[] + /** the run's text the piece stands for: [from, to) */ + from: number + to: number + /** clusters in order ('asc'), in reverse (right to left, 'desc'), or neither (a shaper reordered them) */ + order: 'asc' | 'desc' | null + synthetic?: { bold?: boolean; italic?: boolean } + ascent: number + descent: number +} + +interface Measured { + text: string + style: RunStyle + /** the drawn size: smaller for superscript and subscript */ + size: number + rise: number + pieces: Piece[] + /** for each UTF-16 unit of the text, how far it moves the pen (a ligature's width goes to its first character) */ + adv: Float64Array + /** 1 where a cluster starts: a line is never broken inside one (a character of two UTF-16 units, a letter and its marks) */ + starts: Uint8Array + ascent: number + descent: number + br?: boolean +} + +/** Helvetica's line metrics as browsers take them from Arial, which stands in for it */ +const STD_ASCENT = 0.905 +const STD_DESCENT = 0.212 + +const DEFAULT_TAB = 96 + +async function measureRun(book: FontBook, run: ParaRun, opts: LayoutOptions): Promise { + const st = run.style + const text = st.caps ? run.text.toUpperCase() : run.text + const size = st.baseline ? st.size * 0.65 : st.size + const rise = st.baseline ? (st.baseline / 100) * st.size : 0 + const weight = st.bold ? 700 : 400 + const m = await book.measure({ text, font: st.font, size, weight, italic: !!st.italic }) + const adv = new Float64Array(text.length) + const starts = new Uint8Array(text.length) + const pieces: Piece[] = [] + let ascent = m.ascent + let descent = m.descent + for (const p of m.pieces) { + if (p.font && p.run) { + const k = size / p.font.unitsPerEm + const r = p.run + const clusters = r.clusters.map((c) => c + p.from) + const advances = r.advances.map((a) => a * k) + clusters.forEach((c, i) => ((adv[c] += advances[i]), (starts[c] = 1))) + const line = p.font.lineMetrics() + const synthetic = { bold: weight >= 600 && p.font.weight < 600, italic: !!st.italic && !p.font.italic } + pieces.push({ + font: p.font, + glyphs: r.glyphs, + advances, + ...(r.dx.some((v) => v) || r.dy.some((v) => v) ? { dx: r.dx.map((v) => v * k), dy: r.dy.map((v) => v * k) } : {}), + clusters, + from: p.from, + to: p.to, + order: orderOf(clusters), + ...(synthetic.bold || synthetic.italic ? { synthetic } : {}), + ascent: line.ascent * k, + descent: line.descent * k, + }) + } else { + // no file: Helvetica, one code per character + const font = stdFont(st.bold, st.italic) + const glyphs: number[] = [] + const advances: number[] = [] + const clusters: number[] = [] + for (let i = p.from; i < p.to; ) { + const cp = text.codePointAt(i)! + const code = stdCode(cp) + const w = (stdWidth(code, !!st.bold) * size) / 1000 + glyphs.push(code) + advances.push(w) + clusters.push(i) + adv[i] += w + starts[i] = 1 + i += cp > 0xffff ? 2 : 1 + } + if (!/^\s*$/.test(text.slice(p.from, p.to))) opts.onMissing?.(st.font) + pieces.push({ font, glyphs, advances, clusters, from: p.from, to: p.to, order: 'asc', ascent: STD_ASCENT * size, descent: STD_DESCENT * size }) + } + } + if (!ascent && !descent) { + ascent = STD_ASCENT * size + descent = STD_DESCENT * size + } + return { text, style: st, size, rise, pieces, adv, starts, ascent, descent, br: run.br } +} + +function orderOf(clusters: number[]): 'asc' | 'desc' | null { + let asc = true + let desc = true + for (let i = 1; i < clusters.length; i++) { + if (clusters[i] < clusters[i - 1]) asc = false + if (clusters[i] > clusters[i - 1]) desc = false + } + return asc ? 'asc' : desc ? 'desc' : null +} + +/** the glyphs of a piece that stand for text in [a, b), in drawing order: found by halving where clusters are in order */ +function glyphIndices(p: Piece, a: number, b: number): number[] { + const cl = p.clusters + const first = (pred: (c: number) => boolean) => { + let lo = 0 + let hi = cl.length + while (lo < hi) { + const mid = (lo + hi) >> 1 + if (pred(cl[mid])) hi = mid + else lo = mid + 1 + } + return lo + } + const span = (lo: number, hi: number) => Array.from({ length: Math.max(0, hi - lo) }, (_, k) => lo + k) + if (p.order === 'asc') return span(first((c) => c >= a), first((c) => c >= b)) + if (p.order === 'desc') return span(first((c) => c < b), first((c) => c < a)) + // (reordered by a shaper: every glyph looked at) + const out: number[] = [] + cl.forEach((c, i) => c >= a && c < b && out.push(i)) + return out +} + +/** a place in a paragraph: run and UTF-16 index in its text */ +interface Pos { + run: number + at: number +} + +interface Line { + from: Pos + /** exclusive */ + to: Pos + /** the width of what is drawn (without trailing spaces) */ + width: number + /** the line ends the paragraph or at a break: not stretched when justified */ + last: boolean +} + +const isSpace = (c: string) => c === ' ' || c === '\t' || c === ' ' +/** characters a line breaks after or around: CJK ideographs, kana, Hangul (each a word of its own) */ +const isCjk = (cp: number) => (cp >= 0x2e80 && cp <= 0x9fff) || (cp >= 0xac00 && cp <= 0xd7af) || (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xff00 && cp <= 0xffef) || (cp >= 0x20000 && cp <= 0x323af) + +export interface LaidOut { + /** drawing commands with (0, 0) at the box's top left */ + items: DrawItem[] + /** the height the paragraphs take */ + height: number + /** the widest line */ + width: number +} + +/** + * Lays out paragraphs in a box `width` px wide, the first line's top at 0. Text that does not fit the height is laid + * out all the same: the caller anchors and clips. + */ +export async function layoutParagraphs(book: FontBook, paras: ParaSpec[], width: number, opts: LayoutOptions = {}): Promise { + const items: DrawItem[] = [] + let y = 0 + let widest = 0 + for (const p of paras) { + y += p.before + const runs: Measured[] = [] + for (const r of p.runs) runs.push(await measureRun(book, r, opts)) + const bullet = p.bullet && p.runs.some((r) => r.text || r.br) ? await measureRun(book, { text: p.bullet.text, style: p.bullet.style }, opts) : undefined + // the bullet takes the hanging indent, or its own width and 0.4 em + const hang = p.indent < 0 ? -p.indent : 0 + const bulletW = bullet ? Math.max(hang, bullet.adv.reduce((a, b) => a + b, 0) + (hang ? 0 : 0.4 * bullet.size)) : 0 + const firstX = p.marL + p.indent + bulletW + const avail = (first: boolean) => Math.max(0, width - (first ? firstX : p.marL)) + const lines = breakLines(runs, avail, opts.wrap !== false) + const empty = !lines.length || runs.every((r) => !r.text.length) + if (empty) { + // an empty paragraph is one line of its end size + const h = p.linePx ?? p.emptySize * (p.lineMult ?? 1.2) + y += h + p.after + continue + } + lines.forEach((line, li) => { + const x0 = li === 0 ? firstX : p.marL + // the line's height: each run's box (its size × the multiple, or the px height) around its baseline, as CSS + // centres an inline box's glyphs in its line-height + let above = 0 + let below = 0 + forEach(runs, line, (r) => { + const lh = p.linePx ?? r.size * (p.lineMult ?? 1.2) + const half = (lh - (r.ascent + r.descent)) / 2 + above = Math.max(above, r.ascent + half + r.rise) + below = Math.max(below, r.descent + half - r.rise) + }) + if (li === 0 && bullet) { + const lh = p.linePx ?? bullet.size * (p.lineMult ?? 1.2) + const half = (lh - (bullet.ascent + bullet.descent)) / 2 + above = Math.max(above, bullet.ascent + half) + below = Math.max(below, bullet.descent + half) + } + // a line of nothing but a break: as high as an empty paragraph + if (!above && !below) above = p.linePx ?? p.emptySize * (p.lineMult ?? 1.2) + const baseline = y + above + const room = avail(li === 0) + const extra = Math.max(0, room - line.width) + let x = x0 + (p.align === 'center' ? extra / 2 : p.align === 'right' ? extra : 0) + // justified: the room left goes to the spaces between words (not to those that end the line) + const just = { stretch: 0, spaces: 0 } + if (p.align === 'justify' && !line.last) { + let pending = 0 + forEach(runs, line, (r, a, b) => { + for (let i = a; i < b; i++) { + if (r.text[i] === ' ') pending++ + else if (!isSpace(r.text[i])) (just.spaces += pending), (pending = 0) + } + }) + just.stretch = just.spaces ? extra / just.spaces : 0 + } + if (li === 0 && bullet) emit(items, bullet, 0, bullet.text.length, p.marL + p.indent, baseline, { stretch: 0, spaces: 0 }) + forEach(runs, line, (r, a, b) => { + x = emit(items, r, a, b, x, baseline, just) + }) + widest = Math.max(widest, x0 + line.width) + y = baseline + below + }) + y += p.after + } + return { items, height: y, width: widest } +} + +/** each run's part of a line: `fn(run, from, to)` */ +function forEach(runs: Measured[], line: Line, fn: (r: Measured, from: number, to: number) => void) { + for (let k = line.from.run; k <= line.to.run && k < runs.length; k++) { + const r = runs[k] + const a = k === line.from.run ? line.from.at : 0 + const b = k === line.to.run ? line.to.at : r.text.length + if (b > a || (r.br && k < line.to.run)) fn(r, a, b) + } +} + +/** greedy line breaking: a line ends at the last break opportunity that fits, or inside a word longer than the line */ +function breakLines(runs: Measured[], avail: (first: boolean) => number, wrap: boolean): Line[] { + const lines: Line[] = [] + let start: Pos = { run: 0, at: 0 } + let width = 0 + /** after the last break opportunity: where the line would end, and its width without trailing spaces */ + let brk: { pos: Pos; width: number } | null = null + /** the width up to the end of the last non-space */ + let inked = 0 + /** the first character of the cluster the loop is in */ + let base = 0 + const push = (to: Pos, w: number, last: boolean) => { + lines.push({ from: start, to, width: w, last }) + start = to + } + for (let k = 0; k < runs.length; k++) { + const r = runs[k] + if (r.br) { + push({ run: k, at: 0 }, inked, true) + start = { run: k + 1, at: 0 } + width = inked = 0 + brk = null + continue + } + for (let i = 0; i < r.text.length; i++) { + const c = r.text[i] + const cp = r.text.codePointAt(i)! + let w = r.adv[i] + // inside a cluster: no break here, nor a line end; after its last unit, a line can end after an ideograph + if (i > 0 && !r.starts[i] && c !== '\n' && c !== '\r' && c !== '\v' && c !== '\t') { + width += w + inked = width + if (isCjk(base) && (i + 1 >= r.text.length || r.starts[i + 1])) brk = { pos: { run: k, at: i + 1 }, width: inked } + continue + } + base = cp + if (c === '\t') { + // to the next default tab stop + const at = width + w = (Math.floor(at / DEFAULT_TAB) + 1) * DEFAULT_TAB - at + r.adv[i] = w + } + if (c === '\n' || c === '\r' || c === '\v') { + push({ run: k, at: i }, inked, true) + start = { run: k, at: i + 1 } + width = inked = 0 + brk = null + continue + } + const space = isSpace(c) + // a break before an ideograph + if (!space && isCjk(cp) && width > 0) brk = { pos: { run: k, at: i }, width: inked } + if (!space && wrap && width + w > avail(lines.length === 0) + 0.01 && width > 0) { + // past the end: break at the last opportunity, else here (a word longer than the line) + const at = brk ?? { pos: { run: k, at: i }, width: inked } + push(at.pos, at.width, false) + // measure again from the new start to here + width = 0 + inked = 0 + for (let kk = at.pos.run; kk <= k; kk++) { + const rr = runs[kk] + for (let ii = kk === at.pos.run ? at.pos.at : 0; ii < (kk === k ? i : rr.text.length); ii++) { + width += rr.adv[ii] + if (!isSpace(rr.text[ii])) inked = width + } + } + brk = null + } + width += w + if (!space) inked = width + // after spaces, hyphens and ideographs, a line can end + if (space || c === '-' || c === '‐' || c === '/' || isCjk(cp)) { + const next = i + 1 < r.text.length ? r.text[i + 1] : k + 1 < runs.length ? runs[k + 1].text[0] : '' + const whole = i + 1 >= r.text.length || r.starts[i + 1] + if (whole && !(space && next && isSpace(next))) brk = { pos: { run: k, at: i + 1 }, width: inked } + } + } + } + const end = { run: runs.length - 1, at: runs[runs.length - 1]?.text.length ?? 0 } + if (runs.length && (start.run < end.run || (start.run === end.run && start.at < end.at) || !lines.length)) push(end, inked, true) + return lines +} + +/** draws `r.text[a, b)` from the pen at `x` on `baseline`; returns where the pen ends */ +function emit(items: DrawItem[], r: Measured, a: number, b: number, x: number, baseline: number, just: { stretch: number; spaces: number }): number { + const st = r.style + const mark = items.length + const y = baseline - r.rise + const startX = x + // the pieces in the line: they follow one another through the text, so the first is found by halving + let lo = 0 + let hi = r.pieces.length + while (lo < hi) { + const mid = (lo + hi) >> 1 + if (r.pieces[mid].to > a) hi = mid + else lo = mid + 1 + } + for (let k = lo; k < r.pieces.length && r.pieces[k].from < b; k++) { + const p = r.pieces[k] + // the piece's part of the line: its own text, so a copy gives each character once + const from = Math.max(a, p.from) + const to = Math.min(b, p.to) + if (to <= from) continue + const indices = glyphIndices(p, from, to) + const glyphs: number[] = [] + const advances: number[] = [] + const clusters: number[] = [] + const dx: number[] = [] + const dy: number[] = [] + let px = x + for (const i of indices) { + const c = p.clusters[i] + const ch = r.text[c] + let adv = ch === '\t' ? r.adv[c] : p.advances[i] + if (just.spaces > 0 && ch === ' ') (adv += just.stretch), just.spaces-- + x += adv + if (ch === '\t') { + // a tab moves the pen and draws nothing (its glyph would be a box, or a question mark) + if (advances.length) advances[advances.length - 1] += adv + else px = x + continue + } + glyphs.push(p.glyphs[i]) + advances.push(adv) + clusters.push(c - from) + if (p.dx) dx.push(p.dx[i]), dy.push(p.dy![i]) + } + if (!glyphs.length) continue + const text = r.text.slice(from, to) + // spaces draw nothing: a run of them is only a move + if (st.color.a > 0 && /\S/.test(text)) { + items.push({ + t: 'text', + x: px, + y, + size: r.size, + font: p.font, + glyphs, + advances, + ...(p.dx ? { dx, dy } : {}), + text, + clusters, + fill: st.color, + ...(p.synthetic ? { synthetic: p.synthetic } : {}), + }) + } + } + const w = x - startX + if (w > 0) { + const top = y - r.ascent + const h = r.ascent + r.descent + // (a highlight is behind the run's text) + if (st.highlight) items.splice(mark, 0, { t: 'path', d: rectPath(startX, top, w, h), fill: { t: 'color', color: st.highlight } }) + // the lines a browser draws: under the baseline by a tenth of the size, through it at a third + const thick = Math.max(0.5, r.size / 15) + if (st.underline) items.push({ t: 'path', d: rectPath(startX, y + r.size * 0.1, w, thick), fill: { t: 'color', color: st.color } }) + if (st.strike) items.push({ t: 'path', d: rectPath(startX, y - r.size * 0.3, w, thick), fill: { t: 'color', color: st.color } }) + if (st.href) items.push({ t: 'link', x: startX, y: top, w, h, url: st.href }) + } + return x +} + +/** One line of text, not broken: its drawing commands from the pen at (0, 0) on the baseline, and its width. */ +export async function textLine(book: FontBook, text: string, style: RunStyle, opts: LayoutOptions = {}): Promise<{ items: DrawItem[]; width: number }> { + const r = await measureRun(book, { text, style }, opts) + const items: DrawItem[] = [] + const width = emit(items, r, 0, r.text.length, 0, 0, { stretch: 0, spaces: 0 }) + return { items, width } +} diff --git a/src/core/draw/types.ts b/src/core/draw/types.ts new file mode 100644 index 0000000..6e8658d --- /dev/null +++ b/src/core/draw/types.ts @@ -0,0 +1,95 @@ +/** + * Pages of drawing commands: what a layout makes of a document (a slide, a sheet's pages, a document's pages), and + * what a backend paints (PDF, SVG). Lengths are CSS px (1/96 in), y down, as in the document models; a PDF backend + * scales them to points. + */ +import type { Font } from '../font/font' + +/** [a, b, c, d, e, f]: x' = a·x + c·y + e, y' = b·x + d·y + f (as SVG and PDF) */ +export type Matrix = [number, number, number, number, number, number] + +/** red, green, blue 0-255, alpha 0-1 */ +export interface Rgba { + r: number + g: number + b: number + a: number +} + +/** a path: moves, lines, cubic curves and closes, in absolute coordinates */ +export type Seg = { k: 'M' | 'L'; x: number; y: number } | { k: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number } | { k: 'Z' } + +export interface Stop { + /** 0-1 */ + at: number + color: Rgba +} + +export type Paint = + | { t: 'color'; color: Rgba } + /** from (x0, y0) to (x1, y1), in the coordinates of the item painted */ + | { t: 'linear'; x0: number; y0: number; x1: number; y1: number; stops: Stop[] } + /** circles from (fx, fy) r 0 to (cx, cy) r */ + | { t: 'radial'; cx: number; cy: number; r: number; fx: number; fy: number; stops: Stop[] } + +export interface StrokeStyle { + paint: Paint + width: number + dash?: number[] + cap?: 'butt' | 'round' | 'square' + join?: 'miter' | 'round' | 'bevel' +} + +/** the fonts a PDF has without a file: text no declared file serves is set in these (characters of Windows-1252 only) */ +export type StdFont = 'Helvetica' | 'Helvetica-Bold' | 'Helvetica-Oblique' | 'Helvetica-BoldOblique' + +/** a picture's bytes: JPEG and PNG are drawn; another format is skipped by the backend that cannot draw it */ +export interface ImageData { + bytes: Uint8Array + /** the MIME type, from the file's first bytes */ + type: string + /** a key the backend shares the picture by when it is drawn more than once (its part name) */ + key?: string +} + +export type DrawItem = + | { t: 'path'; d: Seg[]; fill?: Paint; rule?: 'nonzero' | 'evenodd'; stroke?: StrokeStyle } + | { + t: 'text' + /** the pen at the start of the baseline */ + x: number + y: number + /** px */ + size: number + /** a font file, or a PDF's own font for text no file serves (then `glyphs` are Windows-1252 codes) */ + font: Font | StdFont + glyphs: number[] + /** how far the pen moves after each glyph, px */ + advances: number[] + /** glyph offsets, px (right and up); absent when all are 0 */ + dx?: number[] + dy?: number[] + /** + * the text the glyphs stand for (all of it, and nothing more), and for each glyph the index of its first character + * (copy and search in a PDF) + */ + text: string + clusters: number[] + fill: Rgba + /** a regular file stands in for bold or italic text: the backend thickens or slants it */ + synthetic?: { bold?: boolean; italic?: boolean } + } + /** the picture stretched over x, y, w, h */ + | { t: 'image'; image: ImageData; x: number; y: number; w: number; h: number; opacity?: number } + | { t: 'group'; transform?: Matrix; clip?: Seg[]; clipRule?: 'nonzero' | 'evenodd'; opacity?: number; items: DrawItem[] } + /** a link over an area (not drawn) */ + | { t: 'link'; x: number; y: number; w: number; h: number; url: string } + +export interface Page { + /** px */ + w: number + h: number + items: DrawItem[] + /** the page's title (a slide's): a PDF's outline */ + title?: string +} diff --git a/src/core/font/book.ts b/src/core/font/book.ts index cb18d87..a92fe14 100644 --- a/src/core/font/book.ts +++ b/src/core/font/book.ts @@ -145,10 +145,15 @@ export class FontBook { } } + /** fonts by their file: a file declared for several families (Calibri and Carlito) is read once, and is one font */ + private files = new Map>() + private load(face: Face): Promise { - return (face.font ??= (async () => { + const { src } = face.source + const known = this.files.get(src) + if (known) return (face.font ??= known) + const p = (face.font ??= (async () => { try { - const { src } = face.source let data: ArrayBuffer | ArrayBufferView | Blob if (typeof src !== 'string') data = src else if (this.opts.fetch) data = await this.opts.fetch(src) @@ -163,6 +168,8 @@ export class FontBook { return null } })()) + this.files.set(src, p) + return p } /** diff --git a/src/core/font/font.ts b/src/core/font/font.ts index 5fa4b14..b87ae28 100644 --- a/src/core/font/font.ts +++ b/src/core/font/font.ts @@ -227,6 +227,8 @@ export class Font { */ readonly variable: boolean /** the license lets the font be embedded in a document (OS/2 fsType: not "restricted license") */ + /** OS/2 fsType, the license's embedding bits: 0x0100 no subsetting, 0x0200 bitmaps only (0 without an OS/2 table) */ + readonly fsType: number readonly embeddable: boolean /** substitutions the font makes by itself: ligatures, and what else it does to plain text */ readonly gsub: Substitution | null @@ -294,7 +296,8 @@ export class Font { this.fixedPitch = has(post, 16) && post.getUint32(12) !== 0 this.variable = tables.has('fvar') // fsType bit 1: restricted license embedding (bit 9, bitmaps only, does not matter to outlines) - this.embeddable = !(has(os2, 10) && os2.getUint16(8) & 0x0002) + this.fsType = has(os2, 10) ? os2.getUint16(8) : 0 + this.embeddable = !(this.fsType & 0x0002) this.names = readNames(tables.get('name')) this.cmap = readCmap(need('cmap')) @@ -334,8 +337,8 @@ export class Font { * Throws a `FontError` that says what is wrong with a file that cannot be read. */ static async open(data: ArrayBuffer | ArrayBufferView | Blob, index = 0): Promise { - const bytes = - data instanceof Uint8Array ? data : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data instanceof Blob ? await data.arrayBuffer() : data) + // (a Node Buffer as a plain Uint8Array: its `slice` shares the memory, where a subset copies a table to change it) + const bytes = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data instanceof Blob ? await data.arrayBuffer() : data) const sfnt = await readSfnt(bytes, index) try { return new Font(sfnt.tables, sfnt) diff --git a/src/core/font/subset.ts b/src/core/font/subset.ts index 4b86a87..83c845f 100644 --- a/src/core/font/subset.ts +++ b/src/core/font/subset.ts @@ -97,7 +97,7 @@ function writeCmap(chars: [number, number][]): Uint8Array { function commonTables(font: Font, kept: number[], chars: [number, number][], glyphs: Map): Map { const t = font.tables const tables = new Map() - for (const tag of ['OS/2', 'name', 'head', 'hhea']) if (t.has(tag)) tables.set(tag, t.get(tag)!.slice()) + for (const tag of ['OS/2', 'name', 'head', 'hhea']) if (t.has(tag)) tables.set(tag, new Uint8Array(t.get(tag)!)) const n = kept.length // every glyph with its own width: the short form (one width for the last glyphs) saves nothing in a subset view(tables.get('hhea')!).setUint16(34, n) @@ -183,7 +183,7 @@ function subsetGlyf(font: Font, used: Iterable, chars: [number, number][ tables.set('glyf', newGlyf) tables.set('loca', newLoca) view(tables.get('head')!).setUint16(50, 1) - const maxp = t.get('maxp')!.slice() + const maxp = new Uint8Array(t.get('maxp')!) view(maxp).setUint16(4, kept.length) tables.set('maxp', maxp) // what the glyphs' instructions use @@ -313,6 +313,8 @@ const FDARRAY = 1236 const FDSELECT = 1237 const UNIQUE_ID = 13 const XUID = 14 +/** the strings every CFF has: a font's own strings are numbered after them */ +const STANDARD_STRINGS = 391 function subsetCff(font: Font, used: Iterable, chars: [number, number][]): FontSubset { const cff = font.tables.get('CFF ')! @@ -376,7 +378,25 @@ function subsetCff(font: Font, used: Iterable, chars: [number, number][] head.bytes(cff.subarray(0, v.getUint8(2))) head.bytes(cff.subarray(v.getUint8(2), names.end)) const tail = new Out() - tail.bytes(cff.subarray(tops.end, gsubrs.end)) + const set = new Map() + if (cid) { + // a CID font's glyphs are renumbered: its CIDs are no longer those of its character collection (Adobe-Japan1…), so + // the subset says Adobe-Identity-0, as the PDF that embeds it does + // (byte by byte: a long string spread into one call is past an engine's limit of arguments) + const list = strings.items.map((b) => { + let s = '' + for (const c of b) s += String.fromCharCode(c) + return s + }) + const sid = (s: string) => { + let i = list.indexOf(s) + if (i < 0) i = list.push(s) - 1 + return STANDARD_STRINGS + i + } + set.set(ROS, [sid('Adobe'), sid('Identity'), 0]) + writeIndex(tail, list.map((s) => Uint8Array.from(s, (c) => c.charCodeAt(0)))) + tail.bytes(cff.subarray(strings.end, gsubrs.end)) + } else tail.bytes(cff.subarray(tops.end, gsubrs.end)) const charset = new Out() // format 0: the name of each glyph kept; a CID font is renumbered, its CIDs are the glyphs of the subset @@ -386,7 +406,6 @@ function subsetCff(font: Font, used: Iterable, chars: [number, number][] const strs = new Out() writeIndex(strs, kept.map((g) => charStrings[g])) - const set = new Map() const drop = new Set([ENCODING, UNIQUE_ID, XUID]) let build: (base: number) => number[] if (cid) { @@ -465,6 +484,19 @@ function subsetCff(font: Font, used: Iterable, chars: [number, number][] return { bytes: writeSfnt(tables, 'cff'), glyphs, outlines: 'cff', cff: table } } +/** PostScript outlines keyed by CID (CJK fonts): their glyphs are not their CIDs, so the whole font cannot stand in for a subset in a PDF */ +export function isCidKeyed(font: Font): boolean { + const cff = font.tables.get('CFF ') + if (font.outlines !== 'cff' || !cff || cff.length < 4) return false + try { + const names = readIndex(cff, view(cff).getUint8(2)) + const tops = readIndex(cff, names.end) + return !!tops.items[0] && readDict(tops.items[0]).some((e) => e.op === ROS) + } catch { + return false + } +} + /** * The font with only the glyphs `used` (and what they are made of), renumbered. `chars`: the characters the subset's * own character map should give (code point, glyph of the font): what a browser needs to draw text in it; a PDF diff --git a/src/core/index.ts b/src/core/index.ts index 57cc627..f3495e8 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -14,6 +14,11 @@ export { PptxPresentation } from './pptx/parser' export type * from './pptx/types' export { Engine } from './worker/engine' export { DocumentClient, setDefaultWorker, type OpenOptions } from './worker/client' -export type { Events, MeasuredText, Methods, OpenResult } from './worker/protocol' +export type { Events, MeasuredText, Methods, OpenResult, PdfExport } from './worker/protocol' +export { writePdf, type PdfOptions } from './pdf/writer' +export { pageToSvg } from './draw/svg' +export { svgItems } from './draw/svg-in' +export { slidePage, type SlideDrawOptions } from './pptx/draw' +export type { Page, DrawItem, Paint, Rgba, Seg, Matrix, StrokeStyle, StdFont, ImageData as DrawImage } from './draw/types' export { threadsOf, newCommentId, type DocComment, type CommentUser, type CommentMention, type CommentAnchor, type CommentThread } from './comments' export { highlight, highlightLines, languageOf, languageOfFile, LANGUAGE_NAME, type Token } from './syntax' diff --git a/src/core/pdf/writer.ts b/src/core/pdf/writer.ts new file mode 100644 index 0000000..89e62be --- /dev/null +++ b/src/core/pdf/writer.ts @@ -0,0 +1,737 @@ +/** + * Pages of drawing commands written as a PDF file: no browser, no dependency. Fonts are embedded as subsets with the + * text of their glyphs (text can be selected, copied and searched), JPEG pictures are copied as they are, PNG and GIF + * ones unpacked and packed again with their transparency, links and an outline from the pages' titles are kept. + * Streams are packed with the runtime's `CompressionStream`. + */ +import type { Font } from '../font/font' +import { isCidKeyed, subsetFont, toUnicodeCMap, type FontSubset } from '../font/subset' +import { decodeGif, decodePng, jpegInfo, sniffImage, type Pixels } from '../draw/image' +import { apply, invert, multiply, IDENTITY } from '../draw/path' +import { glyphTexts } from '../draw/glyphs' +import { isBold, stdChar, stdWidth } from '../draw/stdfont' +import type { DrawItem, ImageData, Matrix, Page, Paint, Rgba, Seg, StdFont, Stop } from '../draw/types' + +export interface PdfOptions { + /** the document's title (the file's metadata) */ + title?: string + author?: string + subject?: string + /** the program that made the document (default "office-engine") */ + producer?: string + /** a bookmark for each page that has a title (default true) */ + outline?: boolean + /** told of what could not be drawn as it is (a picture of a format that is not read, a font that may not be embedded) */ + onWarning?: (text: string) => void +} + +/** px (1/96 in) to points */ +const PT = 0.75 + +/** a PDF number: decimal, never an exponent (past what a page can use, a coordinate is clamped) */ +const n = (v: number): string => { + if (!Number.isFinite(v)) return '0' + const r = Math.round(Math.max(-1e9, Math.min(1e9, v)) * 1000) / 1000 + return r === 0 ? '0' : r.toFixed(3).replace(/\.?0+$/, '') +} + +/** + * A number to six significant digits, never an exponent: the entries of transforms and the places of stops, which + * three decimals would flatten (a scale of 0.00149 written as 0.001) + */ +const nm = (v: number): string => { + if (!Number.isFinite(v) || Math.abs(v) < 1e-12) return '0' + const c = Math.max(-1e9, Math.min(1e9, v)) + const s = c.toFixed(Math.max(0, Math.min(15, 5 - Math.floor(Math.log10(Math.abs(c)))))) + return s.includes('.') ? s.replace(/\.?0+$/, '') : s +} + +/** a matrix as it is written: what is drawn, and the boxes and patterns worked out from it, use the same numbers */ +const written = (m: Matrix): Matrix => m.map((v) => Number(nm(v))) as Matrix + +/** a URI action's address: ASCII only, as the format asks (other characters percent-encoded as UTF-8), escaped */ +// eslint-disable-next-line no-control-regex +const uriString = (url: string) => + '(' + + url + // (half a surrogate pair is no character: it cannot be encoded, and stands for U+FFFD as in a browser) + .replace(/[\ud800-\udbff](?![\udc00-\udfff])|(? encodeURIComponent(c)) + .replace(/[\\()]/g, '\\$&') + + ')' + +/** a PDF text string: ASCII as it is (escaped), anything else as UTF-16 with its byte order mark */ +function pdfString(s: string): string { + // eslint-disable-next-line no-control-regex + if (/^[\x20-\x7e]*$/.test(s)) return '(' + s.replace(/[\\()]/g, '\\$&') + ')' + let hex = 'FEFF' + for (let i = 0; i < s.length; i++) hex += s.charCodeAt(i).toString(16).padStart(4, '0') + return `<${hex}>` +} + +const pdfName = (s: string) => '/' + s.replace(/[^A-Za-z0-9+_.-]/g, (c) => '#' + c.charCodeAt(0).toString(16).padStart(2, '0')) + +async function deflate(data: Uint8Array): Promise { + const stream = new Blob([data as Uint8Array]).stream().pipeThrough(new CompressionStream('deflate') as unknown as TransformStream) + return new Uint8Array(await new Response(stream).arrayBuffer()) +} + +const latin1 = (s: string): Uint8Array => { + const b = new Uint8Array(s.length) + for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i) + return b +} + +interface FontUse { + name: string + /** embedded whole (the license allows no subset): named without a subset's tag */ + whole?: boolean + /** glyph → the text it stands for (the first glyph of a cluster carries it) */ + glyphs: Map + /** the subset, once every page's glyphs are known */ + sub?: FontSubset +} + +interface StdUse { + name: string +} + +/** Writes `pages` as a PDF file. */ +export async function writePdf(pages: Page[], opts: PdfOptions = {}): Promise> { + // (a file of no page is one readers refuse) + if (!pages.length) throw new Error('A PDF file needs at least one page') + const w = new PdfWriter(opts) + return w.write(pages) +} + +class PdfWriter { + private objects: (Uint8Array | undefined)[] = [undefined] + private fonts = new Map() + private std = new Map() + /** fonts that may not be embedded: their text is set in Helvetica */ + private refused = new Set() + private images = new Map() + private alphas = new Map() + private shadings: { name: string; ref: number }[] = [] + private warned = new Set() + + constructor(private opts: PdfOptions) {} + + private warn(text: string) { + if (this.warned.has(text)) return + this.warned.add(text) + this.opts.onWarning?.(text) + } + + /** a new object number */ + private alloc(): number { + this.objects.push(undefined) + return this.objects.length - 1 + } + + private set(ref: number, body: string | Uint8Array) { + this.objects[ref] = typeof body === 'string' ? latin1(body) : body + } + + private async stream(ref: number, dict: string, data: Uint8Array, compress = true) { + const body = compress ? await deflate(data) : data + const head = latin1(`<<${dict}${compress ? '/Filter/FlateDecode' : ''}/Length ${body.length}>>\nstream\n`) + const tail = latin1('\nendstream') + const out = new Uint8Array(head.length + body.length + tail.length) + out.set(head) + out.set(body, head.length) + out.set(tail, head.length + body.length) + this.objects[ref] = out + } + + async write(pages: Page[]): Promise> { + const catalog = this.alloc() + const tree = this.alloc() + // the glyphs every font draws, before any page is written: pages name the subsets' glyphs + for (const p of pages) this.collect(p.items) + for (const [font, use] of this.fonts) { + if (this.refused.has(font)) continue + try { + if (font.fsType & 0x0100) { + // the license allows the whole font only: its glyphs as they are + if (isCidKeyed(font)) throw new Error('it may not be subset, and its glyphs are not its characters') + use.sub = { bytes: font.sfnt(), glyphs: new Map([0, ...use.glyphs.keys()].map((g) => [g, g])), outlines: font.outlines } + use.whole = true + } else use.sub = subsetFont(font, use.glyphs.keys()) + } catch (e) { + // a damaged font (or one that cannot be embedded whole) takes its text to Helvetica, not the file down + this.refused.add(font) + this.warn(`The font ${font.names.family} could not be embedded (${(e as Error).message}): its text is set in Helvetica`) + } + } + const kids: number[] = [] + const outline: { title: string; page: number; h: number }[] = [] + for (const page of pages) { + const ref = this.alloc() + kids.push(ref) + const content = this.alloc() + const W = page.w * PT + const H = page.h * PT + const ctx: Ctx = { ops: [], m: [PT, 0, 0, -PT, 0, H], base: IDENTITY, page: [W, H], links: [], res: new Set() } + ctx.ops.push(`${n(PT)} 0 0 ${n(-PT)} 0 ${n(H)} cm`) + await this.items(page.items, ctx) + await this.stream(content, '', latin1(ctx.ops.join('\n'))) + const annots: number[] = [] + for (const l of ctx.links) { + const a = this.alloc() + this.set(a, `<>>>`) + annots.push(a) + } + this.set(ref, `< `${a} 0 R`).join(' ')}]` : ''}>>`) + if (page.title) outline.push({ title: page.title, page: ref, h: H }) + } + this.set(tree, `< `${k} 0 R`).join(' ')}]/Count ${kids.length}>>`) + await this.writeFonts() + let outlines = '' + if (this.opts.outline !== false && outline.length) { + const root = this.alloc() + const refs = outline.map(() => this.alloc()) + outline.forEach((o, i) => { + const links = `${i ? `/Prev ${refs[i - 1]} 0 R` : ''}${i < refs.length - 1 ? `/Next ${refs[i + 1]} 0 R` : ''}` + this.set(refs[i], `<>`) + }) + this.set(root, `<>`) + outlines = `/Outlines ${root} 0 R/PageMode/UseOutlines` + } + this.set(catalog, `<>`) + const info = this.alloc() + const d = new Date() + const date = `D:${d.getUTCFullYear()}${[d.getUTCMonth() + 1, d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds()].map((v) => String(v).padStart(2, '0')).join('')}Z` + const meta: [string, string | undefined][] = [['Title', this.opts.title], ['Author', this.opts.author], ['Subject', this.opts.subject], ['Producer', this.opts.producer ?? 'office-engine']] + this.set(info, `<<${meta.filter(([, v]) => v).map(([k, v]) => `/${k} ${pdfString(v!)}`).join('')}/CreationDate(${date})>>`) + return this.file(catalog, info) + } + + private file(catalog: number, info: number): Uint8Array { + const head = latin1('%PDF-1.7\n%\xe2\xe3\xcf\xd3\n') + const chunks: Uint8Array[] = [head] + const offsets: number[] = [0] + let at = head.length + for (let i = 1; i < this.objects.length; i++) { + const body = this.objects[i] ?? latin1('null') + const open = latin1(`${i} 0 obj\n`) + const close = latin1('\nendobj\n') + offsets.push(at) + chunks.push(open, body, close) + at += open.length + body.length + close.length + } + let xref = `xref\n0 ${this.objects.length}\n0000000000 65535 f \n` + for (let i = 1; i < offsets.length; i++) xref += `${String(offsets[i]).padStart(10, '0')} 00000 n \n` + xref += `trailer\n<>\nstartxref\n${at}\n%%EOF\n` + chunks.push(latin1(xref)) + let size = 0 + for (const c of chunks) size += c.length + const out = new Uint8Array(size) + size = 0 + for (const c of chunks) out.set(c, size), (size += c.length) + return out + } + + // ---- what the pages use ----------------------------------------------------- + + private collect(items: DrawItem[]) { + for (const it of items) { + if (it.t === 'group') this.collect(it.items) + else if (it.t === 'text' && typeof it.font !== 'string') { + const font = it.font + if (!this.refused.has(font) && (!font.embeddable || font.fsType & 0x0200)) { + this.refused.add(font) + this.warn(`The font ${font.names.family} may not be embedded${font.embeddable ? ' but as bitmaps' : ''}: its text is set in Helvetica`) + } + if (this.refused.has(font)) continue + let use = this.fonts.get(font) + if (!use) this.fonts.set(font, (use = { name: `F${this.fonts.size + this.std.size + 1}`, glyphs: new Map() })) + // the first glyph of a cluster stands for its characters (several for a ligature), the others for none + const texts = glyphTexts(it) + it.glyphs.forEach((g, i) => { + if (!use.glyphs.get(g)) use.glyphs.set(g, texts[i]) + }) + } + } + } + + private resources(res: Set): string { + const fonts: string[] = [] + const xobjects: string[] = [] + const states: string[] = [] + const shadings: string[] = [] + const patterns: string[] = [] + for (const r of res) { + const [kind, name, ref] = r.split(' ') + if (kind === 'F') fonts.push(`/${name} ${ref} 0 R`) + else if (kind === 'X') xobjects.push(`/${name} ${ref} 0 R`) + else if (kind === 'G') states.push(`/${name} ${ref} 0 R`) + else if (kind === 'S') shadings.push(`/${name} ${ref} 0 R`) + else if (kind === 'P') patterns.push(`/${name} ${ref} 0 R`) + } + return `<<${fonts.length ? `/Font<<${fonts.join('')}>>` : ''}${xobjects.length ? `/XObject<<${xobjects.join('')}>>` : ''}${states.length ? `/ExtGState<<${states.join('')}>>` : ''}${shadings.length ? `/Shading<<${shadings.join('')}>>` : ''}${patterns.length ? `/Pattern<<${patterns.join('')}>>` : ''}>>` + } + + private fontRefs = new Map() + private tags = new Set() + private baseNames = new Set() + private forms = 0 + + private fontRef(name: string): number { + let ref = this.fontRefs.get(name) + if (ref === undefined) this.fontRefs.set(name, (ref = this.alloc())) + return ref + } + + private async writeFonts() { + for (const [font, use] of this.fonts) { + const sub = use.sub + if (this.refused.has(font) || !sub) continue + const ref = this.fontRef(use.name) + const upm = font.unitsPerEm + const k = 1000 / upm + // a tag of six capitals from the font and the glyphs kept, as the subsets of one font in two documents differ; + // two subsets of one document never share one + let hash = 0 + for (const c of font.names.postScript + font.names.family) hash = (hash * 31 + c.charCodeAt(0)) >>> 0 + for (const g of [...use.glyphs.keys()].sort((a, b) => a - b)) hash = (hash * 31 + g) >>> 0 + let tag = '' + for (let tries = 0; !tag || this.tags.has(tag); tries++) { + tag = '' + let h = (hash + tries * 7919) >>> 0 + for (let i = 0; i < 6; i++) (tag += String.fromCharCode(65 + (h % 26))), (h = Math.floor(h / 26)) + } + this.tags.add(tag) + // (the name as it is, escaped: two fonts whose names differ only in punctuation keep apart) + const ps = (font.names.postScript || font.names.family || 'Font').replace(/[^\x21-\x7e]/g, '') + let base = use.whole ? ps : `${tag}+${ps}` + // (two fonts of one name, two files of a family that say the same: kept apart, as a reader may share fonts by name) + for (let k = 2; this.baseNames.has(base); k++) base = `${use.whole ? ps : `${tag}+${ps}`}-${k}` + this.baseNames.add(base) + const m = font.metrics + const flags = 4 | (font.fixedPitch ? 1 : 0) | (font.italic ? 64 : 0) + const file = this.alloc() + const cff = font.outlines === 'cff' + await this.stream(file, cff ? '/Subtype/OpenType' : `/Length1 ${sub.bytes.length}`, sub.bytes) + const desc = this.alloc() + this.set( + desc, + `< n(v * k)).join(' ')}]/ItalicAngle ${n(m.italicAngle)}/Ascent ${n(m.ascent * k)}/Descent ${n(-m.descent * k)}/CapHeight ${n((m.capHeight || m.ascent) * k)}/StemV ${font.weight >= 600 ? 120 : 80}/${cff ? 'FontFile3' : 'FontFile2'} ${file} 0 R>>`, + ) + // widths of the subset's glyphs, in order + const widths: [number, number][] = [...sub.glyphs].map(([old, now]) => [now, font.advanceOf(old) * k] as [number, number]).sort((a, b) => a[0] - b[0]) + const W: string[] = [] + for (let i = 0; i < widths.length; ) { + let j = i + while (j + 1 < widths.length && widths[j + 1][0] === widths[j][0] + 1) j++ + W.push(`${widths[i][0]}[${widths.slice(i, j + 1).map(([, v]) => n(v)).join(' ')}]`) + i = j + 1 + } + const cid = this.alloc() + this.set( + cid, + `<>/FontDescriptor ${desc} 0 R/DW ${n(font.advanceOf(0) * k)}/W[${W.join('')}]${cff ? '' : '/CIDToGIDMap/Identity'}>>`, + ) + const toUni = this.alloc() + await this.stream(toUni, '', latin1(unescape(encodeURIComponent(toUnicodeCMap([...use.glyphs].map(([g, text]) => [sub.glyphs.get(g)!, text] as [number, string])))))) + this.set(ref, `<>`) + } + for (const [font, use] of this.std) { + const ref = this.fontRef(use.name) + const bold = isBold(font) + const widths: string[] = [] + for (let c = 32; c <= 255; c++) widths.push(String(stdWidth(c, bold))) + this.set(ref, `<>`) + } + } + + // ---- page content ------------------------------------------------------------- + + private async items(items: DrawItem[], ctx: Ctx) { + for (const it of items) await this.item(it, ctx) + } + + private async item(it: DrawItem, ctx: Ctx) { + switch (it.t) { + case 'path': + return this.path(it, ctx) + case 'text': + return this.text(it, ctx) + case 'image': + return this.image(it, ctx) + case 'link': { + const pts = [apply(ctx.m, it.x, it.y), apply(ctx.m, it.x + it.w, it.y), apply(ctx.m, it.x, it.y + it.h), apply(ctx.m, it.x + it.w, it.y + it.h)] + const xs = pts.map((p) => p[0]) + const ys = pts.map((p) => p[1]) + ctx.links.push({ rect: [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)], url: it.url }) + return + } + case 'group': { + if (!it.items.length) return + if (it.opacity === undefined || it.opacity >= 1) { + ctx.ops.push('q') + await this.groupBody(it, ctx) + ctx.ops.push('Q') + return + } + // a transparent group is drawn whole, then made transparent (an isolated transparency group): its parts do not + // show through one another, as in the viewer + const inner: Ctx = { ops: [], m: ctx.m, base: ctx.m, page: ctx.page, links: ctx.links, res: new Set() } + await this.groupBody(it, inner) + const form = await this.form(inner, '/Group<>') + if (!form) return + const { name, ref } = form + ctx.res.add(`X ${name} ${ref}`) + ctx.ops.push('q') + this.alpha(ctx, it.opacity, it.opacity) + ctx.ops.push(`/${name} Do`, 'Q') + return + } + } + } + + /** a group's transform, clip and items, into `ctx` */ + private async groupBody(it: Extract, ctx: Ctx) { + const saved = ctx.m + if (it.transform) { + const t = written(it.transform) + ctx.ops.push(`${t.map(nm).join(' ')} cm`) + ctx.m = multiply(t, ctx.m) + } + if (it.clip) ctx.ops.push((pathOps(it.clip) || '0 0 m') + (it.clipRule === 'evenodd' ? ' W* n' : ' W n')) + await this.items(it.items, ctx) + ctx.m = saved + } + + /** + * What was drawn into `inner` as a form XObject, its box the page in the form's space (what is off the page is not + * seen anyway); null when that space is flattened to nothing + */ + private async form(inner: Ctx, extra: string): Promise<{ name: string; ref: number } | null> { + const back = invert(inner.base) + if (!back) return null + const [W, H] = inner.page + const pts = [apply(back, 0, 0), apply(back, W, 0), apply(back, 0, H), apply(back, W, H)] + const xs = pts.map((p) => p[0]) + const ys = pts.map((p) => p[1]) + const box = [Math.min(...xs) - 1, Math.min(...ys) - 1, Math.max(...xs) + 1, Math.max(...ys) + 1] + const ref = this.alloc() + const name = `Fm${++this.forms}` + await this.stream(ref, `/Type/XObject/Subtype/Form/BBox[${box.map(n).join(' ')}]${extra}/Resources ${this.resources(inner.res)}`, latin1(inner.ops.join('\n'))) + return { name, ref } + } + + /** an ExtGState for these alphas, made current */ + private alpha(ctx: Ctx, fill: number, stroke: number) { + const key = `${n(fill)} ${n(stroke)}` + let name = this.alphas.get(key) + let ref: number + if (!name) { + name = `G${this.alphas.size + 1}` + ref = this.alloc() + this.set(ref, `<>`) + this.alphas.set(key, name) + this.alphaRefs.set(name, ref) + } else ref = this.alphaRefs.get(name)! + ctx.res.add(`G ${name} ${ref}`) + ctx.ops.push(`/${name} gs`) + } + + private alphaRefs = new Map() + + /** a shading object of the gradient's colors, or (`alpha`) of its stops' alphas as gray */ + private shadingObject(p: Exclude, alpha: boolean): number { + const ref = this.alloc() + const coords = p.t === 'linear' ? [p.x0, p.y0, p.x1, p.y1] : [p.fx, p.fy, 0, p.cx, p.cy, p.r] + const fn = stopsFunction(p.stops, alpha ? (c) => n(c.a) : rgb) + this.set(ref, `<>`) + return ref + } + + /** the gradient as a shading of the content stream (`sh`) */ + private shading(ctx: Ctx, p: Exclude, alpha = false): string { + const ref = this.shadingObject(p, alpha) + const name = `Sh${this.shadings.length + 1}` + this.shadings.push({ name, ref }) + ctx.res.add(`S ${name} ${ref}`) + return name + } + + /** the gradient as a shading pattern, to stroke with: placed in the current space, as the shading of `sh` is */ + private pattern(ctx: Ctx, p: Exclude): string | null { + const back = invert(ctx.base) + if (!back) return null + const ref = this.alloc() + this.set(ref, `<>`) + const name = `P${++this.patterns}` + ctx.res.add(`P ${name} ${ref}`) + return name + } + + private patterns = 0 + + /** the gradient's alphas as a soft mask, made current: a mask of the same shading in gray */ + private async gradientMask(ctx: Ctx, p: Exclude, clip: string) { + const inner: Ctx = { ops: [], m: ctx.m, base: ctx.m, page: ctx.page, links: [], res: new Set() } + const sh = this.shading(inner, p, true) + if (clip) inner.ops.push(clip) + inner.ops.push(`/${sh} sh`) + const form = await this.form(inner, '/Group<>') + if (!form) return + const gs = this.alloc() + this.set(gs, `<>>>`) + // (a name of their own: the alphas' are G1, G2…) + const name = `M${++this.masks}` + ctx.res.add(`G ${name} ${gs}`) + ctx.ops.push(`/${name} gs`) + } + + private masks = 0 + + private async path(it: Extract, ctx: Ctx) { + if (!it.d.length) return + const ops = pathOps(it.d) + const evenodd = it.rule === 'evenodd' + const fill = it.fill && settled(it.fill) + const stroke = it.stroke && it.stroke.width > 0 ? { ...it.stroke, paint: settled(it.stroke.paint) } : undefined + if (fill && fill.t !== 'color') { + // a gradient: the path clips, the shading paints + const name = this.shading(ctx, fill) + const clip = ops + (evenodd ? ' W* n' : ' W n') + ctx.ops.push('q', clip) + const alphas = fill.stops.map((s) => s.color.a) + if (alphas.some((a) => a !== alphas[0])) await this.gradientMask(ctx, fill, clip) + else if (alphas[0] < 1) this.alpha(ctx, alphas[0], 1) + ctx.ops.push(`/${name} sh`, 'Q') + } + const solid = fill?.t === 'color' && fill.color.a > 0 ? fill.color : undefined + const sp = stroke && !(stroke.paint.t === 'color' && stroke.paint.color.a <= 0) ? stroke.paint : undefined + // a color fill and a color outline are painted together (B): where they overlap, the outline is not over the fill + const together = solid && sp?.t === 'color' + if (solid && !together) { + ctx.ops.push('q') + if (solid.a < 1) this.alpha(ctx, solid.a, 1) + ctx.ops.push(`${rgb(solid)} rg`, ops + (evenodd ? ' f*' : ' f'), 'Q') + } + if (!stroke || !sp) return + ctx.ops.push('q') + if (sp.t === 'color') { + if (sp.color.a < 1 || (together && solid.a < 1)) this.alpha(ctx, together ? solid.a : 1, sp.color.a) + if (together) ctx.ops.push(`${rgb(solid)} rg`) + ctx.ops.push(`${rgb(sp.color)} RG`) + } else { + // a gradient along the line: a shading pattern, its alphas a soft mask where they change + const name = this.pattern(ctx, sp) + if (!name) return void ctx.ops.push('Q') + const alphas = sp.stops.map((s) => s.color.a) + if (alphas.some((a) => a !== alphas[0])) await this.gradientMask(ctx, sp, '') + else if (alphas[0] < 1) this.alpha(ctx, 1, alphas[0]) + ctx.ops.push(`/Pattern CS /${name} SCN`) + } + ctx.ops.push(`${n(stroke.width)} w`) + if (stroke.dash?.length) ctx.ops.push(`[${stroke.dash.map(n).join(' ')}] 0 d`) + ctx.ops.push(`${{ butt: 0, round: 1, square: 2 }[stroke.cap ?? 'butt']} J`, `${{ miter: 0, round: 1, bevel: 2 }[stroke.join ?? 'miter']} j`, ops + (together ? (evenodd ? ' B*' : ' B') : ' S'), 'Q') + } + + private text(it: Extract, ctx: Ctx) { + if (!it.glyphs.length || it.fill.a <= 0) return + if (typeof it.font !== 'string' && this.refused.has(it.font)) return this.stdText(asStd(it), ctx) + if (typeof it.font === 'string') return this.stdText(it as StdText, ctx) + const use = this.fonts.get(it.font)! + const ref = this.fontRef(use.name) + ctx.res.add(`F ${use.name} ${ref}`) + const font = it.font + const k = it.size / font.unitsPerEm + // a glyph stands for one text in the whole file: where this text has it stand for another (a ligature of the font + // and the one character U+FB01), the text is given as it is + const texts = glyphTexts(it) + const actual = it.glyphs.some((g, i) => use.glyphs.get(g) !== texts[i]) + if (actual) ctx.ops.push(`/Span<>BDC`) + this.glyphText(it, ctx, use.name, (g) => (use.sub!.glyphs.get(g) ?? 0).toString(16).padStart(4, '0'), (g) => font.advanceOf(g) * k) + if (actual) ctx.ops.push('EMC') + } + + private stdText(it: StdText, ctx: Ctx) { + let use = this.std.get(it.font) + if (!use) this.std.set(it.font, (use = { name: `F${this.fonts.size + this.std.size + 1}` })) + ctx.res.add(`F ${use.name} ${this.fontRef(use.name)}`) + const bold = isBold(it.font) + this.glyphText(it, ctx, use.name, (g) => g.toString(16).padStart(2, '0'), (g) => (stdWidth(g, bold) * it.size) / 1000) + } + + /** the glyphs as one TJ, each moved from where the font's width puts it to where the layout did */ + private glyphText(it: Extract, ctx: Ctx, font: string, code: (g: number) => string, width: (g: number) => number) { + const ops = ctx.ops + ops.push('q') + if (it.fill.a < 1) this.alpha(ctx, it.fill.a, it.fill.a) + ops.push(`${rgb(it.fill)} rg`) + const syn = it.synthetic + if (syn?.bold) ops.push(`${rgb(it.fill)} RG`, `${n(it.size * 0.03)} w`, '2 Tr') + const skew = syn?.italic ? 0.21 : 0 + ops.push('BT', `/${font} ${n(it.size)} Tf`) + const placed = it.dx?.some((v) => v) || it.dy?.some((v) => v) + if (placed) { + // glyphs moved off the pen: each at its own place + let x = it.x + it.glyphs.forEach((g, i) => { + ops.push(`1 0 ${n(skew)} -1 ${n(x + (it.dx?.[i] ?? 0))} ${n(it.y - (it.dy?.[i] ?? 0))} Tm <${code(g)}> Tj`) + x += it.advances[i] + }) + } else { + ops.push(`1 0 ${n(skew)} -1 ${n(it.x)} ${n(it.y)} Tm`) + let tj = '' + let run = '' + it.glyphs.forEach((g, i) => { + run += code(g) + const off = it.advances[i] - width(g) + if (Math.abs(off) > 1e-3 && i < it.glyphs.length - 1) { + tj += `<${run}>${n((-off * 1000) / it.size)}` + run = '' + } + }) + if (run) tj += `<${run}>` + ops.push(`[${tj}] TJ`) + } + ops.push('ET', 'Q') + } + + private async image(it: Extract, ctx: Ctx) { + if (it.w <= 0 || it.h <= 0) return + const xo = await this.xobject(it.image) + if (!xo) return + ctx.res.add(`X ${xo.name} ${xo.ref}`) + ctx.ops.push('q') + if (it.opacity !== undefined && it.opacity < 1) this.alpha(ctx, it.opacity, it.opacity) + ctx.ops.push(`${nm(it.w)} 0 0 ${nm(-it.h)} ${nm(it.x)} ${nm(it.y + it.h)} cm`, `/${xo.name} Do`, 'Q') + } + + private async xobject(img: ImageData): Promise<{ name: string; ref: number } | null> { + const key = img.key ?? img.bytes + const known = this.images.get(key) + if (known !== undefined) return known + let out: { name: string; ref: number } | null = null + const kind = sniffImage(img.bytes) + try { + if (kind === 'jpeg') { + const info = jpegInfo(img.bytes) + if (info) { + const ref = this.alloc() + const cs = info.components === 1 ? 'DeviceGray' : info.components === 4 ? 'DeviceCMYK' : 'DeviceRGB' + const decode = info.components === 4 && info.adobe ? '/Decode[1 0 1 0 1 0 1 0]' : '' + await this.stream(ref, `/Type/XObject/Subtype/Image/Width ${info.w}/Height ${info.h}/ColorSpace/${cs}/BitsPerComponent 8${decode}/Filter/DCTDecode`, img.bytes, false) + // (DCTDecode named in the dictionary: the bytes are the JPEG as it is) + out = { name: `Im${this.images.size + 1}`, ref } + } + } else if (kind === 'png' || kind === 'gif') { + const px = kind === 'png' ? await decodePng(img.bytes) : decodeGif(img.bytes) + out = { name: `Im${this.images.size + 1}`, ref: await this.pixels(px) } + } + } catch (e) { + this.warn(`A picture could not be read: ${(e as Error).message}`) + } + if (!out && kind !== 'png' && kind !== 'jpeg' && kind !== 'gif') this.warn(`Pictures in ${(kind ?? 'an unknown format').toUpperCase()} are not drawn in a PDF yet`) + this.images.set(key, out) + return out + } + + private async pixels(px: Pixels): Promise { + const ref = this.alloc() + let smask = '' + if (px.alpha) { + const s = this.alloc() + await this.stream(s, `/Type/XObject/Subtype/Image/Width ${px.w}/Height ${px.h}/ColorSpace/DeviceGray/BitsPerComponent 8`, px.alpha) + smask = `/SMask ${s} 0 R` + } + await this.stream(ref, `/Type/XObject/Subtype/Image/Width ${px.w}/Height ${px.h}/ColorSpace/${px.channels === 1 ? 'DeviceGray' : 'DeviceRGB'}/BitsPerComponent 8${smask}`, px.color) + return ref + } +} + +type StdText = Extract & { font: StdFont } + +interface Ctx { + ops: string[] + /** user space to PDF space, for links */ + m: Matrix + /** the content stream's own space to PDF space: the page's is the identity, a form's the space it is drawn in */ + base: Matrix + /** the page's size in points: what a form's box must hold */ + page: [number, number] + links: { rect: number[]; url: string }[] + /** resources the page uses: "F name ref", "X name ref"… */ + res: Set +} + +/** text of a font that may not be embedded, set in Helvetica: each cluster's characters where its glyphs were */ +function asStd(it: Extract): StdText { + const font = it.font as Font + const std = font.weight >= 600 ? (font.italic ? 'Helvetica-BoldOblique' : 'Helvetica-Bold') : font.italic ? 'Helvetica-Oblique' : 'Helvetica' + const bold = isBold(std) + const glyphs: number[] = [] + const advances: number[] = [] + const clusters: number[] = [] + const texts = glyphTexts(it) + // each cluster as wide as its glyphs together + const widths = new Map() + it.clusters.forEach((c, k) => widths.set(c, (widths.get(c) ?? 0) + it.advances[k])) + it.glyphs.forEach((_, i) => { + const from = it.clusters[i] ?? 0 + if (!texts[i]) return + // its last character takes up what its others do not; a tab is pen movement: a space, whose width is the layout's + let width = widths.get(from) ?? 0 + const chars = [...texts[i].replace(/\t/g, ' ')] + chars.forEach((ch, k) => { + const code = stdCodeOf(ch) + const w = k < chars.length - 1 ? (stdWidth(code, bold) * it.size) / 1000 : width + glyphs.push(code) + advances.push(w) + clusters.push(from) + width -= w + }) + }) + return { ...it, font: std, glyphs, advances, clusters, dx: undefined, dy: undefined, synthetic: undefined } +} + +function stdCodeOf(ch: string): number { + const cp = ch.codePointAt(0)! + for (let c = 32; c < 256; c++) if (stdChar(c).codePointAt(0) === cp) return c + return 0x3f +} + +function pathOps(d: Seg[]): string { + const out: string[] = [] + for (const s of d) { + if (s.k === 'M') out.push(`${n(s.x)} ${n(s.y)} m`) + else if (s.k === 'L') out.push(`${n(s.x)} ${n(s.y)} l`) + else if (s.k === 'C') out.push(`${n(s.x1)} ${n(s.y1)} ${n(s.x2)} ${n(s.y2)} ${n(s.x)} ${n(s.y)} c`) + else out.push('h') + } + return out.join(' ') +} + +const rgb = (c: Rgba) => `${n(c.r / 255)} ${n(c.g / 255)} ${n(c.b / 255)}` + +/** a gradient of no length (its two points at one place, a circle of no radius) paints its last stop's color, as SVG says */ +function settled(p: Paint): Paint { + if (p.t === 'color') return p + const flat = p.t === 'linear' ? p.x0 === p.x1 && p.y0 === p.y1 : !(p.r > 0) + const last = [...p.stops].sort((a, b) => a.at - b.at).pop() + return flat || !last ? { t: 'color', color: last?.color ?? { r: 0, g: 0, b: 0, a: 0 } } : p +} + +/** + * A function from 0-1 to the stops' colors (`color` writes one): an interpolation between two, a stitching of them for + * more. Two stops at one place make a hard edge: the interval between them, of no width, is left out. + */ +function stopsFunction(stops: Stop[], color: (c: Rgba) => string): string { + // (places as they are written: stops that round to one place make one hard edge, not an interval of no width) + const s = (stops.length ? [...stops] : [{ at: 0, color: { r: 0, g: 0, b: 0, a: 1 } }]).map((x) => ({ ...x, at: Number(nm(Math.min(1, Math.max(0, x.at)))) })).sort((a, b) => a.at - b.at) + if (s[0].at > 0) s.unshift({ at: 0, color: s[0].color }) + if (s[s.length - 1].at < 1) s.push({ at: 1, color: s[s.length - 1].color }) + const lerp = (a: Rgba, b: Rgba) => `<>` + const parts: { from: number; fn: string }[] = [] + for (let i = 0; i < s.length - 1; i++) if (s[i + 1].at > s[i].at) parts.push({ from: s[i].at, fn: lerp(s[i].color, s[i + 1].color) }) + if (!parts.length) return lerp(s[s.length - 1].color, s[s.length - 1].color) + if (parts.length === 1) return parts[0].fn + return `< p.fn).join('')}]/Bounds[${parts.slice(1).map((p) => nm(p.from)).join(' ')}]/Encode[${parts.map(() => '0 1').join(' ')}]>>` +} diff --git a/src/core/pptx/draw.ts b/src/core/pptx/draw.ts new file mode 100644 index 0000000..66e97f3 --- /dev/null +++ b/src/core/pptx/draw.ts @@ -0,0 +1,364 @@ +/** + * A slide as a page of drawing commands (#46): shapes, pictures, tables and text placed as the viewer places them + * (`SlideView`), text laid out in the host's font files. A PDF or SVG backend paints the page. + */ +import type { FontBook } from '../font/book' +import { ellipsePath, multiply, parseColor, parsePath, rectPath, rotate, roundRectPath, translate, IDENTITY } from '../draw/path' +import { sniffImage } from '../draw/image' +import { svgItems } from '../draw/svg-in' +import { layoutParagraphs, type ParaSpec, type RunStyle } from '../draw/text' +import { renderChart } from '../xlsx/chart-svg' +import type { DrawItem, ImageData, Matrix, Page, Paint, Rgba, Seg, StrokeStyle } from '../draw/types' +import { safeHref } from '../url' +import { geomPath, LINE_GEOMS } from './geometry' +import type { Box, Fill, SlideEl, SlideModel, Stroke, TCell, TextBody } from './types' + +export interface SlideDrawOptions { + /** the host's font files */ + fonts: FontBook + /** a part's bytes (pictures), by its name in the package */ + part: (name: string) => Promise + /** the font of text that names none (default Calibri, as PowerPoint's default theme) */ + defaultFont?: string + onWarning?: (text: string) => void +} + +const PT = 96 / 72 +const BLACK: Rgba = { r: 0, g: 0, b: 0, a: 1 } +const WHITE: Rgba = { r: 255, g: 255, b: 255, a: 1 } + +/** Lays out one slide as a page. */ +export async function slidePage(slide: SlideModel, opts: SlideDrawOptions): Promise { + const d = new SlideDrawer(opts) + const items: DrawItem[] = [] + const all = rectPath(0, 0, slide.w, slide.h) + // the page is white under a background that lets it through + items.push({ t: 'path', d: all, fill: { t: 'color', color: WHITE } }) + if (slide.bg) items.push(...(await d.fill(slide.bg, all, { x: 0, y: 0, w: slide.w, h: slide.h }))) + for (const el of slide.els) items.push(...(await d.element(el))) + return { w: slide.w, h: slide.h, items: [{ t: 'group', clip: all, items }], ...(slide.title ? { title: slide.title } : {}) } +} + +class SlideDrawer { + private images = new Map>() + + constructor(private opts: SlideDrawOptions) {} + + private warn(text: string) { + this.opts.onWarning?.(text) + } + + async element(el: SlideEl): Promise { + switch (el.t) { + case 'shape': + return this.shape(el) + case 'pic': + return this.picture(el) + case 'table': + return this.table(el) + case 'chart': { + // the viewer's chart picture, read back as drawing commands + const w = Math.max(1, Math.round(el.box.w)) + const h = Math.max(1, Math.round(el.box.h)) + try { + const items = await svgItems(renderChart(el.model, w, h), this.opts.fonts, { width: el.box.w, height: el.box.h, onMissing: (f) => this.missing(f) }) + return [{ t: 'group', transform: boxMatrix(el.box), items }] + } catch (e) { + this.warn(`A chart could not be drawn: ${(e as Error).message}`) + return [] + } + } + case 'placeholder': + this.warn(`${el.label} is not drawn in a PDF`) + return [] + } + } + + private image(target: string): Promise { + let p = this.images.get(target) + if (!p) { + p = Promise.resolve() + .then(() => this.opts.part(target)) + .then( + (bytes) => { + if (!bytes) return null + const kind = sniffImage(bytes) + return { bytes, type: kind ? `image/${kind === 'svg' ? 'svg+xml' : kind}` : 'application/octet-stream', key: target } + }, + // a part that cannot be read leaves its picture out, not the slide + (e: unknown) => { + this.warn(`A picture could not be read: ${reason(e)}`) + return null + }, + ) + this.images.set(target, p) + } + return p + } + + /** a picture stretched over a box: SVG pictures as drawing commands, others as they are */ + private async picItem(image: ImageData, x: number, y: number, w: number, h: number): Promise { + if (image.type === 'image/svg+xml') { + try { + const items = await svgItems(new TextDecoder().decode(image.bytes), this.opts.fonts, { width: w, height: h, onMissing: (f) => this.missing(f) }) + return { t: 'group', transform: translate(x, y), items } + } catch (e) { + this.warn(`An SVG picture could not be drawn: ${(e as Error).message}`) + return { t: 'group', items: [] } + } + } + return { t: 'image', image, x, y, w, h } + } + + /** a fill painted inside `clip`, `box` the area a picture or gradient spans */ + async fill(fill: Fill, clip: Seg[], box: { x: number; y: number; w: number; h: number }, rule?: 'evenodd'): Promise { + if (fill.t === 'solid') { + const c = parseColor(fill.c) + return c ? [{ t: 'path', d: clip, fill: { t: 'color', color: c }, ...(rule ? { rule } : {}) }] : [] + } + if (fill.t === 'grad') { + const paint = gradient(fill.css, box) + return paint ? [{ t: 'path', d: clip, fill: paint, ...(rule ? { rule } : {}) }] : [] + } + if (fill.t === 'img') { + const image = await this.image(fill.target) + if (!image) return [] + // (a tiled picture is stretched: tiles are not drawn yet) + return [{ t: 'group', clip, ...(rule ? { clipRule: rule } : {}), items: [await this.picItem(image, box.x, box.y, box.w, box.h)] }] + } + return [] + } + + private async shape(el: Extract): Promise { + const { box } = el + const items: DrawItem[] = [] + const isLine = LINE_GEOMS.has(el.geom) + const d = parsePath(el.path ?? geomPath(el.geom, box.w, box.h, el.adj)) + // the outline flips with the shape, its text does not + const flip: Matrix = [box.flipH ? -1 : 1, 0, 0, box.flipV ? -1 : 1, box.flipH ? box.w : 0, box.flipV ? box.h : 0] + const shapeItems: DrawItem[] = [] + if (!isLine && el.fill) shapeItems.push(...(await this.fill(el.fill, d, { x: 0, y: 0, w: box.w, h: box.h }, 'evenodd'))) + if (el.stroke) shapeItems.push(...strokeItems(d, el.stroke)) + if (shapeItems.length) items.push(box.flipH || box.flipV ? { t: 'group', transform: flip, items: shapeItems } : { t: 'group', items: shapeItems }) + if (el.text) items.push(...(await this.text(el.text, box.w, box.h))) + return [{ t: 'group', transform: boxMatrix(box), items }] + } + + private async picture(el: Extract): Promise { + const { box } = el + const image = el.target ? await this.image(el.target) : null + const items: DrawItem[] = [] + const clip = el.geom === 'ellipse' ? ellipsePath(box.w / 2, box.h / 2, box.w / 2, box.h / 2) : el.geom === 'roundRect' ? roundRectPath(0, 0, box.w, box.h, Math.min(box.w, box.h) * 0.1667) : rectPath(0, 0, box.w, box.h) + if (image) { + if (!/^image\/(png|jpeg|gif|svg\+xml)$/.test(image.type)) this.warn(`Pictures in ${image.type.replace(/^image\//, '').toUpperCase()} are not drawn in a PDF yet`) + let x = 0 + let y = 0 + let w = box.w + let h = box.h + if (el.crop) { + const [l, t, r, b] = el.crop + w = box.w / Math.max(0.01, 1 - l - r) + h = box.h / Math.max(0.01, 1 - t - b) + x = -l * w + y = -t * h + } + let pic: DrawItem = await this.picItem(image, x, y, w, h) + // the cropped picture flipped in its frame, as PowerPoint flips it (about the frame's centre, not the picture's) + if (box.flipH || box.flipV) pic = { t: 'group', transform: [box.flipH ? -1 : 1, 0, 0, box.flipV ? -1 : 1, box.flipH ? box.w : 0, box.flipV ? box.h : 0], items: [pic] } + items.push({ t: 'group', clip, items: [pic] }) + } + if (el.stroke) { + // a CSS outline: around the box, outside it + const s = el.stroke + const c = parseColor(s.c) + if (c) items.push({ t: 'path', d: rectPath(-s.w / 2, -s.w / 2, box.w + s.w, box.h + s.w), stroke: { paint: { t: 'color', color: c }, width: s.w } }) + } + return [{ t: 'group', transform: boxMatrix(box), items }] + } + + private async table(el: Extract): Promise { + const { cols, rows } = el + const xs = [0] + for (const w of cols) xs.push(xs[xs.length - 1] + w) + const right = (ci: number, n: number) => xs[Math.min(cols.length, ci + Math.max(1, n))] ?? xs[xs.length - 1] + // each cell's text laid out first: rows grow to their text, as a table's rows do in the viewer + const heights = rows.map((r) => r.h) + const laid = new Map() + for (let ri = 0; ri < rows.length; ri++) { + for (let ci = 0; ci < rows[ri].cells.length; ci++) { + const cell = rows[ri].cells[ci] + const t = cell.text + if (cell.hidden || !t || t.empty) continue + const w = right(ci, cell.colSpan) - (xs[ci] ?? 0) + const out = await layoutParagraphs(this.opts.fonts, t.paras.map((p) => this.para(p)), Math.max(0, w - t.ins[0] - t.ins[2]), { wrap: t.wrap, onMissing: (f) => this.missing(f) }) + laid.set(cell, out.items) + if (cell.rowSpan <= 1) heights[ri] = Math.max(heights[ri], out.height + t.ins[1] + t.ins[3]) + } + } + const ys = [0] + for (const h of heights) ys.push(ys[ys.length - 1] + h) + const fills: DrawItem[] = [] + const texts: DrawItem[] = [] + const borders: DrawItem[] = [] + const edge = (s: Stroke | undefined, x0: number, y0: number, x1: number, y1: number) => { + const c = s && parseColor(s.c) + if (s && c) borders.push({ t: 'path', d: [{ k: 'M', x: x0, y: y0 }, { k: 'L', x: x1, y: y1 }], stroke: { paint: { t: 'color', color: c }, width: Math.max(1, s.w) } }) + } + for (let ri = 0; ri < rows.length; ri++) { + for (let ci = 0; ci < rows[ri].cells.length; ci++) { + const cell = rows[ri].cells[ci] + if (cell.hidden) continue + const x = xs[ci] ?? 0 + const y = ys[ri] + const w = right(ci, cell.colSpan) - x + const h = ys[Math.min(rows.length, ri + Math.max(1, cell.rowSpan))] - y + if (cell.fill) fills.push(...(await this.fill(cell.fill, rectPath(x, y, w, h), { x, y, w, h }))) + const items = laid.get(cell) + // (cells are anchored at the top in the viewer) + if (items && cell.text) texts.push({ t: 'group', transform: translate(x + cell.text.ins[0], y + cell.text.ins[1]), items }) + edge(cell.bt, x, y, x + w, y) + edge(cell.bb, x, y + h, x + w, y + h) + edge(cell.bl, x, y, x, y + h) + edge(cell.br, x + w, y, x + w, y + h) + } + } + return [{ t: 'group', transform: boxMatrix(el.box), items: [...fills, ...texts, ...borders] }] + } + + private missed = new Set() + + private missing(font: string) { + const name = font.replace(/^"([^"]*)".*$/, '$1').split(',')[0].trim() + if (this.missed.has(name)) return + this.missed.add(name) + this.warn(`No font file for ${name}: its text is set in Helvetica`) + } + + private para(p: TextBody['paras'][number]): ParaSpec { + const font = this.opts.defaultFont ?? '"Calibri", Carlito, sans-serif' + const style = (r: { sz: number; b?: boolean; i?: boolean; u?: boolean; strike?: boolean; color?: string; font?: string; baseline?: number; caps?: boolean; href?: string; hl?: string }): RunStyle => ({ + font: r.font ?? font, + size: r.sz * PT, + ...(r.b ? { bold: true } : {}), + ...(r.i ? { italic: true } : {}), + color: parseColor(r.color) ?? BLACK, + ...(r.u ? { underline: true } : {}), + ...(r.strike ? { strike: true } : {}), + ...(r.baseline ? { baseline: r.baseline } : {}), + ...(r.caps ? { caps: true } : {}), + ...(safeHref(r.href) ? { href: safeHref(r.href)! } : {}), + ...(parseColor(r.hl) ? { highlight: parseColor(r.hl)! } : {}), + }) + return { + runs: p.runs.map((r) => ({ text: r.br ? '' : r.text, style: style(r), ...(r.br ? { br: true } : {}) })), + align: p.algn, + marL: p.marL, + indent: p.indent, + ...(p.lnPx ? { linePx: p.lnPx } : { lineMult: (p.lnPct ?? 1) * 1.2 }), + before: p.spcBef, + after: p.spcAft, + ...(p.bullet ? { bullet: { text: p.bullet.text, style: { font: p.bullet.font ?? p.runs[0]?.font ?? font, size: p.bullet.sz * PT, color: parseColor(p.bullet.color) ?? parseColor(p.runs[0]?.color) ?? BLACK } } } : {}), + emptySize: p.endSz * PT, + } + } + + /** a shape's text in its box (box-local px): insets, vertical anchor, vertical text turned */ + private async text(t: TextBody, w: number, h: number): Promise { + if (t.empty) return [] + const [l, top, r, b] = t.ins + const vertical = t.vert === 'vert' || t.vert === 'eaVert' || t.vert === 'vert270' || t.vert === 'mongolianVert' || t.vert === 'wordArtVertRtl' + // vertical text is laid out across the box's height, then turned + const bw = vertical ? h : w + const bh = vertical ? w : h + const out = await layoutParagraphs(this.opts.fonts, t.paras.map((p) => this.para(p)), Math.max(0, bw - l - r), { wrap: t.wrap, onMissing: (f) => this.missing(f) }) + const room = bh - top - b + const dy = t.anchor === 'ctr' ? (room - out.height) / 2 : t.anchor === 'b' ? room - out.height : 0 + let m: Matrix = translate(l, top + dy) + if (vertical) m = multiply(m, t.vert === 'vert270' ? [0, -1, 1, 0, 0, h] : [0, 1, -1, 0, w, 0]) + return [{ t: 'group', transform: m, items: out.items }] + } +} + +/** what went wrong, in words, whatever was thrown (an object with no way to be a string included) */ +function reason(e: unknown): string { + if (e instanceof Error) return e.message + try { + return String(e) + } catch { + return 'an error' + } +} + +/** box-local px to slide px: the box's place, turned about its centre */ +function boxMatrix(b: Box): Matrix { + let m: Matrix = IDENTITY + if (b.rot) m = rotate(b.rot, b.w / 2, b.h / 2) + return multiply(m, translate(b.x, b.y)) +} + +/** `linear-gradient(Adeg, c p%, …)` / `radial-gradient(circle, …)` as the engine writes them, over `box` as CSS spans them */ +export function gradient(css: string, box: { x: number; y: number; w: number; h: number }): Paint | null { + const stops: { at: number; color: Rgba }[] = [] + const re = /(#[0-9a-f]{3,8}|rgba?\([^)]*\))\s*(-?[\d.]+)?%?/gi + const body = css.replace(/^[a-z-]+\(\s*(?:-?[\d.]+deg|circle)\s*,/i, '') + for (let m = re.exec(body); m; m = re.exec(body)) { + const color = parseColor(m[1]) + if (color) stops.push({ at: m[2] !== undefined ? Number(m[2]) / 100 : NaN, color }) + } + if (!stops.length) return null + // stops without a place are spread between their neighbours, as CSS spreads them + stops.forEach((s, i) => { + if (Number.isNaN(s.at)) s.at = stops.length === 1 ? 0 : i / (stops.length - 1) + }) + const cx = box.x + box.w / 2 + const cy = box.y + box.h / 2 + if (/^radial/i.test(css)) { + const r = Math.hypot(box.w, box.h) / 2 + return { t: 'radial', cx, cy, r, fx: cx, fy: cy, stops } + } + const deg = Number(/(-?[\d.]+)deg/.exec(css)?.[1] ?? 180) + const a = (deg * Math.PI) / 180 + // CSS: 0deg points up, 90deg right; the line is as long as the box is across in that direction + const dx = Math.sin(a) + const dy = -Math.cos(a) + const half = (Math.abs(box.w * dx) + Math.abs(box.h * dy)) / 2 + return { t: 'linear', x0: cx - dx * half, y0: cy - dy * half, x1: cx + dx * half, y1: cy + dy * half, stops } +} + +/** a line's dash pattern as the model writes it ("4 3", px) */ +const dashOf = (s: string | undefined) => (s ? s.split(/[\s,]+/).map(Number).filter((v) => Number.isFinite(v) && v >= 0) : undefined) + +/** a shape's outline, with its arrowheads */ +function strokeItems(d: Seg[], s: Stroke): DrawItem[] { + const c = parseColor(s.c) + if (!c) return [] + const stroke: StrokeStyle = { paint: { t: 'color', color: c }, width: s.w, join: 'round' } + const dash = dashOf(s.dash) + if (dash?.length && dash.some((v) => v > 0)) stroke.dash = dash + const items: DrawItem[] = [{ t: 'path', d, stroke }] + // the viewer's markers: a triangle four line widths long, centred on the end, along the line + const head = (tip: { x: number; y: number }, from: { x: number; y: number }) => { + const len = Math.hypot(tip.x - from.x, tip.y - from.y) + if (!len) return + const ux = (tip.x - from.x) / len + const uy = (tip.y - from.y) / len + const size = 4 * s.w + // refX 5 of a 10-wide marker: the triangle's middle is on the end + const bx = tip.x - ux * size * 0.5 + const by = tip.y - uy * size * 0.5 + const pt = { x: bx + ux * size, y: by + uy * size } + const l = { x: bx - uy * size * 0.5, y: by + ux * size * 0.5 } + const r = { x: bx + uy * size * 0.5, y: by - ux * size * 0.5 } + items.push({ t: 'path', d: [{ k: 'M', ...l }, { k: 'L', ...pt }, { k: 'L', ...r }, { k: 'Z' }], fill: { t: 'color', color: c } }) + } + const pts = d.filter((x): x is Exclude => x.k !== 'Z') + if (pts.length >= 2) { + const last = pts[pts.length - 1] + const before = last.k === 'C' ? { x: last.x2, y: last.y2 } : pts[pts.length - 2] + const first = pts[0] + const second = pts[1].k === 'C' ? { x: pts[1].x1, y: pts[1].y1 } : pts[1] + if (s.tail) head(last, before) + if (s.head) head(first, second) + } + return items +} diff --git a/src/react/pptx/geometry.ts b/src/core/pptx/geometry.ts similarity index 100% rename from src/react/pptx/geometry.ts rename to src/core/pptx/geometry.ts diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts index 34c800c..1dc5b55 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -22,11 +22,16 @@ import { XlsxCollabWorker } from '../../collab/xlsx-worker' import type { XOp } from '../../collab/xlsx-ops' import { PptxCollabWorker } from '../../collab/pptx-worker' import type { POp } from '../../collab/pptx-ops' -import type { Events, MeasuredText, Methods, OpenParams, OpenResult } from './protocol' +import type { Events, MeasuredText, Methods, OpenParams, OpenResult, PdfExport } from './protocol' import type { FontSource } from '../fonts' import { FontBook, type TextSpec } from '../font/book' import type { Shaper } from '../font/text' import { checkedComment, type CommentStore } from '../comments' +import { slidePage } from '../pptx/draw' +import { writePdf } from '../pdf/writer' +import { pageToSvg } from '../draw/svg' +import type { Page } from '../draw/types' +import type { SlideModel } from '../pptx/types' const WRITES = new Set([ 'comments.set', @@ -233,6 +238,10 @@ export class Engine { return case 'fonts.measure': return this.measure(args[0] as TextSpec[]) + case 'pdf': + return this.pdf((args[0] ?? {}) as PdfExport) + case 'pptx.svg': + return pageToSvg(await this.slidePage(await this.need(this.pptx).slide(args[0] as number))) case 'collab.xlsx.revert': return this.xc().revert(args[0] as number) case 'collab.pptx.apply': @@ -289,6 +298,41 @@ export class Engine { return out } + /** a slide laid out as a page, its text in the font files of `fonts.set` */ + private slidePage(slide: SlideModel): Promise { + const pkg = this.need(this.pkg) + return slidePage(slide, { + fonts: this.fonts, + part: async (name) => (pkg.has(name) ? new Uint8Array(await (await pkg.blob(name)).arrayBuffer()) : null), + onWarning: (text) => this.warn(text), + }) + } + + private warned = new Set() + + /** a warning told once per document */ + private warn(text: string) { + if (this.warned.has(text)) return + this.warned.add(text) + this.emit('warning', { text }) + } + + private async pdf(opts: PdfExport): Promise { + const pres = this.pptx + if (!pres) throw new Error('PDF output is written for presentations only so far (p10node/office-engine#44)') + const all = pres.meta.slides + for (const i of opts.slides ?? []) if (!all[i]) throw new Error(`No slide #${i}`) + // hidden slides only when asked for, even when named: a list of pages does not show what was hidden + const which = (opts.slides ?? all.map((s) => s.index)).filter((i) => opts.hidden || !all[i].hidden) + if (!which.length) throw new Error(opts.slides?.length ? 'Every slide asked for is hidden: ask for them with `hidden: true`' : opts.slides ? 'No slides were asked for' : 'Every slide is hidden: ask for them with `hidden: true`') + const pages: Page[] = [] + for (const i of which) { + pages.push(await this.slidePage(await pres.slide(i))) + } + const bytes = await writePdf(pages, { ...(opts.title ? { title: opts.title } : {}), onWarning: (text) => this.warn(text) }) + return new Blob([bytes], { type: 'application/pdf' }) + } + /** the comments of the open document */ private comments(): CommentStore { const store = this.docx?.comments ?? this.xlsx?.comments ?? this.pptx?.comments diff --git a/src/core/worker/protocol.ts b/src/core/worker/protocol.ts index b795c7a..fd74f63 100644 --- a/src/core/worker/protocol.ts +++ b/src/core/worker/protocol.ts @@ -17,6 +17,15 @@ export interface MeasuredText extends Omit { pieces: { from: number; to: number; family: string; width: number }[] } +export interface PdfExport { + /** the slides written, by index (default all); hidden ones only with `hidden` */ + slides?: number[] + /** hidden slides are written too (default false: not even when `slides` names them) */ + hidden?: boolean + /** the document's title in the file's metadata */ + title?: string +} + export interface OpenParams { name?: string headers?: Record @@ -146,6 +155,13 @@ export interface Methods { * text differently or no declared file serves it. */ 'fonts.measure'(texts: TextSpec[]): MeasuredText[] + /** + * The open document as a PDF file, its text set in the files of `fonts.set` (Helvetica where none serves it): + * presentations for now (#44). What could not be drawn as it is comes as `warning` events. + */ + pdf(opts?: PdfExport): Blob + /** a slide as an SVG picture, drawn as the PDF draws it */ + 'pptx.svg'(index: number): string /** collaboration (src/collab): a shared XLSX operation, outside the undo history; `rec` reverts it */ 'collab.xlsx.apply'(op: XOp): { res: XlsxEditResult | null; rec: number | null } 'collab.xlsx.revert'(rec: number): XlsxEditResult | null diff --git a/src/react/pptx/Slide.tsx b/src/react/pptx/Slide.tsx index bf5c3b9..b336caa 100644 --- a/src/react/pptx/Slide.tsx +++ b/src/react/pptx/Slide.tsx @@ -6,7 +6,7 @@ import type { DocumentClient } from '../../core/worker/client' import { chartUrl } from '../common/chart' import { useMediaUrl } from '../common/hooks' import { useStrings } from '../strings' -import { geomPath, LINE_GEOMS } from './geometry' +import { geomPath, LINE_GEOMS } from '../../core/pptx/geometry' function boxStyle(b: Box): CSSProperties { const t: string[] = [] @@ -246,13 +246,14 @@ function PicView({ el, client, live }: { el: Extract; cli else if (el.geom === 'roundRect') style.borderRadius = Math.min(box.w, box.h) * 0.1667 if (el.stroke) style.outline = `${el.stroke.w}px solid ${cssColor(el.stroke.c) ?? 'transparent'}` let img: CSSProperties = { position: 'absolute', left: 0, top: 0, width: '100%', height: '100%' } + const flip = box.flipH || box.flipV ? `scale(${box.flipH ? -1 : 1}, ${box.flipV ? -1 : 1})` : undefined if (el.crop) { const [l, t, r, b] = el.crop const sw = box.w / Math.max(0.01, 1 - l - r) const sh = box.h / Math.max(0.01, 1 - t - b) - img = { position: 'absolute', left: -l * sw, top: -t * sh, width: sw, height: sh } + // the cropped part is flipped in the frame: about the frame's centre, not the whole picture's + img = { position: 'absolute', left: -l * sw, top: -t * sh, width: sw, height: sh, ...(flip ? { transformOrigin: `${l * sw + box.w / 2}px ${t * sh + box.h / 2}px` } : {}) } } - const flip = box.flipH || box.flipV ? `scale(${box.flipH ? -1 : 1}, ${box.flipV ? -1 : 1})` : undefined if (flip) img.transform = flip return (
diff --git a/test/pdf-output.test.ts b/test/pdf-output.test.ts new file mode 100644 index 0000000..b127e05 --- /dev/null +++ b/test/pdf-output.test.ts @@ -0,0 +1,742 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { Font, FontBook, subsetFont } from '../src/core/font' +import { decodeGif, decodePng, jpegInfo } from '../src/core/draw/image' +import { ellipsePath, parseColor, parsePath, rectPath } from '../src/core/draw/path' +import { pageToSvg } from '../src/core/draw/svg' +import { parseTransform, svgItems } from '../src/core/draw/svg-in' +import { layoutParagraphs, type ParaSpec, type RunStyle } from '../src/core/draw/text' +import type { DrawItem, Page } from '../src/core/draw/types' +import { writePdf } from '../src/core/pdf/writer' +import { gradient, slidePage } from '../src/core/pptx/draw' +import type { SlideModel } from '../src/core/pptx/types' +import { Engine } from '../src/core/worker/engine' +import { testFont } from './font-builder' +import { buildFont } from './font-tables' + +const BLACK = { r: 0, g: 0, b: 0, a: 1 } + +/** a font whose printable characters are all 1000 units (1 em) wide, the space 500 */ +const EM = testFont({ family: 'Test Em', advance: 1000, space: 500 }) +const book = (family = 'Test Em', bytes: Uint8Array = EM) => new FontBook([{ family, src: bytes }]) + +async function inflate(b: Uint8Array): Promise { + return new Uint8Array(await new Response(new Blob([b as Uint8Array]).stream().pipeThrough(new DecompressionStream('deflate'))).arrayBuffer()) +} + +async function deflate(b: Uint8Array): Promise { + return new Uint8Array(await new Response(new Blob([b as Uint8Array]).stream().pipeThrough(new CompressionStream('deflate') as unknown as TransformStream)).arrayBuffer()) +} + +const latin1 = (b: Uint8Array) => { + let s = '' + for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000)) + return s +} + +/** a PDF's objects by number, streams unpacked */ +async function readPdf(pdf: Uint8Array): Promise<{ text: string; objects: Map }> { + const text = latin1(pdf) + const objects = new Map() + // every offset of the cross-reference table starts its object + const xref = Number(/startxref\n(\d+)/.exec(text)![1]) + expect(text.slice(xref, xref + 4)).toBe('xref') + const count = Number(/xref\n0 (\d+)/.exec(text.slice(xref))![1]) + const rows = text.slice(xref).split('\n').slice(2, 2 + count) + for (let i = 1; i < count; i++) { + const at = Number(rows[i].slice(0, 10)) + expect(text.slice(at, at + `${i} 0 obj`.length)).toBe(`${i} 0 obj`) + const end = text.indexOf('\nendobj', at) + const body = text.slice(at + `${i} 0 obj\n`.length, end) + const s = body.indexOf('\nstream\n') + if (s < 0) objects.set(i, { dict: body }) + else { + const dict = body.slice(0, s) + const len = Number(/\/Length (\d+)/.exec(dict)![1]) + const start = at + `${i} 0 obj\n`.length + s + '\nstream\n'.length + let data = pdf.subarray(start, start + len) + if (dict.includes('/FlateDecode')) data = await inflate(data) + objects.set(i, { dict, stream: data }) + } + } + return { text, objects } +} + +/** the text a ToUnicode map gives the glyph codes of a TJ: what a reader copies */ +function unicodeOf(cmap: string, hex: string): string { + const map = new Map() + for (const m of cmap.matchAll(/<([0-9A-F]{4})> <([0-9A-F]+)>/gi)) { + let s = '' + for (let i = 0; i < m[2].length; i += 4) s += String.fromCharCode(parseInt(m[2].slice(i, i + 4), 16)) + map.set(m[1].toUpperCase(), s) + } + let out = '' + for (let i = 0; i < hex.length; i += 4) out += map.get(hex.slice(i, i + 4).toUpperCase()) ?? '?' + return out +} + +describe('paths, transforms, colors', () => { + test('SVG path data: relative commands, H / V, curves and arcs end where they should', () => { + const d = parsePath('m10 20 h30 v40 H0 l5 5 z') + expect(d.map((s) => s.k).join('')).toBe('MLLLLZ') + expect(d[1]).toEqual({ k: 'L', x: 40, y: 20 }) + expect(d[2]).toEqual({ k: 'L', x: 40, y: 60 }) + expect(d[4]).toEqual({ k: 'L', x: 5, y: 65 }) + const c = parsePath('M0 0 Q10 0 10 10 T20 20 S30 30 40 40 A10 10 0 0 1 60 40') + const last = c[c.length - 1] as { x: number; y: number } + expect(last.x).toBeCloseTo(60) + expect(last.y).toBeCloseTo(40) + // a half circle: two quarter curves + expect(c.filter((s) => s.k === 'C').length).toBe(5) + // numbers after a move are lines; what follows an error is dropped + expect(parsePath('M0 0 10 10 20 0').map((s) => s.k).join('')).toBe('MLL') + expect(parsePath('M0 0 L10 10 L x').length).toBe(2) + }) + + test('transforms apply right to left, as SVG reads them', () => { + const m = parseTransform('translate(10 20) scale(2)') + expect(m).toEqual([2, 0, 0, 2, 10, 20]) + const r = parseTransform('rotate(90 10 10)') + // (20, 10) turns about (10, 10) to (10, 20) + expect(r[0] * 20 + r[2] * 10 + r[4]).toBeCloseTo(10) + expect(r[1] * 20 + r[3] * 10 + r[5]).toBeCloseTo(20) + }) + + test('CSS colors as numbers; anything else is none', () => { + expect(parseColor('#f80')).toEqual({ r: 255, g: 136, b: 0, a: 1 }) + expect(parseColor('rgba(1,2,3,0.5)')).toEqual({ r: 1, g: 2, b: 3, a: 0.5 }) + expect(parseColor('url(x)')).toBeNull() + expect(parseColor('transparent')).toBeNull() + }) + + test('the engine\'s gradients span the box as CSS spans them', () => { + const g = gradient('linear-gradient(90deg, #ff0000 0%, rgba(0,0,255,0.5) 100%)', { x: 0, y: 0, w: 200, h: 100 }) + if (g?.t !== 'linear') throw new Error() + expect([g.x0, g.y0, g.x1, g.y1].map((v) => Math.round(v))).toEqual([0, 50, 200, 50]) + expect(g.stops.map((s) => s.color.a)).toEqual([1, 0.5]) + const r = gradient('radial-gradient(circle, #fff 0%, #000 100%)', { x: 0, y: 0, w: 60, h: 80 }) + expect(r).toMatchObject({ t: 'radial', cx: 30, cy: 40, r: 50 }) + }) +}) + +describe('pictures unpacked', () => { + const png = async (w: number, h: number, type: number, depth: number, rows: number[][], extra: [string, number[]][] = [], interlace = 0) => { + const chunk = (t: string, d: number[]) => { + const out = [d.length >>> 24, (d.length >> 16) & 255, (d.length >> 8) & 255, d.length & 255, ...[...t].map((c) => c.charCodeAt(0)), ...d, 0, 0, 0, 0] + return out + } + const raw = await deflate(new Uint8Array(rows.flatMap((r) => [0, ...r]))) + const ihdr = [0, 0, 0, w, 0, 0, 0, h, depth, type, 0, 0, interlace] + return new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10, ...chunk('IHDR', ihdr), ...extra.flatMap(([t, d]) => chunk(t, d)), ...chunk('IDAT', [...raw]), ...chunk('IEND', [])]) + } + + test('PNG: RGBA, a palette with transparency, 1-bit gray', async () => { + const rgba = await decodePng(await png(2, 1, 6, 8, [[255, 0, 0, 255, 0, 0, 255, 128]])) + expect(rgba).toMatchObject({ w: 2, h: 1, channels: 3 }) + expect([...rgba.color]).toEqual([255, 0, 0, 0, 0, 255]) + expect([...rgba.alpha!]).toEqual([255, 128]) + const pal = await decodePng(await png(2, 1, 3, 8, [[0, 1]], [['PLTE', [10, 20, 30, 40, 50, 60]], ['tRNS', [0]]])) + expect([...pal.color]).toEqual([10, 20, 30, 40, 50, 60]) + expect([...pal.alpha!]).toEqual([0, 255]) + const bits = await decodePng(await png(8, 1, 0, 1, [[0b10100000]])) + expect(bits.channels).toBe(1) + expect([...bits.color]).toEqual([255, 0, 255, 0, 0, 0, 0, 0]) + expect(bits.alpha).toBeUndefined() + }) + + test('PNG: filters undone (sub, up, average, Paeth)', async () => { + // one row per filter, each reading back 1 2 3 + const rows = [[1, 1, 1, 1], [2, 0, 0, 0], [3, 1, 1, 1], [4, 0, 0, 0]] + const raw = await deflate(new Uint8Array(rows.flat())) + const chunk = (t: string, d: number[]) => [d.length >>> 24, (d.length >> 16) & 255, (d.length >> 8) & 255, d.length & 255, ...[...t].map((c) => c.charCodeAt(0)), ...d, 0, 0, 0, 0] + const file = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10, ...chunk('IHDR', [0, 0, 0, 3, 0, 0, 0, 4, 8, 0, 0, 0, 0]), ...chunk('IDAT', [...raw]), ...chunk('IEND', [])]) + const px = await decodePng(file) + expect([...px.color]).toEqual([1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]) + }) + + test('GIF: the first frame, its transparent color as alpha', () => { + const red = Uint8Array.from(atob('R0lGODlhAQABAPAAAP8AAP///yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=='), (c) => c.charCodeAt(0)) + const px = decodeGif(red) + expect([...px.color]).toEqual([255, 0, 0]) + expect(px.alpha).toBeUndefined() + const clear = Uint8Array.from(atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'), (c) => c.charCodeAt(0)) + expect([...decodeGif(clear).alpha!]).toEqual([0]) + }) + + test('JPEG: size and color components from its frame header', () => { + const sof = [0xff, 0xd8, 0xff, 0xc0, 0, 17, 8, 0, 20, 0, 30, 3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1, 0xff, 0xd9] + expect(jpegInfo(new Uint8Array(sof))).toEqual({ w: 30, h: 20, components: 3, adobe: false }) + }) +}) + +describe('text laid out', () => { + const style = (over: Partial = {}): RunStyle => ({ font: 'Test Em', size: 10, color: BLACK, ...over }) + const para = (text: string, over: Partial = {}): ParaSpec => ({ runs: [{ text, style: style() }], align: 'left', marL: 0, indent: 0, before: 0, after: 0, emptySize: 10, ...over }) + const texts = (items: DrawItem[]) => items.filter((i): i is Extract => i.t === 'text') + + test('lines break at spaces, a word longer than the line inside it', async () => { + // each letter 10 px, a space 5 px: "aaa bbb" is 65 px + const out = await layoutParagraphs(book(), [para('aaa bbb cc'), para('abcdefghij')], 50) + const lines = texts(out.items).map((t) => [t.text.slice(t.clusters[0], t.clusters[t.clusters.length - 1] + 1), t.x, t.y]) + expect(lines).toEqual([ + ['aaa ', 0, 9], + ['bbb ', 0, 21], + ['cc', 0, 33], + ['abcde', 0, 45], + ['fghij', 0, 57], + ]) + // 1.2 × 10 px a line, ascent 8 and descent 2 centred in it: the baseline 9 px down + expect(out.height).toBeCloseTo(60) + }) + + test('aligned, justified, with a hanging bullet', async () => { + const center = await layoutParagraphs(book(), [para('ab', { align: 'center' })], 100) + expect(texts(center.items)[0].x).toBe(40) + const right = await layoutParagraphs(book(), [para('ab', { align: 'right' })], 100) + expect(texts(right.items)[0].x).toBe(80) + // justified: the first line's one space takes what is left; the last line is not stretched + const just = await layoutParagraphs(book(), [para('aa bb cc', { align: 'justify' })], 60) + const first = texts(just.items)[0] + // "aa bb" ends at 60; the space after it is not stretched + expect(first.advances.reduce((a, b) => a + b, 0)).toBeCloseTo(65) + expect(first.advances[2]).toBeCloseTo(20) + const bul = await layoutParagraphs(book(), [para('ab', { marL: 30, indent: -30, bullet: { text: '•', style: style({ font: 'Nothing' }) } })], 100) + const t = texts(bul.items) + // the bullet at the hanging indent, the text at the margin + expect(t[0].x).toBe(0) + expect(t[0].font).toBe('Helvetica') + expect(t[1].x).toBe(30) + }) + + test('text no file serves is set in Helvetica and reported', async () => { + const missing: string[] = [] + const out = await layoutParagraphs(book(), [{ ...para(''), runs: [{ text: 'Größe', style: style({ font: '"Calibri", Carlito, sans-serif', bold: true }) }] }], 500, { onMissing: (f) => missing.push(f) }) + const t = texts(out.items)[0] + expect(t.font).toBe('Helvetica-Bold') + // Windows-1252 codes; ß is 0xDF + expect(t.glyphs).toEqual([0x47, 0x72, 0xf6, 0xdf, 0x65]) + expect(missing).toEqual(['"Calibri", Carlito, sans-serif']) + }) + + test('underline, highlight and link around a run', async () => { + const out = await layoutParagraphs(book(), [{ ...para(''), runs: [{ text: 'ab', style: style({ underline: true, highlight: { r: 255, g: 255, b: 0, a: 1 }, href: 'https://example.com/' }) }] }], 100) + expect(out.items.map((i) => i.t)).toEqual(['path', 'text', 'path', 'link']) + expect(out.items[3]).toMatchObject({ t: 'link', x: 0, w: 20, url: 'https://example.com/' }) + }) +}) + +describe('PDF files', () => { + test('fonts embedded as subsets whose text can be copied; pictures, links, outline', async () => { + const font = await Font.open(EM) + const glyphs = [...'Hi there'].map((c) => font.glyphOf(c.codePointAt(0)!)) + const png = await (async () => { + const raw = await deflate(new Uint8Array([0, 255, 0, 0, 128])) + const chunk = (t: string, d: number[]) => [d.length >>> 24, (d.length >> 16) & 255, (d.length >> 8) & 255, d.length & 255, ...[...t].map((c) => c.charCodeAt(0)), ...d, 0, 0, 0, 0] + return new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10, ...chunk('IHDR', [0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]), ...chunk('IDAT', [...raw]), ...chunk('IEND', [])]) + })() + const page: Page = { + w: 400, + h: 300, + title: 'First', + items: [ + { t: 'path', d: rectPath(10, 10, 100, 50), fill: { t: 'linear', x0: 10, y0: 0, x1: 110, y1: 0, stops: [{ at: 0, color: BLACK }, { at: 0.5, color: { r: 255, g: 0, b: 0, a: 1 } }, { at: 1, color: { r: 255, g: 255, b: 255, a: 1 } }] } }, + { t: 'path', d: ellipsePath(200, 50, 30, 20), fill: { t: 'color', color: { r: 0, g: 0, b: 255, a: 0.5 } }, stroke: { paint: { t: 'color', color: BLACK }, width: 2, dash: [4, 2] } }, + { t: 'text', x: 10, y: 100, size: 20, font, glyphs, advances: glyphs.map((g) => (font.advanceOf(g) * 20) / 1000), text: 'Hi there', clusters: [0, 1, 2, 3, 4, 5, 6, 7], fill: BLACK }, + { t: 'text', x: 10, y: 150, size: 20, font: 'Helvetica', glyphs: [0x41, 0x80], advances: [13.34, 11.12], text: 'A€', clusters: [0, 1], fill: BLACK }, + { t: 'image', image: { bytes: png, type: 'image/png' }, x: 300, y: 200, w: 50, h: 50 }, + { t: 'group', transform: [1, 0, 0, 1, 100, 0], items: [{ t: 'link', x: 10, y: 80, w: 80, h: 25, url: 'https://example.com/a(b)' }] }, + ], + } + const pdf = await writePdf([page, { w: 400, h: 300, items: [] }], { title: 'Täst' }) + expect(latin1(pdf.subarray(0, 8))).toBe('%PDF-1.7') + const { text, objects } = await readPdf(pdf) + const all = [...objects.values()] + expect(text).toContain('/Count 2') + // the page is 300 × 225 points + expect(text).toContain('/MediaBox[0 0 300 225]') + const type0 = all.find((o) => o.dict.includes('/Subtype/Type0'))! + expect(type0.dict).toMatch(/\/BaseFont\/[A-Z]{6}\+TestEm/) + expect(all.some((o) => o.dict.includes('/FontFile2'))).toBe(true) + expect(all.some((o) => o.dict.includes('/BaseFont/Helvetica/Encoding/WinAnsiEncoding'))).toBe(true) + // the subset is a font of its own, of the glyphs used + const file = all.find((o) => o.dict.includes('/Length1'))! + const sub = await Font.open(file.stream!) + expect(sub.numGlyphs).toBe(new Set([0, ...glyphs]).size) + // copying the text gives it back + const cmapRef = Number(/\/ToUnicode (\d+)/.exec(type0.dict)![1]) + const cmap = latin1(objects.get(cmapRef)!.stream!) + const content = all.map((o) => (o.stream && o.dict.length < 40 ? latin1(o.stream) : '')).find((s) => s.includes('TJ'))! + const hex = [...content.matchAll(/\/F1 20 Tf\n[^\n]*Tm\n\[(.*)\] TJ/g)][0][1].replace(/[^<>0-9a-f]|<|>/gi, '') + expect(unicodeOf(cmap, hex)).toBe('Hi there') + // the gradient as a stitched shading, the half-transparent fill through a graphics state + expect(text).toContain('/FunctionType 3') + expect(text).toContain('/ca 0.5') + expect(content).toContain('[4 2] 0 d') + // the picture with its alpha as a soft mask + expect(all.some((o) => o.dict.includes('/SMask'))).toBe(true) + // the link moved with its group, in points, its address escaped + expect(text).toContain('/Rect[82.5 146.25 142.5 165]') + expect(text).toContain('/URI(https://example.com/a\\(b\\))') + expect(text).toContain('/Title (First)') + expect(text).toContain('/Title ') + }) + + test('PostScript outlines are embedded as OpenType; a font that forbids embedding is replaced by Helvetica', async () => { + const cff = await Font.open(buildFont({ family: 'Test Cff', cff: true, advances: [500, 600, 700], chars: [[0x41, 1], [0x42, 2]] })) + const locked = await Font.open(buildFont({ family: 'Test Locked', fsType: 2, advances: [500, 600, 700], chars: [[0x41, 1], [0x42, 2]] })) + const text = (font: Font): DrawItem => ({ t: 'text', x: 0, y: 20, size: 10, font, glyphs: [1, 2], advances: [6, 7], text: 'AB', clusters: [0, 1], fill: BLACK }) + const warnings: string[] = [] + const pdf = await writePdf([{ w: 100, h: 100, items: [text(cff), text(locked)] }], { onWarning: (w) => warnings.push(w) }) + const { text: s, objects } = await readPdf(pdf) + expect(s).toContain('/Subtype/CIDFontType0') + expect(s).toContain('/Subtype/OpenType') + expect(s).not.toContain('TestLocked') + expect(warnings).toEqual(['The font Test Locked may not be embedded: its text is set in Helvetica']) + // its text in Helvetica: the characters, where the glyphs were + const content = [...objects.values()].map((o) => (o.stream ? latin1(o.stream) : '')).find((c) => c.includes('/F2'))! + expect(content).toContain('[<41>67<42>] TJ') + }) + + test('a picture in a format a PDF does not take is left out, and said so', async () => { + const warnings: string[] = [] + const emf = new Uint8Array(64) + emf.set([1, 0, 0, 0]) + emf.set([0x20, 0x45, 0x4d, 0x46], 40) + await writePdf([{ w: 10, h: 10, items: [{ t: 'image', image: { bytes: emf, type: 'image/emf' }, x: 0, y: 0, w: 10, h: 10 }] }], { onWarning: (w) => warnings.push(w) }) + expect(warnings).toEqual(['Pictures in EMF are not drawn in a PDF yet']) + }) +}) + +describe('fonts read once, subsets from Node Buffers', () => { + test('a file declared for two families is one font', async () => { + const b = new FontBook([{ family: 'Calibri', src: EM }, { family: 'Carlito', src: EM }]) + const one = await b.measure({ text: 'a', font: 'Calibri', size: 10 }) + const two = await b.measure({ text: 'a', font: 'Carlito', size: 10 }) + expect(one.pieces[0].font).toBe(two.pieces[0].font) + }) + + test('subsetting a font read from a Buffer leaves the font as it was, and keeps each glyph\'s side bearing', async () => { + const bytes = buildFont({ family: 'Test Lsb', advances: [500, 600, 700, 800], chars: [[0x41, 1], [0x42, 2], [0x43, 3]] }) + const font = await Font.open(Buffer.from(bytes)) + const before = new Uint8Array(font.tables.get('hhea')!) + const sub = subsetFont(font, [3]) + expect(new Uint8Array(font.tables.get('hhea')!)).toEqual(before) + const lsb = (f: Font, g: number) => new DataView(f.tables.get('hmtx')!.buffer, f.tables.get('hmtx')!.byteOffset).getInt16(g * 4 + 2) + const again = await Font.open(sub.bytes) + expect(lsb(again, sub.glyphs.get(3)!)).toBe(lsb(font, 3)) + }) +}) + +describe('slides as pages', () => { + const slide = (els: SlideModel['els'], over: Partial = {}): SlideModel => ({ index: 0, w: 400, h: 300, els, ...over }) + const opts = { fonts: book(), part: async () => null } + const flat = (items: DrawItem[]): DrawItem[] => items.flatMap((i) => (i.t === 'group' ? flat(i.items) : [i])) + + test('a shape\'s outline flips, its text turns with it but is not flipped', async () => { + const page = await slidePage( + slide([ + { + t: 'shape', + box: { x: 100, y: 50, w: 200, h: 100, rot: 90, flipH: true }, + geom: 'rect', + fill: { t: 'solid', c: '#ff0000' }, + stroke: { c: '#000000', w: 2, tail: 'triangle' }, + text: { anchor: 'ctr', ins: [10, 5, 10, 5], wrap: true, paras: [{ algn: 'center', marL: 0, indent: 0, spcBef: 0, spcAft: 0, runs: [{ text: 'ab', sz: 7.5, font: 'Test Em' }], endSz: 7.5 }] }, + }, + ]), + opts, + ) + expect(page).toMatchObject({ w: 400, h: 300 }) + const shape = (page.items[0] as Extract).items[1] as Extract + // turned about its centre (200, 100), then placed + expect(shape.transform![0]).toBeCloseTo(0) + expect(shape.transform![1]).toBeCloseTo(1) + expect(shape.transform![4]).toBeCloseTo(250) + expect(shape.transform![5]).toBeCloseTo(0) + const outline = shape.items[0] as Extract + expect(outline.transform).toEqual([-1, 0, 0, 1, 200, 0]) + // fill, outline, arrowhead + expect(outline.items.map((i) => i.t)).toEqual(['path', 'path', 'path']) + const text = flat(shape.items).find((i) => i.t === 'text') as Extract + // 7.5 pt is 10 px: "ab" is 20 px wide, centred in 180 px; one 12 px line centred in 90 + const block = shape.items[1] as Extract + expect(block.transform).toEqual([1, 0, 0, 1, 10, 5 + 39]) + expect(text.x).toBe(80) + }) + + test('a table\'s rows grow to their text', async () => { + const cell = (text: string) => ({ text: { anchor: 't' as const, ins: [0, 0, 0, 0] as [number, number, number, number], wrap: true, paras: [{ algn: 'left' as const, marL: 0, indent: 0, spcBef: 0, spcAft: 0, runs: [{ text, sz: 7.5, font: 'Test Em' }], endSz: 7.5 }] }, colSpan: 1, rowSpan: 1, hidden: false, fill: { t: 'solid' as const, c: '#eeeeee' }, bb: { c: '#000000', w: 1 } }) + const page = await slidePage(slide([{ t: 'table', box: { x: 0, y: 0, w: 60, h: 20 }, cols: [30, 30], rows: [{ h: 5, cells: [cell('aaa bbb'), cell('c')] }, { h: 5, cells: [cell('d'), cell('e')] }] }]), opts) + const items = flat(page.items) + const borders = items.filter((i): i is Extract => i.t === 'path' && !!i.stroke) + // the first row is two lines of 12 px: its bottom border at 24, the second row's at 36 + expect(borders.map((b) => (b.d[0] as { y: number }).y)).toEqual([24, 24, 36, 36]) + }) + + test('charts and SVG pictures are drawn as shapes and text', async () => { + const items = await svgItems( + 'ab', + book(), + ) + const top = items[0] as Extract + // the view box fitted to 100 × 50 + expect(top.transform).toEqual([0.5, 0, 0, 0.5, 0, 0]) + const all = flat(items) + expect(all.map((i) => i.t)).toEqual(['path', 'path', 'text']) + // objectBoundingBox: the gradient across the rectangle + expect((all[0] as Extract).fill).toMatchObject({ t: 'linear', x0: 0, x1: 200 }) + const g = top.items[1] as Extract + expect(g.transform).toEqual([1, 0, 0, 1, 10, 0]) + expect(g.clip?.length).toBe(5) + // the text centred on its x: 40 px wide + const t = top.items[2] as Extract + expect(t.transform).toEqual([1, 0, 0, 1, 80, 80]) + }) + + test('the sample deck as a PDF: every slide a page, its title in the outline, its chart drawn', async () => { + const warnings: string[] = [] + const engine = new Engine((e, d) => e === 'warning' && warnings.push((d as { text: string }).text)) + await engine.open(new Uint8Array(readFileSync('playground/public/samples/sample.pptx')), { name: 'sample.pptx' }) + await engine.call('fonts.set', [[{ family: 'Calibri', src: EM }]]) + const blob = (await engine.call('pdf', [{ title: 'Sample' }])) as Blob + expect(blob.type).toBe('application/pdf') + const { text, objects } = await readPdf(new Uint8Array(await blob.arrayBuffer())) + expect(text).toContain('/Count 5') + expect(text).toContain('/Title (Shapes & images)') + expect(text).toContain('/Title (Chart \\(placeholder\\))') + expect(text).toContain('/Title (Sample)') + // the chart's labels are text + const contents = [...objects.values()].map((o) => (o.stream && o.dict.length < 40 ? latin1(o.stream) : '')).join('\n') + expect(contents.split(' TJ').length).toBeGreaterThan(50) + expect(warnings.every((w) => !/chart/i.test(w))).toBe(true) + // one slide, and as SVG + const one = (await engine.call('pdf', [{ slides: [2] }])) as Blob + expect(latin1(new Uint8Array(await one.arrayBuffer()))).toContain('/Count 1') + const svg = (await engine.call('pptx.svg', [0])) as string + expect(svg).toMatch(/^ { + const engine = new Engine(() => {}) + await engine.open(new Uint8Array(readFileSync('playground/public/samples/sample.pptx')), { name: 'sample.pptx' }) + await engine.call('pptx.slides', [{ op: 'hide', index: 1, hidden: true }]) + const count = async (opts: object) => /\/Count (\d+)/.exec(latin1(new Uint8Array(await ((await engine.call('pdf', [opts])) as Blob).arrayBuffer())))![1] + expect(await count({})).toBe('4') + expect(await count({ hidden: true })).toBe('5') + // named, a hidden slide is still left out: a list of slides does not show what was hidden + expect(await count({ slides: [0, 1] })).toBe('1') + expect(await count({ slides: [1], hidden: true })).toBe('1') + expect(engine.call('pdf', [{ slides: [1] }])).rejects.toThrow('Every slide asked for is hidden') + }) + + test('a page as SVG', () => { + const svg = pageToSvg({ w: 10, h: 10, items: [{ t: 'path', d: rectPath(0, 0, 5, 5), fill: { t: 'color', color: { r: 255, g: 0, b: 0, a: 0.5 } } }] }) + expect(svg).toBe('') + }) +}) + +describe('review: hostile input, copied text, licenses', () => { + const style = (over: Partial = {}): RunStyle => ({ font: 'Test Em', size: 10, color: BLACK, ...over }) + const para = (runs: { text: string; style: RunStyle }[]): ParaSpec => ({ runs, align: 'left', marL: 0, indent: 0, before: 0, after: 0, emptySize: 10 }) + const texts = (items: DrawItem[]) => items.filter((i): i is Extract => i.t === 'text') + const contents = (objects: Map) => [...objects.values()].map((o) => (o.stream && !o.dict.includes('/Length1') && !o.dict.includes('/Subtype/') ? latin1(o.stream) : '')).join('\n') + + test('an SVG whose uses repeat uses is refused, not multiplied; a use of itself is drawn once', async () => { + let svg = '' + for (let i = 1; i <= 20; i++) svg += `` + svg += '' + expect(svgItems(svg, book())).rejects.toThrow(/is not drawn/) + const loop = await svgItems('', book()) + const flat = (items: DrawItem[]): DrawItem[] => items.flatMap((i) => (i.t === 'group' ? flat(i.items) : [i])) + expect(flat(loop).length).toBe(2) + }) + + test('a PNG is unpacked no further than a little past its pixels; a GIF frame past the limit is refused', async () => { + const chunk = (t: string, d: number[] | Uint8Array) => [d.length >>> 24, (d.length >> 16) & 255, (d.length >> 8) & 255, d.length & 255, ...[...t].map((c) => c.charCodeAt(0)), ...d, 0, 0, 0, 0] + // 16 MB of zeros behind a 1 × 1 picture + const raw = await deflate(new Uint8Array(16 * 1024 * 1024)) + const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10, ...chunk('IHDR', [0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0]), ...chunk('IDAT', raw), ...chunk('IEND', [])]) + expect(decodePng(png)).rejects.toThrow(/much longer than its pixels/) + const gif = Uint8Array.from(atob('R0lGODlhAQABAPAAAP8AAP///yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=='), (c) => c.charCodeAt(0)) + // the frame (its descriptor at byte 27) says 9000 × 9000 + gif.set([0x28, 0x23, 0x28, 0x23], 32) + expect(() => decodeGif(gif)).toThrow(/not drawn/) + }) + + test('16-bit color keys compare all their bits', async () => { + const chunk = (t: string, d: number[] | Uint8Array) => [d.length >>> 24, (d.length >> 16) & 255, (d.length >> 8) & 255, d.length & 255, ...[...t].map((c) => c.charCodeAt(0)), ...d, 0, 0, 0, 0] + const raw = await deflate(new Uint8Array([0, 0xab, 0x01, 0xab, 0x02])) + const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10, ...chunk('IHDR', [0, 0, 0, 2, 0, 0, 0, 1, 16, 0, 0, 0, 0]), ...chunk('tRNS', [0xab, 0x01]), ...chunk('IDAT', raw), ...chunk('IEND', [])]) + const px = await decodePng(png) + expect([...px.color]).toEqual([0xab, 0xab]) + expect([...px.alpha!]).toEqual([0, 255]) + }) + + test('a line set in two fonts: each glyph run stands for its own characters', async () => { + const greek = buildFont({ family: 'Test Greek', advances: [500, 600], chars: [[0x3a9, 1]] }) + const b = new FontBook([{ family: 'Test Em', src: EM }, { family: 'Test Greek', src: greek }]) + const out = await layoutParagraphs(b, [para([{ text: 'AΩB', style: style({ font: 'Test Em, Test Greek' }) }])], 500) + expect(texts(out.items).map((t) => [t.text, t.clusters])).toEqual([ + ['A', [0]], + ['Ω', [0]], + ['B', [0]], + ]) + }) + + test('lines are not broken inside a character of two UTF-16 units; tabs draw nothing', async () => { + const out = await layoutParagraphs(book(), [para([{ text: 'a\u{20000}\u{20000}\u{20000}', style: style({ font: 'Nothing' }) }])], 1) + for (const t of texts(out.items)) expect(t.text).not.toMatch(/^[\udc00-\udfff]|[\ud800-\udbff]$/) + const tab = await layoutParagraphs(book(), [para([{ text: 'A\tB', style: style({ font: 'Nothing' }) }])], 500) + const t = texts(tab.items)[0] + expect(t.glyphs).toEqual([0x41, 0x42]) + // B at the first tab stop + expect(t.advances[0]).toBe(96) + }) + + test('a narrow box of long text is laid out in linear time', async () => { + const t0 = performance.now() + const out = await layoutParagraphs(book(), [para([{ text: 'a'.repeat(20000), style: style() }])], 1) + expect(texts(out.items).length).toBe(20000) + expect(performance.now() - t0).toBeLessThan(3000) + }) + + test('the license: bitmaps only is not embedded, no subsetting embeds the whole font, a damaged font falls back', async () => { + const font = (fsType: number, family: string) => buildFont({ family, fsType, advances: [500, 600, 700, 800], chars: [[0x41, 1], [0x42, 2], [0x43, 3]] }) + const bitmaps = await Font.open(font(0x0200, 'Test Bitmaps')) + const whole = await Font.open(font(0x0100, 'Test Whole')) + const damaged = await Font.open(font(0, 'Test Damaged')) + // its first glyph made to end past its table + const loca = damaged.tables.get('loca')! + new DataView(loca.buffer, loca.byteOffset).setUint32(8, 0x7fffffff) + const text = (f: Font): DrawItem => ({ t: 'text', x: 0, y: 20, size: 10, font: f, glyphs: [1], advances: [6], text: 'A', clusters: [0], fill: BLACK }) + const warnings: string[] = [] + const pdf = await writePdf([{ w: 100, h: 100, items: [text(bitmaps), text(whole), text(damaged)] }], { onWarning: (w) => warnings.push(w) }) + expect(warnings).toEqual([ + 'The font Test Bitmaps may not be embedded but as bitmaps: its text is set in Helvetica', + expect.stringMatching(/^The font Test Damaged could not be embedded \(.*\): its text is set in Helvetica$/), + ]) + const { objects } = await readPdf(pdf) + const file = [...objects.values()].find((o) => o.dict.includes('/Length1'))! + expect((await Font.open(file.stream!)).numGlyphs).toBe(4) + }) + + test('a glyph that stands for different text in two places is given its text; links are ASCII', async () => { + const font = await Font.open(EM) + const g = font.glyphOf(0x66) + const item = (text: string): DrawItem => ({ t: 'text', x: 0, y: 20, size: 10, font, glyphs: [g], advances: [10], text, clusters: [0], fill: BLACK }) + const pdf = await writePdf([{ w: 100, h: 100, items: [item('fi'), item('fi'), { t: 'link', x: 0, y: 0, w: 10, h: 10, url: 'https://example.org/café(x)' }] }]) + const { text, objects } = await readPdf(pdf) + const c = contents(objects) + expect(c.match(/ActualText/g)?.length).toBe(1) + expect(c).toContain('/Span<>>BDC') + expect(text).toContain('/URI(https://example.org/caf%C3%A9\\(x\\))') + }) + + test('transparent groups are drawn whole; a gradient that fades has a soft mask; numbers have no exponent; hard stops', async () => { + const red = { r: 255, g: 0, b: 0, a: 1 } + const pdf = await writePdf([ + { + w: 100, + h: 100, + items: [ + { t: 'group', opacity: 0.5, items: [{ t: 'path', d: rectPath(0, 0, 50, 50), fill: { t: 'color', color: red } }, { t: 'path', d: rectPath(25, 25, 50, 50), fill: { t: 'color', color: { ...red, a: 0.8 } } }] }, + { t: 'path', d: rectPath(0, 0, 1e22, 10), fill: { t: 'linear', x0: 0, y0: 0, x1: 100, y1: 0, stops: [{ at: 0, color: { ...red, a: 0 } }, { at: 0.5, color: red }, { at: 0.5, color: BLACK }, { at: 1, color: BLACK }] } }, + ], + }, + ]) + const { text, objects } = await readPdf(pdf) + expect(text).toContain('/Subtype/Form') + expect(text).toContain('/Group<>') + expect(text).toContain('/SMask< { + const cid = await Font.open(buildFont({ family: 'Test Cid', cff: 'cid', advances: [500, 600, 700], chars: [[0x41, 1], [0x42, 2]] })) + const sub = subsetFont(cid, [2]) + expect(latin1(sub.cff!)).toContain('Identity') + }) + + test('a slide\'s picture that cannot be read is left out; an empty selection is refused', async () => { + const warnings: string[] = [] + const page = await slidePage({ index: 0, w: 100, h: 100, els: [{ t: 'pic', box: { x: 0, y: 0, w: 10, h: 10 }, target: 'ppt/media/a.png' }] }, { fonts: book(), part: async () => Promise.reject(new Error('gone')), onWarning: (w) => warnings.push(w) }) + expect(page.w).toBe(100) + expect(warnings).toEqual(['A picture could not be read: gone']) + const engine = new Engine(() => {}) + await engine.open(new Uint8Array(readFileSync('playground/public/samples/sample.pptx')), { name: 'sample.pptx' }) + expect(engine.call('pdf', [{ slides: [] }])).rejects.toThrow('No slides were asked for') + expect(writePdf([])).rejects.toThrow(/at least one page/) + }) + + test('a cropped, flipped picture shows its cropped part mirrored in the frame', async () => { + const png = Uint8Array.from(atob('R0lGODlhAQABAPAAAP8AAP///yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=='), (c) => c.charCodeAt(0)) + const page = await slidePage({ index: 0, w: 100, h: 100, els: [{ t: 'pic', box: { x: 0, y: 0, w: 75, h: 10, flipH: true }, target: 'a.gif', crop: [0.25, 0, 0, 0] }] }, { fonts: book(), part: async () => png }) + const frame = (page.items[0] as Extract).items[1] as Extract + const flip = (frame.items[0] as Extract).items[0] as Extract + expect(flip.transform).toEqual([-1, 0, 0, 1, 75, 0]) + // the picture's 100 px with its first 25 cut off + expect(flip.items[0]).toMatchObject({ t: 'image', x: -25, w: 100 }) + }) +}) + +describe('re-check: budgets, names, boxes', () => { + const style = (over: Partial = {}): RunStyle => ({ font: 'Test Em', size: 10, color: BLACK, ...over }) + const para = (runs: { text: string; style: RunStyle }[]): ParaSpec => ({ runs, align: 'left', marL: 0, indent: 0, before: 0, after: 0, emptySize: 10 }) + const texts = (items: DrawItem[]) => items.filter((i): i is Extract => i.t === 'text') + const red = { r: 255, g: 0, b: 0, a: 1 } + + test('clip paths count toward the segments an SVG may draw', async () => { + let d = 'M0 0' + for (let i = 0; i < 4000; i++) d += ` L${i % 10} ${i % 7}` + let svg = `` + for (let i = 0; i < 251; i++) svg += '' + expect(svgItems(svg + '', book())).rejects.toThrow(/path segments is not drawn/) + }) + + test('a picture part that throws, or rejects with anything, is left out', async () => { + for (const part of [() => { throw new Error('sync') }, () => Promise.reject(null)]) { + const warnings: string[] = [] + await slidePage({ index: 0, w: 10, h: 10, els: [{ t: 'pic', box: { x: 0, y: 0, w: 5, h: 5 }, target: 'a.png' }] }, { fonts: book(), part: part as () => Promise, onWarning: (w) => warnings.push(w) }) + expect(warnings.length).toBe(1) + } + }) + + test('a link with half a surrogate pair is written, as U+FFFD', async () => { + const pdf = await writePdf([{ w: 10, h: 10, items: [{ t: 'link', x: 0, y: 0, w: 5, h: 5, url: 'https://example.org/\ud800x' }] }]) + expect(latin1(pdf)).toContain('/URI(https://example.org/%EF%BF%BDx)') + }) + + test('long runs and runs in two fonts stay linear', async () => { + const font = await Font.open(EM) + const n = 40000 + const g = font.glyphOf(0x41) + const t0 = performance.now() + await writePdf([{ w: 10, h: 10, items: [{ t: 'text', x: 0, y: 10, size: 10, font, glyphs: Array(n).fill(g), advances: Array(n).fill(10), text: 'A'.repeat(n), clusters: Array.from({ length: n }, (_, i) => i), fill: BLACK }] }]) + expect(performance.now() - t0).toBeLessThan(2000) + const greek = buildFont({ family: 'Test Greek', advances: [500, 600], chars: [[0x3a9, 1]] }) + const b = new FontBook([{ family: 'Test Em', src: EM }, { family: 'Test Greek', src: greek }]) + const t1 = performance.now() + const out = await layoutParagraphs(b, [para([{ text: 'AΩ'.repeat(6000), style: style({ font: 'Test Em, Test Greek' }) }])], 1) + expect(texts(out.items).length).toBe(12000) + expect(performance.now() - t1).toBeLessThan(3000) + }) + + test('masks have names of their own; a form\'s box holds the page wherever it is drawn; whole fonts carry no subset tag', async () => { + const whole = await Font.open(buildFont({ family: 'Test Whole', fsType: 0x0100, advances: [500, 600], chars: [[0x41, 1]] })) + const items: DrawItem[] = [ + { t: 'path', d: rectPath(0, 0, 10, 10), fill: { t: 'linear', x0: 0, y0: 0, x1: 10, y1: 0, stops: [{ at: 0, color: { ...red, a: 0 } }, { at: 1, color: red }] } }, + ...Array.from({ length: 5 }, (_, i): DrawItem => ({ t: 'path', d: rectPath(0, 0, 1, 1), fill: { t: 'color', color: { ...red, a: (i + 1) / 10 } } })), + { t: 'group', transform: [1, 0, 0, 1, -1000010, 0], items: [{ t: 'group', opacity: 0.5, items: [{ t: 'path', d: rectPath(1000010, 0, 50, 50), fill: { t: 'color', color: red } }] }] }, + { t: 'text', x: 0, y: 20, size: 10, font: whole, glyphs: [1], advances: [6], text: 'A', clusters: [0], fill: BLACK }, + ] + const { text } = await readPdf(await writePdf([{ w: 100, h: 100, items }])) + const names = [...text.matchAll(/\/ExtGState<<([^>]*)>>/g)].flatMap((m) => [...m[1].matchAll(/\/(\w+) \d+ 0 R/g)].map((x) => x[1])) + expect(new Set(names).size).toBe(names.length) + expect(names).toContain('M1') + // the transparent group's form: in its space the page is at x 1000010 (and the box around it) + const box = /\/BBox\[([^\]]*)\]\/Group<<\/S\/Transparency\/I true/.exec(text)![1].split(' ').map(Number) + expect(box[0]).toBeLessThanOrEqual(1000010) + expect(box[2]).toBeGreaterThanOrEqual(1000110) + expect(text).toContain('/BaseFont/TestWhole') + }) + + test('a gradient along a line is a shading pattern; stops that round together make one edge', async () => { + const stops = [0, 0.0002, 0.5001, 0.5002, 0.9998, 1].map((at, i) => ({ at, color: i % 2 ? red : BLACK })) + const { text, objects } = await readPdf(await writePdf([{ w: 100, h: 100, items: [{ t: 'path', d: [{ k: 'M', x: 0, y: 0 }, { k: 'L', x: 100, y: 0 }], stroke: { paint: { t: 'linear', x0: 0, y0: 0, x1: 100, y1: 0, stops }, width: 4 } }] }])) + expect(text).toContain('/PatternType 2') + expect([...objects.values()].map((o) => (o.stream ? latin1(o.stream) : '')).join('')).toContain('/Pattern CS /P1 SCN') + const bounds = /\/Bounds\[([^\]]*)\]/.exec(text)![1].split(' ').map(Number) + for (let i = 1; i < bounds.length; i++) expect(bounds[i]).toBeGreaterThan(bounds[i - 1]) + }) + + test('a PNG whose data is cut short of its checksum is refused', async () => { + const chunk = (t: string, d: number[] | Uint8Array) => [d.length >>> 24, (d.length >> 16) & 255, (d.length >> 8) & 255, d.length & 255, ...[...t].map((c) => c.charCodeAt(0)), ...d, 0, 0, 0, 0] + const raw = await deflate(new Uint8Array([0, 7])) + const png = (data: Uint8Array) => new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10, ...chunk('IHDR', [0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0]), ...chunk('IDAT', data), ...chunk('IEND', [])]) + expect([...(await decodePng(png(raw))).color]).toEqual([7]) + expect(decodePng(png(raw.subarray(0, raw.length - 4)))).rejects.toThrow(/damaged/) + }) + + test('a line can end after an ideograph of two UTF-16 units', async () => { + // x 10 px, the ideograph in Helvetica (a question mark, 5.56 px), y and z 10 px: x and the ideograph fit in 31 px with y + const out = await layoutParagraphs(book(), [para([{ text: 'x\u{20000}yz', style: style() }])], 21) + const t = texts(out.items) + expect(t.map((i) => i.text)).toEqual(['x', '\u{20000}', 'yz']) + expect(t[1].y).toBe(t[0].y) + expect(t[2].y).toBeGreaterThan(t[0].y) + }) +}) + +describe('final check: precision, reuse, edges', () => { + const red = { r: 255, g: 0, b: 0, a: 1 } + const blue = { r: 0, g: 0, b: 255, a: 1 } + + test('small scales are written as they are, so boxes and patterns agree with what is drawn', async () => { + const pdf = await writePdf([ + { + w: 100, + h: 100, + items: [ + { t: 'group', transform: [0.00149, 0, 0, 1, 0, 0], items: [{ t: 'group', opacity: 0.5, items: [{ t: 'path', d: rectPath(60000, 0, 50000, 50), fill: { t: 'color', color: red } }] }] }, + { t: 'group', opacity: 0.5, items: [{ t: 'group', transform: [0.02, 0, 0, 1, 0, 0], items: [{ t: 'group', transform: [0.02, 0, 0, 1, 0, 0], items: [{ t: 'path', d: [{ k: 'M', x: 0, y: 10 }, { k: 'L', x: 200000, y: 10 }], stroke: { paint: { t: 'linear', x0: 0, y0: 0, x1: 200000, y1: 0, stops: [{ at: 0, color: red }, { at: 1, color: blue }] }, width: 2 } }] }] }] }, + ], + }, + ]) + const { text, objects } = await readPdf(pdf) + const all = [...objects.values()].map((o) => (o.stream ? latin1(o.stream) : '')).join('\n') + expect(all).toContain('0.00149 0 0 1 0 0 cm') + // the form's box, in its space: the page's 75 points are 75 / (0.75 × 0.00149) wide there + const box = /\/BBox\[([^\]]*)\]/.exec(text)![1].split(' ').map(Number) + expect(box[2]).toBeCloseTo(100 / 0.00149 + 1, -1) + // the pattern keeps the product of the two scales, in the space of the form it is drawn in + expect(text).toMatch(/\/PatternType 2\/Shading \d+ 0 R\/Matrix\[0\.0004 0 0 1 0 0\]/) + }) + + test('a text command changed after one export is exported as it is now', async () => { + const font = await Font.open(EM) + const item: Extract = { t: 'text', x: 0, y: 20, size: 10, font, glyphs: [font.glyphOf(0x41)], advances: [10], text: 'A', clusters: [0], fill: BLACK } + expect(pageToSvg({ w: 10, h: 10, items: [item] })).toContain('>A') + item.text = 'B' + item.glyphs = [font.glyphOf(0x42)] + expect(pageToSvg({ w: 10, h: 10, items: [item] })).toContain('>B') + }) + + test('a gradient of no length paints its last color; a color fill and outline are painted together', async () => { + const { objects } = await readPdf( + await writePdf([ + { + w: 100, + h: 100, + items: [ + { t: 'path', d: [{ k: 'M', x: 0, y: 5 }, { k: 'L', x: 50, y: 5 }], stroke: { paint: { t: 'linear', x0: 20, y0: 5, x1: 20, y1: 5, stops: [{ at: 0, color: red }, { at: 1, color: blue }] }, width: 2 } }, + { t: 'path', d: rectPath(10, 10, 50, 50), fill: { t: 'color', color: { ...red, a: 0.5 } }, stroke: { paint: { t: 'color', color: { ...blue, a: 0.5 } }, width: 6 } }, + ], + }, + ]), + ) + const c = [...objects.values()].map((o) => (o.stream ? latin1(o.stream) : '')).join('\n') + expect(c).toContain('0 0 1 RG') + expect(c).not.toContain('/Pattern CS') + expect(c).toMatch(/1 0 0 rg\n0 0 1 RG\n6 w\n0 J\n0 j\n10 10 m .* B\n/) + }) + + test('two fonts of one name keep apart', async () => { + const whole = (name: string) => buildFont({ family: name, fsType: 0x0100, advances: [500, 600], chars: [[0x41, 1]] }) + const a = await Font.open(whole('Test.A_B')) + const b = await Font.open(whole('TestAB')) + const t = (f: Font): DrawItem => ({ t: 'text', x: 0, y: 20, size: 10, font: f, glyphs: [1], advances: [6], text: 'A', clusters: [0], fill: BLACK }) + const text = latin1(await writePdf([{ w: 10, h: 10, items: [t(a), t(b)] }])) + const names = [...text.matchAll(/\/FontName(\/[^/]+)\//g)].map((m) => m[1]) + expect(new Set(names).size).toBe(2) + }) + + test('a rejection that cannot be made a string is still reported', async () => { + const warnings: string[] = [] + await slidePage({ index: 0, w: 10, h: 10, els: [{ t: 'pic', box: { x: 0, y: 0, w: 5, h: 5 }, target: 'a.png' }] }, { fonts: book(), part: () => Promise.reject(Object.create(null)), onWarning: (w) => warnings.push(w) }) + expect(warnings).toEqual(['A picture could not be read: an error']) + }) +})