Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions src/tools/pdf/extract-images.lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,18 @@ async function objToBlob(obj: PdfImageObj): Promise<{ blob: Blob; width: number;
const ctx = canvas.getContext('2d');
if (!ctx) return null;

if (obj.bitmap) {
canvas.width = obj.bitmap.width;
canvas.height = obj.bitmap.height;
ctx.drawImage(obj.bitmap, 0, 0);
const drawable = obj.bitmap as CanvasImageSource | undefined;
const w = obj.width || (drawable as { width?: number })?.width || 0;
const h = obj.height || (drawable as { height?: number })?.height || 0;

if (drawable && w && h) {
canvas.width = w;
canvas.height = h;
try {
ctx.drawImage(drawable, 0, 0, w, h);
} catch {
return null; // e.g. a detached ImageBitmap
}
} else if (obj.data && obj.width && obj.height) {
const { width, height, data } = obj;
const pixels = width * height;
Expand Down Expand Up @@ -79,8 +87,10 @@ function resolveObj(page: { objs: { has(n: string): boolean; get(n: string, cb?:

/** Extract every embedded raster image from the PDF bytes. */
export async function extractPdfImages(data: ArrayBuffer | Uint8Array): Promise<ExtractedImage[]> {
const pdfjs = await import('pdfjs-dist');
const PdfjsWorker = (await import('pdfjs-dist/build/pdf.worker.min.mjs?worker')).default;
// Use the legacy build: it polyfills newer JS (e.g. Uint8Array.prototype.toHex,
// which pdf.js's default build assumes) so extraction works on older browsers.
const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs');
const PdfjsWorker = (await import('pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker')).default;
const worker = new PdfjsWorker();
pdfjs.GlobalWorkerOptions.workerPort = worker;

Expand Down
Loading