56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
import { AFRelationship, PDFDocument } from 'pdf-lib'
|
|
import { findEmbeddedFiles } from '../../src'
|
|
|
|
/**
|
|
* Crafted PDFs for the read tests, built with pdf-lib's own attach. Saved
|
|
* without object streams by default, like the export since BLK-009; pass
|
|
* `objectStreams: true` for the pre-BLK-009 layout (Filespec and Info
|
|
* packed into an `/ObjStm`, invisible to the byte scan).
|
|
*/
|
|
export interface CraftOptions {
|
|
keywords?: string[]
|
|
before?: [string, unknown]
|
|
objectStreams?: boolean
|
|
}
|
|
|
|
export async function pdfWithAttachment(
|
|
name: string,
|
|
payload: unknown,
|
|
extra: CraftOptions = {},
|
|
): Promise<Uint8Array> {
|
|
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({ useObjectStreams: extra.objectStreams ?? false })
|
|
}
|
|
|
|
async function attachJson(
|
|
doc: PDFDocument,
|
|
name: string,
|
|
payload: unknown,
|
|
): Promise<void> {
|
|
await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, {
|
|
mimeType: 'application/json',
|
|
afRelationship: AFRelationship.Data,
|
|
})
|
|
}
|
|
|
|
export async function pdfWithoutAttachment(
|
|
keywords?: string[],
|
|
objectStreams = false,
|
|
): Promise<Uint8Array> {
|
|
const doc = await PDFDocument.create()
|
|
doc.addPage()
|
|
if (keywords) doc.setKeywords(keywords)
|
|
return doc.save({ useObjectStreams: objectStreams })
|
|
}
|
|
|
|
/** Stored (Flate) size of the first `/EmbeddedFile` stream of a saved PDF, by the byte scan. */
|
|
export function storedAttachmentSize(bytes: Uint8Array): number {
|
|
const [first] = findEmbeddedFiles(bytes)
|
|
if (!first) throw new Error('no EmbeddedFile stream')
|
|
return first.length
|
|
}
|