141 lines
4.2 KiB
TypeScript
141 lines
4.2 KiB
TypeScript
import {
|
|
decodePDFRawStream,
|
|
PDFArray,
|
|
PDFDict,
|
|
PDFDocument,
|
|
PDFName,
|
|
PDFRawStream,
|
|
type PDFPage,
|
|
} from 'pdf-lib'
|
|
import { round2, type ImageEntry, type TextEntry } from './goldens'
|
|
|
|
/**
|
|
* The drawing facts of a saved PDF, read back from its content streams (R4.6: the core
|
|
* writes the file, so nothing is recorded at draw time any more; pdf-lib still reads the
|
|
* file in the tests until R4.8). The streams are the operator sequences pdf-lib emitted
|
|
* and the core reproduces: one operator per line, `q BT rg Tf TL Tm (Tj T*)+ ET Q` per
|
|
* text call, `q cm cm cm cm Do Q` per image. Positions are rounded like the recorder did.
|
|
*/
|
|
|
|
/** WinAnsi is Windows-1252 for every glyph the engine prints. */
|
|
const winAnsi = new TextDecoder('windows-1252')
|
|
|
|
function hexBytes(token: string): Uint8Array {
|
|
const hex = token.slice(1, -1)
|
|
const out = new Uint8Array(hex.length / 2)
|
|
for (let i = 0; i < out.length; i += 1) {
|
|
out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
|
|
}
|
|
return out
|
|
}
|
|
|
|
function contentOf(page: PDFPage): string {
|
|
const contents = page.node.Contents()
|
|
const streams: PDFRawStream[] = []
|
|
if (contents instanceof PDFRawStream) streams.push(contents)
|
|
else if (contents instanceof PDFArray) {
|
|
for (let i = 0; i < contents.size(); i += 1) {
|
|
streams.push(contents.lookup(i, PDFRawStream))
|
|
}
|
|
}
|
|
return streams
|
|
.map((stream) =>
|
|
new TextDecoder('latin1').decode(decodePDFRawStream(stream).decode()),
|
|
)
|
|
.join('\n')
|
|
}
|
|
|
|
/** `/F1` → `Helvetica`, through the page's font resources. */
|
|
function fontNames(page: PDFPage): Map<string, string> {
|
|
const names = new Map<string, string>()
|
|
const resources = page.node.lookup(PDFName.of('Resources'), PDFDict)
|
|
const fonts = resources.lookupMaybe(PDFName.of('Font'), PDFDict)
|
|
if (!fonts) return names
|
|
for (const [key, ref] of fonts.entries()) {
|
|
const font = fonts.context.lookup(ref, PDFDict)
|
|
const base = font.lookup(PDFName.of('BaseFont'))
|
|
names.set(key.decodeText(), String(base).replace(/^\//, ''))
|
|
}
|
|
return names
|
|
}
|
|
|
|
interface PageFacts {
|
|
texts: TextEntry[]
|
|
images: ImageEntry[]
|
|
}
|
|
|
|
function readPage(page: PDFPage, index: number): PageFacts {
|
|
const fonts = fontNames(page)
|
|
const texts: TextEntry[] = []
|
|
const images: ImageEntry[] = []
|
|
let font: string | null = null
|
|
let size: number | null = null
|
|
let x: number | null = null
|
|
let y: number | null = null
|
|
let lines: string[] = []
|
|
let matrices: number[][] = []
|
|
for (const line of contentOf(page).split('\n')) {
|
|
const tokens = line.trim().split(' ')
|
|
const op = tokens[tokens.length - 1]
|
|
const operands = tokens.slice(0, -1)
|
|
switch (op) {
|
|
case 'q':
|
|
matrices = []
|
|
break
|
|
case 'BT':
|
|
lines = []
|
|
break
|
|
case 'Tf':
|
|
font = fonts.get(operands[0]!.slice(1)) ?? operands[0]!
|
|
size = round2(Number(operands[1]))
|
|
break
|
|
case 'Tm':
|
|
x = round2(Number(operands[4]))
|
|
y = round2(Number(operands[5]))
|
|
break
|
|
case 'Tj':
|
|
lines.push(winAnsi.decode(hexBytes(operands[0]!)))
|
|
break
|
|
case 'ET':
|
|
texts.push({ page: index, text: lines.join('\n'), x, y, size, font })
|
|
break
|
|
case 'cm':
|
|
matrices.push(operands.map(Number))
|
|
break
|
|
case 'Do': {
|
|
const translate = matrices[0] ?? []
|
|
const scale = matrices[2] ?? []
|
|
images.push({
|
|
page: index,
|
|
x: round2(translate[4]),
|
|
y: round2(translate[5]),
|
|
width: round2(scale[0]),
|
|
height: round2(scale[3]),
|
|
})
|
|
break
|
|
}
|
|
default:
|
|
break
|
|
}
|
|
}
|
|
return { texts, images }
|
|
}
|
|
|
|
/** Every text and image call of the file, page by page, in stream order. */
|
|
export async function readDrawing(bytes: Uint8Array): Promise<PageFacts> {
|
|
const doc = await PDFDocument.load(bytes)
|
|
const texts: TextEntry[] = []
|
|
const images: ImageEntry[] = []
|
|
doc.getPages().forEach((page, index) => {
|
|
const facts = readPage(page, index)
|
|
texts.push(...facts.texts)
|
|
images.push(...facts.images)
|
|
})
|
|
return { texts, images }
|
|
}
|
|
|
|
/** The bytes of a Blob the export produced. */
|
|
export async function bytesOf(blob: Blob): Promise<Uint8Array> {
|
|
return new Uint8Array(await blob.arrayBuffer())
|
|
}
|