import { AFRelationship, PDFDocument, PDFName, PDFRawStream } from 'pdf-lib' /** Crafted PDFs for the read tests, built with pdf-lib's own attach. */ export async function pdfWithAttachment( name: string, payload: unknown, extra: { keywords?: string[]; before?: [string, unknown] } = {}, ): Promise { const doc = await PDFDocument.create() doc.addPage() if (extra.keywords) doc.setKeywords(extra.keywords) if (extra.before) await attachJson(doc, extra.before[0], extra.before[1]) await attachJson(doc, name, payload) return doc.save() } async function attachJson( doc: PDFDocument, name: string, payload: unknown, ): Promise { await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, { mimeType: 'application/json', afRelationship: AFRelationship.Data, }) } export async function pdfWithoutAttachment( keywords?: string[], ): Promise { const doc = await PDFDocument.create() doc.addPage() if (keywords) doc.setKeywords(keywords) return doc.save() } /** Stored (Flate) size of the first `/EmbeddedFile` stream of a saved PDF. */ export async function storedAttachmentSize(bytes: Uint8Array): Promise { const doc = await PDFDocument.load(bytes) for (const [, object] of doc.context.enumerateIndirectObjects()) { if (!(object instanceof PDFRawStream)) continue const type = object.dict.lookup(PDFName.of('Type')) if (type === PDFName.of('EmbeddedFile')) return object.contents.length } throw new Error('no EmbeddedFile stream') }