Skip to content

A fast, helpful, and open-source document parser

perf: cache PDFium document across page operations

AdemBoukhris457260a3377718b
diff --git a/src/core/parser.test.ts b/src/core/parser.test.ts
index 09c7603..5014d0c 100644
--- a/src/core/parser.test.ts
+++ b/src/core/parser.test.ts
@@ -456,6 +456,8 @@ vi.mock("../engines/pdf/pdfium-renderer.js", async () => {
class {
constructor() {}
+ loadDocument = vi.fn(async () => {});
+ closeDocument = vi.fn();
renderPageToBuffer = vi.fn(async () => Buffer.from(new Uint8Array([1, 2, 3, 4, 5])));
close = vi.fn(async () => {});
}
diff --git a/src/core/parser.ts b/src/core/parser.ts
index a5fae47..c1550bb 100644
--- a/src/core/parser.ts
+++ b/src/core/parser.ts
@@ -298,6 +298,7 @@ export class LiteParse {
const pages = pageNumbers || Array.from({ length: totalPages }, (_, i) => i + 1);
const renderer = new PdfiumRenderer();
+ await renderer.loadDocument(rendererInput, this.config.password);
try {
for (const pageNum of pages) {
diff --git a/src/engines/pdf/pdfium-renderer.test.ts b/src/engines/pdf/pdfium-renderer.test.ts
index ba9a7e5..7da4ee2 100644
--- a/src/engines/pdf/pdfium-renderer.test.ts
+++ b/src/engines/pdf/pdfium-renderer.test.ts
@@ -1,4 +1,4 @@
-import { vi, describe, it, expect } from "vitest";
+import { vi, describe, it, expect, beforeEach } from "vitest";
import { PdfiumRenderer } from "./pdfium-renderer";
const mockPDFiumPageRender = {
@@ -22,16 +22,12 @@ const mockPdfiumDoc = {
destroy: vi.fn(),
};
+const mockLoadDocument = vi.fn(async () => mockPdfiumDoc);
+
const mockPdfiumLibrary = {
- loadDocument: vi
- .fn()
- .mockImplementationOnce(async () => {
- return mockPdfiumDoc;
- })
- .mockImplementationOnce(async () => {
- throw new Error("loading error");
- }),
+ loadDocument: mockLoadDocument,
close: vi.fn(async () => {}),
+ destroy: vi.fn(),
};
vi.mock("fs", async () => {
@@ -58,21 +54,19 @@ vi.mock("@hyzyla/pdfium", async () => {
return mockPdfiumLibrary;
}
- // implement these just to be on the safe side
- loadDocument = vi
- .fn()
- .mockImplementationOnce(async () => {
- return mockPdfiumDoc;
- })
- .mockImplementationOnce(async () => {
- throw new Error("loading error");
- });
+ loadDocument = mockLoadDocument;
close = vi.fn(async () => {});
+ destroy = vi.fn();
}
),
};
});
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockLoadDocument.mockImplementation(async () => mockPdfiumDoc);
+});
+
describe("test renderPageToBuffer", () => {
it("test success", async () => {
const renderer = new PdfiumRenderer();
@@ -81,7 +75,60 @@ describe("test renderPageToBuffer", () => {
});
it("test error propagation", async () => {
+ mockLoadDocument.mockImplementationOnce(async () => {
+ throw new Error("loading error");
+ });
const renderer = new PdfiumRenderer();
await expect(renderer.renderPageToBuffer("test.pdf", 1)).rejects.toThrow("loading error");
});
});
+
+describe("document caching", () => {
+ it("loadDocument caches and reuses the document across multiple renderPageToBuffer calls", async () => {
+ const renderer = new PdfiumRenderer();
+ await renderer.loadDocument("test.pdf");
+
+ expect(mockLoadDocument).toHaveBeenCalledTimes(1);
+
+ await renderer.renderPageToBuffer("test.pdf", 1);
+ await renderer.renderPageToBuffer("test.pdf", 2);
+ await renderer.renderPageToBuffer("test.pdf", 3);
+
+ // loadDocument was only called once (during the explicit loadDocument call),
+ // not again for each renderPageToBuffer
+ expect(mockLoadDocument).toHaveBeenCalledTimes(1);
+ expect(mockPdfiumDoc.destroy).not.toHaveBeenCalled();
+
+ await renderer.close();
+ expect(mockPdfiumDoc.destroy).toHaveBeenCalledTimes(1);
+ });
+
+ it("without loadDocument, each call creates and destroys a temporary document", async () => {
+ const renderer = new PdfiumRenderer();
+
+ await renderer.renderPageToBuffer("test.pdf", 1);
+ await renderer.renderPageToBuffer("test.pdf", 2);
+
+ // Each call loads its own document
+ expect(mockLoadDocument).toHaveBeenCalledTimes(2);
+ // Each call destroys its temporary document
+ expect(mockPdfiumDoc.destroy).toHaveBeenCalledTimes(2);
+ });
+
+ it("closeDocument destroys cached document", async () => {
+ const renderer = new PdfiumRenderer();
+ await renderer.loadDocument("test.pdf");
+
+ expect(mockPdfiumDoc.destroy).not.toHaveBeenCalled();
+ renderer.closeDocument();
+ expect(mockPdfiumDoc.destroy).toHaveBeenCalledTimes(1);
+ });
+
+ it("close() also cleans up cached document", async () => {
+ const renderer = new PdfiumRenderer();
+ await renderer.loadDocument("test.pdf");
+
+ await renderer.close();
+ expect(mockPdfiumDoc.destroy).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/engines/pdf/pdfium-renderer.ts b/src/engines/pdf/pdfium-renderer.ts
index 80b17b9..dcfdcc0 100644
--- a/src/engines/pdf/pdfium-renderer.ts
+++ b/src/engines/pdf/pdfium-renderer.ts
@@ -1,4 +1,4 @@
-import { PDFiumLibrary, type PDFiumPageRenderOptions } from "@hyzyla/pdfium";
+import { PDFiumLibrary, PDFiumDocument, type PDFiumPageRenderOptions } from "@hyzyla/pdfium";
import sharp from "sharp";
import { promises as fs } from "fs";
@@ -39,6 +39,7 @@ interface PdfiumPageInternal {
*/
export class PdfiumRenderer {
private pdfium: PDFiumLibrary | null = null;
+ private cachedDocument: PDFiumDocument | null = null;
async init(): Promise<void> {
if (!this.pdfium) {
@@ -46,33 +47,55 @@ export class PdfiumRenderer {
}
}
- async renderPageToBuffer(
+ /**
+ * Pre-load a PDF document so that subsequent per-page calls
+ * (`renderPageToBuffer`, `extractImageBounds`) reuse it instead
+ * of re-parsing the file on every invocation.
+ */
+ async loadDocument(
pdfInput: string | Buffer | Uint8Array,
- pageNumber: number,
- dpi: number = 150,
password?: string
- ): Promise<Buffer> {
+ ): Promise<void> {
await this.init();
+ this.closeDocument();
+ const pdfBuffer =
+ typeof pdfInput === "string" ? await fs.readFile(pdfInput) : Buffer.from(pdfInput);
+ this.cachedDocument = await this.pdfium!.loadDocument(pdfBuffer, password);
+ }
- if (!this.pdfium) {
- throw new Error("PDFium not initialized");
+ closeDocument(): void {
+ if (this.cachedDocument) {
+ this.cachedDocument.destroy();
+ this.cachedDocument = null;
}
+ }
- // Accept file path or raw bytes
+ private async getOrLoadDocument(
+ pdfInput: string | Buffer | Uint8Array,
+ password?: string
+ ): Promise<{ document: PDFiumDocument; isTemporary: boolean }> {
+ if (this.cachedDocument) {
+ return { document: this.cachedDocument, isTemporary: false };
+ }
+ await this.init();
const pdfBuffer =
typeof pdfInput === "string" ? await fs.readFile(pdfInput) : Buffer.from(pdfInput);
+ const document = await this.pdfium!.loadDocument(pdfBuffer, password);
+ return { document, isTemporary: true };
+ }
- // Load document
- const document = await this.pdfium.loadDocument(pdfBuffer, password);
+ async renderPageToBuffer(
+ pdfInput: string | Buffer | Uint8Array,
+ pageNumber: number,
+ dpi: number = 150,
+ password?: string
+ ): Promise<Buffer> {
+ const { document, isTemporary } = await this.getOrLoadDocument(pdfInput, password);
try {
- // Get page (0-indexed in pdfium)
const page = document.getPage(pageNumber - 1);
-
- // Calculate scale from DPI (72 DPI is the default)
const scale = dpi / 72;
- // Render page using Sharp for image processing
const image = await page.render({
scale,
render: async (options: PDFiumPageRenderOptions) => {
@@ -95,8 +118,9 @@ export class PdfiumRenderer {
return Buffer.from(image.data);
} finally {
- // Clean up document
- document.destroy();
+ if (isTemporary) {
+ document.destroy();
+ }
}
}
@@ -110,20 +134,9 @@ export class PdfiumRenderer {
pageNumber: number,
password?: string
): Promise<Array<{ x: number; y: number; width: number; height: number }>> {
- await this.init();
-
- if (!this.pdfium) {
- throw new Error("PDFium not initialized");
- }
-
- const pdfBuffer =
- typeof pdfInput === "string" ? await fs.readFile(pdfInput) : Buffer.from(pdfInput);
-
- const document = await this.pdfium.loadDocument(pdfBuffer, password);
+ const { document, isTemporary } = await this.getOrLoadDocument(pdfInput, password);
try {
- // Cast to internal interface — module/pageIdx/objectIdx are private in
- // @hyzyla/pdfium typings but required for low-level WASM bound queries
const page = document.getPage(pageNumber - 1) as unknown as PdfiumPageInternal;
const results: Array<{ x: number; y: number; width: number; height: number }> = [];
@@ -134,18 +147,15 @@ export class PdfiumRenderer {
return results;
}
- // Get page dimensions via WASM (getSize() is private in typings)
const pageWidth = mod._FPDF_GetPageWidthF(pagePtr);
const pageHeight = mod._FPDF_GetPageHeightF(pagePtr);
- // Iterate page objects looking for images
for (const obj of page.objects()) {
if (obj.type !== "image") continue;
const objHandle = obj.objectIdx;
if (!objHandle) continue;
- // Allocate memory for 4 floats (left, bottom, right, top)
const ptr = mod._malloc(16);
try {
const ok = mod._FPDFPageObj_GetBounds(objHandle, ptr, ptr + 4, ptr + 8, ptr + 12);
@@ -165,7 +175,6 @@ export class PdfiumRenderer {
if (w > pageWidth * MAX_IMAGE_PAGE_COVERAGE && h > pageHeight * MAX_IMAGE_PAGE_COVERAGE)
continue;
- // Convert PDF coords (Y-up) to viewport coords (Y-down)
results.push({
x: left,
y: pageHeight - top,
@@ -179,12 +188,14 @@ export class PdfiumRenderer {
return results;
} finally {
- document.destroy();
+ if (isTemporary) {
+ document.destroy();
+ }
}
}
async close(): Promise<void> {
- // PDFium WASM doesn't need explicit cleanup
+ this.closeDocument();
if (this.pdfium) {
this.pdfium.destroy();
this.pdfium = null;
diff --git a/src/engines/pdf/pdfjs.test.ts b/src/engines/pdf/pdfjs.test.ts
index bcdc5cf..a9cd3b0 100644
--- a/src/engines/pdf/pdfjs.test.ts
+++ b/src/engines/pdf/pdfjs.test.ts
@@ -48,7 +48,10 @@ vi.mock("./pdfium-renderer.js", async () => {
class {
constructor() {}
+ loadDocument = vi.fn().mockResolvedValue(undefined);
+ closeDocument = vi.fn();
renderPageToBuffer = vi.fn().mockResolvedValue(Buffer.from("this is a page"));
+ close = vi.fn().mockResolvedValue(undefined);
}
),
};
diff --git a/src/engines/pdf/pdfjs.ts b/src/engines/pdf/pdfjs.ts
index 06001c2..dd5d5c5 100644
--- a/src/engines/pdf/pdfjs.ts
+++ b/src/engines/pdf/pdfjs.ts
@@ -601,10 +601,11 @@ export class PdfJsEngine implements PdfEngine {
let images: Image[] = [];
try {
+ const pdfInput = this.currentPdfPath || this.currentPdfData || doc.data;
if (!this.pdfiumRenderer) {
this.pdfiumRenderer = new PdfiumRenderer();
+ await this.pdfiumRenderer.loadDocument(pdfInput);
}
- const pdfInput = this.currentPdfPath || this.currentPdfData || doc.data;
const imageBounds = await this.pdfiumRenderer.extractImageBounds(pdfInput, pageNum);
images = imageBounds.map((bounds) => ({
x: bounds.x,
@@ -667,16 +668,16 @@ export class PdfJsEngine implements PdfEngine {
dpi: number,
password?: string
): Promise<Buffer> {
- if (!this.pdfiumRenderer) {
- this.pdfiumRenderer = new PdfiumRenderer();
- }
-
- // Use file path when available, otherwise pass buffer directly
const pdfInput = this.currentPdfPath || this.currentPdfData;
if (!pdfInput) {
throw new Error("No PDF path or data available for rendering");
}
+ if (!this.pdfiumRenderer) {
+ this.pdfiumRenderer = new PdfiumRenderer();
+ await this.pdfiumRenderer.loadDocument(pdfInput, password);
+ }
+
return await this.pdfiumRenderer.renderPageToBuffer(pdfInput, pageNum, dpi, password);
}