A fast, helpful, and open-source document parser
[Feat] add support for --pasword option. Work on all doc types and cli/api use
Pierre-Loic doulcetc01c45ff00f9
diff --git a/README.md b/README.mdindex c7da9ac..5bdc12c 100644--- a/README.md+++ b/README.md@@ -191,6 +191,7 @@ Options:--dpi <dpi> DPI for rendering (default: "150")--no-precise-bbox Disable precise bounding boxes--preserve-small-text Preserve very small text+ --password <password> Password for encrypted/protected documents--config <file> Config file (JSON)-q, --quiet Suppress progress output-h, --help display help for command@@ -215,6 +216,7 @@ Options:--no-precise-bbox Disable precise bounding boxes--recursive Recursively search input directory--extension <ext> Only process files with this extension (e.g., ".pdf")+ --password <password> Password for encrypted/protected documents (applied to all files)--config <file> Config file (JSON)-q, --quiet Suppress progress output-h, --help display help for command@@ -233,6 +235,7 @@ Options:--target-pages <pages> Page numbers to screenshot (e.g., "1,3,5" or "1-5")--dpi <dpi> DPI for rendering (default: "150")--format <format> Image format: png|jpg (default: "png")+ --password <password> Password for encrypted/protected documents--config <file> Config file (JSON)-q, --quiet Suppress progress output-h, --help display help for command@@ -349,7 +352,8 @@ Create a `liteparse.config.json` file:"dpi": 150,"outputFormat": "json","preciseBoundingBox": true,- "preserveVerySmallText": false+ "preserveVerySmallText": false,+ "password": "optional_password"}```diff --git a/cli/README.md b/cli/README.mdindex f10d0ca..5b29a98 100644--- a/cli/README.md+++ b/cli/README.md@@ -35,7 +35,8 @@ Both commands accept `--config <file>` to load settings from JSON:"maxPages": 100,"dpi": 200,"outputFormat": "json",- "preciseBoundingBox": true+ "preciseBoundingBox": true,+ "password": "optional_password"}```diff --git a/cli/parse.ts b/cli/parse.tsindex 975f398..2f7fbee 100644--- a/cli/parse.ts+++ b/cli/parse.ts@@ -26,6 +26,7 @@ interface ParseCommandOptions {dpi?: string;preciseBbox?: boolean;preserveSmallText?: boolean;+ password?: string;config?: string;quiet?: boolean;}@@ -35,6 +36,7 @@ interface ScreenshotCommandOptions {targetPages?: string;dpi?: string;format?: string;+ password?: string;config?: string;quiet?: boolean;}@@ -50,6 +52,7 @@ interface BatchParseCommandOptions {preciseBbox?: boolean;recursive?: boolean;extension?: string;+ password?: string;config?: string;quiet?: boolean;}@@ -78,6 +81,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("--password <password>", "Password for encrypted/protected documents").option("--config <file>", "Config file (JSON)").option("-q, --quiet", "Suppress progress output").action(async (file: string, options: ParseCommandOptions) => {@@ -120,6 +124,7 @@ programdpi: parseInt(options.dpi || DEFAULT_DPI.toString()),preciseBoundingBox: options.preciseBbox !== false,preserveVerySmallText: options.preserveSmallText || false,+ password: options.password,};// Create parser@@ -168,6 +173,7 @@ program.option("--target-pages <pages>", 'Page numbers to screenshot (e.g., "1,3,5" or "1-5")').option("--dpi <dpi>", "DPI for rendering", DEFAULT_DPI.toString()).option("--format <format>", "Image format: png|jpg", DEFAULT_SCREENSHOT_FORMAT)+ .option("--password <password>", "Password for encrypted/protected documents").option("--config <file>", "Config file (JSON)").option("-q, --quiet", "Suppress progress output").action(async (file: string, options: ScreenshotCommandOptions) => {@@ -196,6 +202,7 @@ programconfig = {...config,dpi: parseInt(options.dpi || DEFAULT_DPI.toString()),+ password: options.password,};// Parse target pages@@ -299,6 +306,7 @@ program.option("--no-precise-bbox", "Disable precise bounding boxes").option("--recursive", "Recursively search input directory").option("--extension <ext>", 'Only process files with this extension (e.g., ".pdf")')+ .option("--password <password>", "Password for encrypted/protected documents (applied to all files)").option("--config <file>", "Config file (JSON)").option("-q, --quiet", "Suppress progress output").action(async (inputDir: string, outputDir: string, options: BatchParseCommandOptions) => {@@ -362,6 +370,7 @@ programmaxPages: parseInt(options.maxPages || DEFAULT_MAX_PAGES.toString()),dpi: parseInt(options.dpi || DEFAULT_DPI.toString()),preciseBoundingBox: options.preciseBbox !== false,+ password: options.password,};// Create a SINGLE parser instance for all files (key for batch efficiency)diff --git a/docs/src/content/docs/liteparse/cli-reference.md b/docs/src/content/docs/liteparse/cli-reference.mdindex 9554aa9..c0fd208 100644--- a/docs/src/content/docs/liteparse/cli-reference.md+++ b/docs/src/content/docs/liteparse/cli-reference.md@@ -36,6 +36,7 @@ lit parse [options] <file>| `--dpi <dpi>` | Rendering DPI | `150` || `--no-precise-bbox` | Disable precise bounding boxes | — || `--preserve-small-text` | Keep very small text | — |+| `--password <password>` | Password for encrypted/protected documents | — || `--config <file>` | JSON config file path | — || `-q, --quiet` | Suppress progress output | — |@@ -92,6 +93,7 @@ lit batch-parse [options] <input-dir> <output-dir>| `--no-precise-bbox` | Disable precise bounding boxes | — || `--recursive` | Search subdirectories | — || `--extension <ext>` | Only process this extension (e.g., `".pdf"`) | — (all supported) |+| `--password <password>` | Password for encrypted/protected documents (applied to all files) | — || `--config <file>` | JSON config file path | — || `-q, --quiet` | Suppress progress output | — |@@ -135,6 +137,7 @@ lit screenshot [options] <file>| `--target-pages <pages>` | Pages to screenshot (e.g., `"1,3,5"` or `"1-5"`) | — (all pages) || `--dpi <dpi>` | Rendering DPI | `150` || `--format <format>` | Image format: `png` or `jpg` | `png` |+| `--password <password>` | Password for encrypted/protected documents | — || `--config <file>` | JSON config file path | — || `-q, --quiet` | Suppress progress output | — |diff --git a/docs/src/content/docs/liteparse/guides/library-usage.md b/docs/src/content/docs/liteparse/guides/library-usage.mdindex 7c70b43..8ee09fc 100644--- a/docs/src/content/docs/liteparse/guides/library-usage.md+++ b/docs/src/content/docs/liteparse/guides/library-usage.md@@ -59,6 +59,7 @@ const parser = new LiteParse({dpi: 300,outputFormat: "json",targetPages: "1-10",+ password: "secret", // for encrypted/protected documents});```@@ -157,6 +158,7 @@ parser = LiteParse(ocr_server_url="http://localhost:8828/ocr",ocr_language="fra",dpi=300,+ password="secret", # for encrypted/protected documents)# Per-call optionsdiff --git a/package-lock.json b/package-lock.jsonindex 7810002..6a4b5e4 100644--- a/package-lock.json+++ b/package-lock.json@@ -2176,6 +2176,7 @@"integrity": "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"undici-types": "~6.21.0"}@@ -2231,6 +2232,7 @@"integrity": "sha512-IgSWvLobTDOjnaxAfDTIHaECbkNlAlKv2j5SjpB2v7QHKv1FIfjwMy8FsDbVfDX/KjmCmYICcw7uGaXLhtsLNg==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "8.56.0","@typescript-eslint/types": "8.56.0",@@ -2566,6 +2568,7 @@"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","dev": true,"license": "MIT",+ "peer": true,"bin": {"acorn": "bin/acorn"},@@ -3056,6 +3059,7 @@"integrity": "sha512-O0piBKY36YSJhlFSG8p9VUdPV/SxxS4FYDWVpr/9GJuMaepzwlf4J8I4ov1b+ySQfDTPhc3DtLaxcT1fN0yqCg==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.8.0","@eslint-community/regexpp": "^4.12.2",@@ -3112,6 +3116,7 @@"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==","dev": true,"license": "MIT",+ "peer": true,"bin": {"eslint-config-prettier": "bin/cli.js"},@@ -4319,6 +4324,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -4381,6 +4387,7 @@"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==","dev": true,"license": "MIT",+ "peer": true,"bin": {"prettier": "bin/prettier.cjs"},@@ -5052,6 +5059,7 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","dev": true,"license": "Apache-2.0",+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -5195,6 +5203,7 @@"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.27.0","fdir": "^6.5.0",diff --git a/src/conversion/convertToPdf.ts b/src/conversion/convertToPdf.tsindex 4fb016b..2183586 100644--- a/src/conversion/convertToPdf.ts+++ b/src/conversion/convertToPdf.ts@@ -235,7 +235,7 @@ export async function findImageMagickCommand(): Promise<{/*** Convert office documents using LibreOffice*/-export async function convertOfficeDocument(filePath: string, outputDir: string): Promise<string> {+export async function convertOfficeDocument(filePath: string, outputDir: string, password?: string): Promise<string> {const libreOfficeCmd = await findLibreOfficeCommand();if (!libreOfficeCmd) {throw new Error(@@ -243,9 +243,15 @@ export async function convertOfficeDocument(filePath: string, outputDir: string));}+ const args = ["--headless", "--invisible", "--convert-to", "pdf", "--outdir", outputDir];+ if (password) {+ args.push(`--infilter=:${password}`);+ }+ args.push(filePath);+await executeCommand(libreOfficeCmd,- ["--headless", "--invisible", "--convert-to", "pdf", "--outdir", outputDir, filePath],+ args,120000 // 2 minutes timeout);@@ -331,7 +337,8 @@ export async function convertImageToPdf(filePath: string, outputDir: string): Pr* Main conversion function*/export async function convertToPdf(- filePath: string+ filePath: string,+ password?: string): Promise<ConversionResult | ConversionPassthrough | ConversionError> {try {// Check if file exists@@ -362,9 +369,9 @@ export async function convertToPdf(let pdfPath: string;if (officeExtensions.includes(extension)) {- pdfPath = await convertOfficeDocument(filePath, tmpDir);+ pdfPath = await convertOfficeDocument(filePath, tmpDir, password);} else if (spreadsheetExtensions.includes(extension)) {- pdfPath = await convertOfficeDocument(filePath, tmpDir);+ pdfPath = await convertOfficeDocument(filePath, tmpDir, password);} else if (imageExtensions.includes(extension)) {pdfPath = await convertImageToPdf(filePath, tmpDir);} else {@@ -419,7 +426,8 @@ export async function guessExtensionFromBuffer(data: Buffer | Uint8Array): Promi* For PDF buffers, callers should skip this and pass data directly to the PDF engine.*/export async function convertBufferToPdf(- data: Buffer | Uint8Array+ data: Buffer | Uint8Array,+ password?: string): Promise<ConversionResult | ConversionPassthrough | ConversionError> {const ext = await guessExtensionFromBuffer(data);@@ -428,5 +436,5 @@ export async function convertBufferToPdf(const tmpPath = path.join(tmpDir, `input${ext}`);await fs.writeFile(tmpPath, data);- return convertToPdf(tmpPath);+ return convertToPdf(tmpPath, password);}diff --git a/src/core/config.ts b/src/core/config.tsindex b6bd793..a9bc5e8 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -20,6 +20,7 @@ export const DEFAULT_CONFIG: LiteParseConfig = {preciseBoundingBox: true,preserveVerySmallText: false,preserveLayoutAlignmentAcrossPages: false,+ password: undefined,};export function mergeConfig(userConfig: Partial<LiteParseConfig>): LiteParseConfig {diff --git a/src/core/parser.ts b/src/core/parser.tsindex 3594ad9..62df4e1 100644--- a/src/core/parser.ts+++ b/src/core/parser.ts@@ -108,7 +108,7 @@ export class LiteParse {if (typeof input === "string") {log(`Processing file: ${input}`);- const conversionResult = await convertToPdf(input);+ const conversionResult = await convertToPdf(input, this.config.password);if ("code" in conversionResult) {throw new Error(`Conversion failed: ${conversionResult.message}`);@@ -126,7 +126,7 @@ export class LiteParse {log(`Converted ${conversionResult.originalExtension} to PDF`);}- doc = await this.pdfEngine.loadDocument(pdfPath);+ doc = await this.pdfEngine.loadDocument(pdfPath, this.config.password);} else {log(`Processing buffer input (${input.byteLength} bytes)`);const ext = await guessExtensionFromBuffer(input);@@ -134,10 +134,10 @@ export class LiteParse {if (ext === ".pdf") {// Zero-disk path: pass bytes directly to the PDF engineconst data = input instanceof Uint8Array ? input : new Uint8Array(input);- doc = await this.pdfEngine.loadDocument(data);+ doc = await this.pdfEngine.loadDocument(data, this.config.password);} else {// Non-PDF buffer: write to temp file for conversion- const conversionResult = await convertBufferToPdf(input);+ const conversionResult = await convertBufferToPdf(input, this.config.password);if ("code" in conversionResult) {throw new Error(`Conversion failed: ${conversionResult.message}`);@@ -151,7 +151,7 @@ export class LiteParse {needsCleanup = true;cleanupPath = conversionResult.pdfPath;log(`Converted ${conversionResult.originalExtension} buffer to PDF`);- doc = await this.pdfEngine.loadDocument(conversionResult.pdfPath);+ doc = await this.pdfEngine.loadDocument(conversionResult.pdfPath, this.config.password);}}@@ -236,7 +236,7 @@ export class LiteParse {log(`Generating screenshots for: ${typeof input === "string" ? input : "<buffer>"}`);// Load PDF document to get page count and dimensions- const doc = await this.pdfEngine.loadDocument(input as string | Uint8Array);+ const doc = await this.pdfEngine.loadDocument(input as string | Uint8Array, this.config.password);const totalPages = doc.numPages;// Determine the input to pass to the renderer (file path or buffer)@@ -325,7 +325,7 @@ export class LiteParse {try {// Render page as image buffer- const imageBuffer = await this.pdfEngine.renderPageImage(doc, page.pageNum, this.config.dpi);+ const imageBuffer = await this.pdfEngine.renderPageImage(doc, page.pageNum, this.config.dpi, this.config.password);// Run OCR directly on the buffer (no temp file needed)log(` OCR on page ${page.pageNum}...`);diff --git a/src/core/types.ts b/src/core/types.tsindex 5a51d4b..6156f6e 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -125,6 +125,14 @@ export interface LiteParseConfig {* @defaultValue `false`*/preserveLayoutAlignmentAcrossPages: boolean;++ /**+ * Password for opening encrypted/protected documents.+ * Used for password-protected PDFs and office documents.+ *+ * @defaultValue `undefined`+ */+ password?: string;}/**diff --git a/src/engines/pdf/interface.ts b/src/engines/pdf/interface.tsindex 79d04bf..602a412 100644--- a/src/engines/pdf/interface.ts+++ b/src/engines/pdf/interface.ts@@ -2,10 +2,10 @@ import { TextItem } from "../../core/types.js";export interface PdfEngine {name: string;- loadDocument(input: string | Uint8Array): Promise<PdfDocument>;+ loadDocument(input: string | Uint8Array, password?: string): Promise<PdfDocument>;extractPage(doc: PdfDocument, pageNum: number): Promise<PageData>;extractAllPages(doc: PdfDocument, maxPages?: number, targetPages?: string): Promise<PageData[]>;- renderPageImage(doc: PdfDocument, pageNum: number, dpi: number): Promise<Buffer>;+ renderPageImage(doc: PdfDocument, pageNum: number, dpi: number, password?: string): Promise<Buffer>;close(doc: PdfDocument): Promise<void>;}diff --git a/src/engines/pdf/pdfium-renderer.ts b/src/engines/pdf/pdfium-renderer.tsindex c9ec56b..697ea5e 100644--- a/src/engines/pdf/pdfium-renderer.ts+++ b/src/engines/pdf/pdfium-renderer.ts@@ -18,7 +18,8 @@ export class PdfiumRenderer {async renderPageToBuffer(pdfInput: string | Buffer | Uint8Array,pageNumber: number,- dpi: number = 150+ dpi: number = 150,+ password?: string): Promise<Buffer> {await this.init();@@ -31,7 +32,7 @@ export class PdfiumRenderer {typeof pdfInput === "string" ? await fs.readFile(pdfInput) : Buffer.from(pdfInput);// Load document- const document = await this.pdfium.loadDocument(pdfBuffer);+ const document = await this.pdfium.loadDocument(pdfBuffer, password);try {// Get page (0-indexed in pdfium)diff --git a/src/engines/pdf/pdfjs.ts b/src/engines/pdf/pdfjs.tsindex 280cffd..a692180 100644--- a/src/engines/pdf/pdfjs.ts+++ b/src/engines/pdf/pdfjs.ts@@ -433,7 +433,7 @@ export class PdfJsEngine implements PdfEngine {private currentPdfPath: string | null = null;private currentPdfData: Uint8Array | null = null;- async loadDocument(input: string | Uint8Array): Promise<PdfDocument> {+ async loadDocument(input: string | Uint8Array, password?: string): Promise<PdfDocument> {let data: Uint8Array;if (typeof input === "string") {data = new Uint8Array(await fs.readFile(input));@@ -449,12 +449,27 @@ export class PdfJsEngine implements PdfEngine {const loadingTask = getDocument({data,+ password,cMapUrl: CMAP_URL,cMapPacked: CMAP_PACKED,standardFontDataUrl: STANDARD_FONT_DATA_URL,});- const pdfDocument = await loadingTask.promise;+ let pdfDocument: PdfJsDocument;+ try {+ pdfDocument = await loadingTask.promise;+ } catch (error: unknown) {+ const message = error instanceof Error ? error.message : String(error);+ if (message.includes("password") || message.includes("Password")) {+ if (password) {+ throw new Error("Incorrect password for this PDF. Please check the password and try again.");+ } else {+ throw new Error("This PDF is password-protected. Use --password <password> to provide the document password.");+ }+ }+ throw error;+ }+const metadata = await pdfDocument.getMetadata();return {@@ -624,7 +639,7 @@ export class PdfJsEngine implements PdfEngine {return pages;}- async renderPageImage(_doc: PdfDocument, pageNum: number, dpi: number): Promise<Buffer> {+ async renderPageImage(_doc: PdfDocument, pageNum: number, dpi: number, password?: string): Promise<Buffer> {if (!this.pdfiumRenderer) {this.pdfiumRenderer = new PdfiumRenderer();}@@ -635,7 +650,7 @@ export class PdfJsEngine implements PdfEngine {throw new Error("No PDF path or data available for rendering");}- return await this.pdfiumRenderer.renderPageToBuffer(pdfInput, pageNum, dpi);+ return await this.pdfiumRenderer.renderPageToBuffer(pdfInput, pageNum, dpi, password);}async close(doc: PdfDocument): Promise<void> {