Skip to content

A fast, helpful, and open-source document parser

feat: add opt-in embedded image detection via PDFium

saravananravi0879dcf5987ce3
diff --git a/cli/parse.ts b/cli/parse.ts
index b5ee4c6..38a1a55 100644
--- a/cli/parse.ts
+++ b/cli/parse.ts
@@ -26,6 +26,7 @@ interface ParseCommandOptions {
dpi?: string;
preciseBbox?: boolean;
preserveSmallText?: boolean;
+ detectImages?: boolean;
password?: string;
config?: string;
quiet?: boolean;
@@ -81,6 +82,7 @@ program
.option("--dpi <dpi>", "DPI for rendering", DEFAULT_DPI.toString())
.option("--no-precise-bbox", "Disable precise bounding boxes")
.option("--preserve-small-text", "Preserve very small text")
+ .option("--detect-images", "Detect embedded images (logos, photos, charts) via PDFium")
.option("--password <password>", "Password for encrypted/protected documents")
.option("--config <file>", "Config file (JSON)")
.option("-q, --quiet", "Suppress progress output")
@@ -125,6 +127,7 @@ program
dpi: parseInt(options.dpi || DEFAULT_DPI.toString()),
preciseBoundingBox: options.preciseBbox !== false,
preserveVerySmallText: options.preserveSmallText || false,
+ detectImages: options.detectImages || false,
password: options.password,
};
diff --git a/src/core/config.ts b/src/core/config.ts
index a9bc5e8..902c140 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -21,6 +21,7 @@ export const DEFAULT_CONFIG: LiteParseConfig = {
preserveVerySmallText: false,
preserveLayoutAlignmentAcrossPages: false,
password: undefined,
+ detectImages: false,
};
export function mergeConfig(userConfig: Partial<LiteParseConfig>): LiteParseConfig {
diff --git a/src/core/parser.ts b/src/core/parser.ts
index 8b0cca6..0ea984f 100644
--- a/src/core/parser.ts
+++ b/src/core/parser.ts
@@ -70,7 +70,7 @@ export class LiteParse {
this.config = mergeConfig(userConfig);
// Initialize PDF engine
- this.pdfEngine = new PdfJsEngine();
+ this.pdfEngine = new PdfJsEngine({ detectImages: this.config.detectImages });
// Initialize OCR engine
// Auto-detect: use HTTP OCR if URL provided, otherwise use Tesseract
diff --git a/src/core/types.ts b/src/core/types.ts
index e9ea6cc..87b275c 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -136,6 +136,15 @@ export interface LiteParseConfig {
* @defaultValue `undefined`
*/
password?: string;
+
+ /**
+ * Detect embedded images (logos, photos, charts) using PDFium and populate
+ * the `images` array on each page. When enabled, this also allows OCR to
+ * trigger on pages that contain images but have sufficient native text.
+ *
+ * @defaultValue `false`
+ */
+ detectImages: boolean;
}
/**
diff --git a/src/engines/pdf/pdfium-renderer.ts b/src/engines/pdf/pdfium-renderer.ts
index 697ea5e..2b4f293 100644
--- a/src/engines/pdf/pdfium-renderer.ts
+++ b/src/engines/pdf/pdfium-renderer.ts
@@ -69,6 +69,92 @@ export class PdfiumRenderer {
}
}
+ /**
+ * Extract bounding boxes of all embedded images on a page.
+ * Uses PDFium's low-level WASM API to iterate page objects and read image bounds.
+ * Returns coordinates in viewport space (Y-down, origin top-left) in PDF points.
+ */
+ async extractImageBounds(
+ pdfInput: string | Buffer | Uint8Array,
+ 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);
+
+ try {
+ const page = document.getPage(pageNumber - 1);
+ const results: Array<{ x: number; y: number; width: number; height: number }> = [];
+
+ // Access the underlying WASM module for low-level bound queries
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const mod = (page as any).module;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const pagePtr = (page as any).pageIdx;
+
+ if (!mod || !mod._FPDFPageObj_GetBounds) {
+ return results;
+ }
+
+ // Get page dimensions via WASM (getSize() is private in typings)
+ const pageWidth: number = mod._FPDF_GetPageWidthF(pagePtr);
+ const pageHeight: number = mod._FPDF_GetPageHeightF(pagePtr);
+
+ // Iterate page objects looking for images
+ for (const obj of page.objects()) {
+ if (obj.type !== "image") continue;
+
+ // objectIdx is the WASM object handle/pointer directly
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const objHandle = (obj as any).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);
+ if (!ok) continue;
+
+ const buf = mod.HEAPU8.buffer;
+ const view = new DataView(buf);
+ const left = view.getFloat32(ptr, true);
+ const bottom = view.getFloat32(ptr + 4, true);
+ const right = view.getFloat32(ptr + 8, true);
+ const top = view.getFloat32(ptr + 12, true);
+
+ const w = right - left;
+ const h = top - bottom;
+
+ // Filter out tiny images (< 10pt) and full-page backgrounds (> 90% coverage)
+ if (w < 10 || h < 10) continue;
+ if (w > pageWidth * 0.9 && h > pageHeight * 0.9) continue;
+
+ // Convert PDF coords (Y-up) to viewport coords (Y-down)
+ results.push({
+ x: left,
+ y: pageHeight - top,
+ width: w,
+ height: h,
+ });
+ } finally {
+ mod._free(ptr);
+ }
+ }
+
+ return results;
+ } finally {
+ document.destroy();
+ }
+ }
+
async close(): Promise<void> {
// PDFium WASM doesn't need explicit cleanup
if (this.pdfium) {
diff --git a/src/engines/pdf/pdfjs.ts b/src/engines/pdf/pdfjs.ts
index 84f1913..2b4542d 100644
--- a/src/engines/pdf/pdfjs.ts
+++ b/src/engines/pdf/pdfjs.ts
@@ -432,6 +432,11 @@ export class PdfJsEngine implements PdfEngine {
private pdfiumRenderer: PdfiumRenderer | null = null;
private currentPdfPath: string | null = null;
private currentPdfData: Uint8Array | null = null;
+ private detectImages: boolean;
+
+ constructor(options?: { detectImages?: boolean }) {
+ this.detectImages = options?.detectImages ?? false;
+ }
async loadDocument(input: string | Uint8Array, password?: string): Promise<PdfDocument> {
let data: Uint8Array;
@@ -598,7 +603,24 @@ export class PdfJsEngine implements PdfEngine {
});
}
- const images: Image[] = [];
+ let images: Image[] = [];
+ if (this.detectImages) {
+ try {
+ if (!this.pdfiumRenderer) {
+ this.pdfiumRenderer = new PdfiumRenderer();
+ }
+ const pdfInput = this.currentPdfPath || this.currentPdfData || doc.data;
+ const imageBounds = await this.pdfiumRenderer.extractImageBounds(pdfInput, pageNum);
+ images = imageBounds.map((bounds) => ({
+ x: bounds.x,
+ y: bounds.y,
+ width: bounds.width,
+ height: bounds.height,
+ }));
+ } catch {
+ // Image extraction is best-effort
+ }
+ }
// Skip annotation extraction - not currently used in processing pipeline
// Can be re-enabled if needed for link extraction, etc.