@d0paminedriven/pdfdown-ocr 0.9.9 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,7 +33,7 @@ Verify with `tesseract --version` -- you should see 5.x.
33
33
 
34
34
  The package automatically detects the tessdata directory at runtime by parsing the output of `tesseract --list-langs`. The detected path is cached for the lifetime of the process using a `OnceLock<Option<String>>` -- no global environment mutation, fully thread-safe.
35
35
 
36
- **Resolution order:**
36
+ **Resolution order:**
37
37
 
38
38
  1. `TESSDATA_PREFIX` environment variable (if set, used as-is -- no auto-detection runs)
39
39
  2. Auto-detection via `tesseract --list-langs` (parses the path from `List of available languages in "/path/to/tessdata/"`)
@@ -53,106 +53,116 @@ export TESSDATA_PREFIX="/opt/custom/tessdata"
53
53
 
54
54
  ## API
55
55
 
56
- This package exports everything from `@d0paminedriven/pdfdown` (text, images, annotations, structured text, metadata -- both sync and async), plus the OCR-specific APIs below. See the [base package docs](https://www.npmjs.com/package/@d0paminedriven/pdfdown) for the full base API.
56
+ This package exports everything from `@d0paminedriven/pdfdown` (text, images, annotations, AcroForm fields, attachments, embedded e-invoice extraction, structured text, metadata -- both sync and async), plus the OCR-specific APIs below. `PdfDocumentOcr` carries the same `form`, `formFields`, `totalFormFields` and `formFieldPages` aggregates as `PdfDocument`; form extraction is read-only and needs neither Tesseract nor PDFium. See the [base package docs](https://www.npmjs.com/package/@d0paminedriven/pdfdown) for the full base API.
57
57
 
58
58
  ### OCR standalone functions
59
59
 
60
60
  ```typescript
61
61
  // Per-page OCR text extraction
62
- export declare function extractTextWithOcrPerPage(
63
- buffer: Buffer,
64
- opts?: OcrOptions,
65
- ): Array<OcrPageText>
62
+ export declare function extractTextWithOcrPerPage(buffer: Buffer, opts?: OcrOptions): Array<OcrPageText>;
66
63
 
67
- export declare function extractTextWithOcrPerPageAsync(
68
- buffer: Buffer,
69
- opts?: OcrOptions,
70
- ): Promise<Array<OcrPageText>>
64
+ export declare function extractTextWithOcrPerPageAsync(buffer: Buffer, opts?: OcrOptions): Promise<Array<OcrPageText>>;
71
65
 
72
66
  // Full document extraction with OCR text fallback
73
- export declare function pdfDocumentOcr(
74
- buffer: Buffer,
75
- opts?: OcrOptions,
76
- ): PdfDocumentOcr
77
-
78
- export declare function pdfDocumentOcrAsync(
79
- buffer: Buffer,
80
- opts?: OcrOptions,
81
- ): Promise<PdfDocumentOcr>
67
+ export declare function pdfDocumentOcr(buffer: Buffer, opts?: OcrOptions): PdfDocumentOcr;
68
+
69
+ export declare function pdfDocumentOcrAsync(buffer: Buffer, opts?: OcrOptions): Promise<PdfDocumentOcr>;
70
+
71
+ // Positioned words and lines with the same three-tier cascade
72
+ export declare function extractLayoutWithOcrPerPage(buffer: Buffer, opts?: OcrOptions): Array<PageLayout>;
73
+
74
+ export declare function extractLayoutWithOcrPerPageAsync(buffer: Buffer, opts?: OcrOptions): Promise<Array<PageLayout>>;
82
75
  ```
83
76
 
84
77
  ### `PdfDown` class (includes OCR methods)
85
78
 
86
79
  ```typescript
87
80
  export declare class PdfDown {
88
- constructor(buffer: Buffer)
81
+ constructor(buffer: Buffer); // a PDF or an .xlsx workbook
82
+ static openAsync(buffer: Buffer): Promise<PdfDown>;
83
+ readonly format: DocumentFormat; // "Pdf" | "Xlsx"
89
84
 
90
85
  // ── Base methods ──
91
- textPerPage(): Array<PageText>
92
- textPerPageAsync(): Promise<Array<PageText>>
93
- imagesPerPage(): Array<PageImage>
94
- imagesPerPageAsync(): Promise<Array<PageImage>>
95
- annotationsPerPage(): Array<PageAnnotation>
96
- annotationsPerPageAsync(): Promise<Array<PageAnnotation>>
97
- structuredText(): Array<StructuredPageText>
98
- structuredTextAsync(): Promise<Array<StructuredPageText>>
99
- metadata(): PdfMeta
100
- metadataAsync(): Promise<PdfMeta>
101
- document(): PdfDocument
102
- documentAsync(): Promise<PdfDocument>
86
+ textPerPage(): Array<PageText>;
87
+ textPerPageAsync(): Promise<Array<PageText>>;
88
+ imagesPerPage(): Array<PageImage>;
89
+ imagesPerPageAsync(): Promise<Array<PageImage>>;
90
+ annotationsPerPage(): Array<PageAnnotation>;
91
+ annotationsPerPageAsync(): Promise<Array<PageAnnotation>>;
92
+ attachments(): Array<Attachment>;
93
+ attachmentsAsync(): Promise<Array<Attachment>>;
94
+ invoice(opts?: InvoiceOptions): InvoiceResult;
95
+ invoiceAsync(opts?: InvoiceOptions): Promise<InvoiceResult>;
96
+ layout(opts?: SpreadsheetOptions): Array<PageLayout>; // a PDF ignores opts; a workbook yields one logical page per sheet
97
+ layoutAsync(opts?: SpreadsheetOptions): Promise<Array<PageLayout>>;
98
+ spreadsheetCells(opts?: SpreadsheetOptions): Array<SheetCells>; // workbooks only
99
+ spreadsheetCellsAsync(opts?: SpreadsheetOptions): Promise<Array<SheetCells>>;
100
+ structuredText(): Array<StructuredPageText>;
101
+ structuredTextAsync(): Promise<Array<StructuredPageText>>;
102
+ metadata(): PdfMeta;
103
+ metadataAsync(): Promise<PdfMeta>;
104
+ document(): PdfDocument;
105
+ documentAsync(): Promise<PdfDocument>;
106
+ formFieldsPerPage(): Array<PageFormField>;
107
+ formFieldsPerPageAsync(): Promise<Array<PageFormField>>;
103
108
 
104
109
  // ── OCR methods ──
105
- textWithOcrPerPage(opts?: OcrOptions): Array<OcrPageText>
106
- textWithOcrPerPageAsync(opts?: OcrOptions): Promise<Array<OcrPageText>>
107
- documentOcr(opts?: OcrOptions): PdfDocumentOcr
108
- documentOcrAsync(opts?: OcrOptions): Promise<PdfDocumentOcr>
110
+ textWithOcrPerPage(opts?: OcrOptions): Array<OcrPageText>;
111
+ textWithOcrPerPageAsync(opts?: OcrOptions): Promise<Array<OcrPageText>>;
112
+ documentOcr(opts?: OcrOptions): PdfDocumentOcr;
113
+ documentOcrAsync(opts?: OcrOptions): Promise<PdfDocumentOcr>;
114
+ layoutWithOcr(opts?: OcrOptions): Array<PageLayout>;
115
+ layoutWithOcrAsync(opts?: OcrOptions): Promise<Array<PageLayout>>;
109
116
  }
110
117
  ```
111
118
 
112
119
  ### Types
113
120
 
114
121
  ```typescript
115
- export const enum TextSource {
116
- Native = 'Native',
117
- Ocr = 'Ocr',
118
- }
122
+ // The deepest cascade tier that produced a page's text, or the logical page of a workbook sheet.
123
+ // Spreadsheet pages carry `PageLayout.sheet` and every word carries `TextWord.cell` ("C3").
124
+ export type TextSource = "Native" | "Ocr" | "Rendered" | "Spreadsheet";
119
125
 
120
126
  export interface OcrPageText {
121
- page: number
122
- text: string
123
- source: TextSource
127
+ page: number;
128
+ text: string;
129
+ source: TextSource;
124
130
  }
125
131
 
126
132
  export interface OcrStructuredPageText {
127
- page: number
128
- header: string
129
- body: string
130
- footer: string
131
- source: TextSource
133
+ page: number;
134
+ header: string;
135
+ body: string;
136
+ footer: string;
137
+ source: TextSource;
132
138
  }
133
139
 
134
140
  export interface OcrOptions {
135
- lang?: string // Tesseract language code, default "eng"
136
- minTextLength?: number // non-whitespace char threshold before OCR fallback, default 1
137
- maxThreads?: number // cap on Rayon threads for OCR parallelism, default 4, clamped to [1, available CPUs]
141
+ lang?: string; // Tesseract language code, default "eng"
142
+ minTextLength?: number; // non-whitespace char threshold before OCR fallback, default 1
143
+ maxThreads?: number; // cap on Rayon threads for OCR parallelism, default 4, clamped to [1, available CPUs]
138
144
  }
139
145
 
140
146
  export interface PdfDocumentOcr {
141
- version: string
142
- isLinearized: boolean
143
- pageCount: number
144
- creator?: string
145
- producer?: string
146
- creationDate?: string
147
- modificationDate?: string
148
- totalImages: number
149
- totalAnnotations: number
150
- imagePages: Array<number>
151
- annotationPages: Array<number>
152
- text: Array<OcrPageText>
153
- structuredText: Array<OcrStructuredPageText>
154
- images: Array<PageImage>
155
- annotations: Array<PageAnnotation>
147
+ version: string;
148
+ isLinearized: boolean;
149
+ pageCount: number;
150
+ creator?: string;
151
+ producer?: string;
152
+ creationDate?: string;
153
+ modificationDate?: string;
154
+ totalImages: number;
155
+ totalAnnotations: number;
156
+ imagePages: Array<number>;
157
+ annotationPages: Array<number>;
158
+ text: Array<OcrPageText>;
159
+ structuredText: Array<OcrStructuredPageText>;
160
+ images: Array<PageImage>;
161
+ annotations: Array<PageAnnotation>;
162
+ form?: FormInfo;
163
+ formFields: Array<PageFormField>;
164
+ totalFormFields: number;
165
+ formFieldPages: Array<number>;
156
166
  }
157
167
  ```
158
168
 
@@ -163,41 +173,44 @@ export interface PdfDocumentOcr {
163
173
  ### Standalone
164
174
 
165
175
  ```typescript
166
- import { readFile } from 'fs/promises'
167
- import { extractTextWithOcrPerPageAsync } from '@d0paminedriven/pdfdown-ocr'
176
+ import { readFile } from "fs/promises";
177
+
178
+ import { extractTextWithOcrPerPageAsync } from "@d0paminedriven/pdfdown-ocr";
168
179
 
169
- const pdf = await readFile('scanned-document.pdf')
170
- const pages = await extractTextWithOcrPerPageAsync(pdf, { lang: 'eng', minTextLength: 10 })
180
+ const pdf = await readFile("scanned-document.pdf");
181
+ const pages = await extractTextWithOcrPerPageAsync(pdf, { lang: "eng", minTextLength: 10 });
171
182
 
172
183
  for (const { page, text, source } of pages) {
173
- console.log(`Page ${page} [${source}]: ${text.slice(0, 100)}...`)
184
+ console.log(`Page ${page} [${source}]: ${text.slice(0, 100)}...`);
174
185
  }
175
186
  ```
176
187
 
177
188
  ### Class-based (parse once, extract many)
178
189
 
179
190
  ```typescript
180
- import { readFile } from 'fs/promises'
181
- import { PdfDown } from '@d0paminedriven/pdfdown-ocr'
191
+ import { readFile } from "fs/promises";
192
+
193
+ import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
182
194
 
183
- const pdf = new PdfDown(await readFile('scanned-document.pdf'))
195
+ const pdf = new PdfDown(await readFile("scanned-document.pdf"));
184
196
 
185
197
  // OCR text extraction
186
- const pages = await pdf.textWithOcrPerPageAsync({ lang: 'eng', minTextLength: 10 })
198
+ const pages = await pdf.textWithOcrPerPageAsync({ lang: "eng", minTextLength: 10 });
187
199
 
188
200
  // All base methods work too
189
- const images = await pdf.imagesPerPageAsync()
190
- const meta = pdf.metadata()
201
+ const images = await pdf.imagesPerPageAsync();
202
+ const meta = pdf.metadata();
191
203
  ```
192
204
 
193
205
  ### Extract everything with OCR in one call
194
206
 
195
207
  ```typescript
196
- import { readFile } from 'fs/promises'
197
- import { PdfDown } from '@d0paminedriven/pdfdown-ocr'
208
+ import { readFile } from "fs/promises";
198
209
 
199
- const pdf = new PdfDown(await readFile('scanned-document.pdf'))
200
- const result = await pdf.documentOcrAsync({ minTextLength: 10 })
210
+ import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
211
+
212
+ const pdf = new PdfDown(await readFile("scanned-document.pdf"));
213
+ const result = await pdf.documentOcrAsync({ minTextLength: 10 });
201
214
 
202
215
  // result.text — OcrPageText[] (page, text, source per page)
203
216
  // result.structuredText — OcrStructuredPageText[] (header/body/footer + source per page)
@@ -209,24 +222,25 @@ const result = await pdf.documentOcrAsync({ minTextLength: 10 })
209
222
  ### Combined: OCR text + images for multimodal pipelines
210
223
 
211
224
  ```typescript
212
- import { readFile } from 'fs/promises'
213
- import { PdfDown } from '@d0paminedriven/pdfdown-ocr'
225
+ import { readFile } from "fs/promises";
226
+
227
+ import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
214
228
 
215
- const pdf = new PdfDown(await readFile('scanned-document.pdf'))
229
+ const pdf = new PdfDown(await readFile("scanned-document.pdf"));
216
230
 
217
231
  const [ocrText, images] = await Promise.all([
218
232
  pdf.textWithOcrPerPageAsync({ minTextLength: 10 }),
219
- pdf.imagesPerPageAsync(),
220
- ])
233
+ pdf.imagesPerPageAsync()
234
+ ]);
221
235
 
222
- const imagesByPage = Map.groupBy(images, (img) => img.page)
236
+ const imagesByPage = Map.groupBy(images, (img) => img.page);
223
237
 
224
238
  for (const { page, text, source } of ocrText) {
225
239
  const pageImages = (imagesByPage.get(page) ?? []).map((img) => ({
226
- dataUrl: `data:image/png;base64,${img.data.toString('base64')}`,
240
+ dataUrl: `data:image/png;base64,${img.data.toString("base64")}`,
227
241
  width: img.width,
228
- height: img.height,
229
- }))
242
+ height: img.height
243
+ }));
230
244
  // Send { page, text, source, images: pageImages } to your embedding pipeline
231
245
  }
232
246
  ```
@@ -235,20 +249,52 @@ for (const { page, text, source } of ocrText) {
235
249
 
236
250
  Both methods extract everything from a PDF in a single call. The difference is how text is extracted:
237
251
 
238
- | Method | Text extraction | Return type | Use when |
239
- |--------|----------------|-------------|----------|
240
- | `document()` / `documentAsync()` | Native PDF text only | `PdfDocument` | PDF has selectable text |
252
+ | Method | Text extraction | Return type | Use when |
253
+ | -------------------------------------- | ------------------------ | ---------------- | ---------------------------------------- |
254
+ | `document()` / `documentAsync()` | Native PDF text only | `PdfDocument` | PDF has selectable text |
241
255
  | `documentOcr()` / `documentOcrAsync()` | Native with OCR fallback | `PdfDocumentOcr` | PDF may contain scanned/image-only pages |
242
256
 
243
- `PdfDocumentOcr` uses `OcrPageText` (with `source: 'Native' | 'Ocr'`) and `OcrStructuredPageText` (with header/body/footer split plus source) instead of the base `PageText` and `StructuredPageText` types. Images, annotations, and metadata are identical in both.
257
+ `PdfDocumentOcr` uses `OcrPageText` (with `source: 'Native' | 'Ocr'`) and `OcrStructuredPageText` (with header/body/footer split plus source) instead of the base `PageText` and `StructuredPageText` types. Images, annotations, metadata and the read-only AcroForm data (`form`, `formFields`, `totalFormFields`, `formFieldPages`; see the base package docs) are identical in both.
258
+
259
+ ### Positioned text with OCR
260
+
261
+ `extractLayoutWithOcrPerPage` returns the base package's `PageLayout` shape (words, lines and image placements with boxes in PDF points) for every page, choosing the source per page exactly like the text cascade:
262
+
263
+ 1. **Native** -- glyphs placed from the content stream, with `fontName` / `fontSize` / `bold` on every word.
264
+ 2. **Ocr** -- the page's embedded raster images are OCR'd and each Tesseract word box is mapped through the image's `Do` placement onto the page. Words carry `confidence` (0..1) instead of font metadata.
265
+ 3. **Rendered** -- with PDFium, the page is rasterised as displayed at `renderDpi` and OCR'd; word boxes are mapped back onto the page box in the page's own frame, the one native words use, and `contentRotation` includes `/Rotate`.
266
+
267
+ Copier and fax scans (`CCITTFaxDecode`, Group 3 and Group 4) are decoded in pure Rust, so they are read at tier 2 without PDFium. When the upright pass scores a mean Tesseract confidence under 55 (a landscape sheet scanned in portrait comes back as punctuation at 35-45), the raster is OCR'd again turned 90°, 270° and 180° and the best orientation wins. The page then reports `contentRotation`, the turn carrying the most confident OCR text across its images (the tiles of a tiled scan vote together), and every word, line and image placement is expressed in that turned frame, with `width`/`height` swapped for a quarter turn. A warning names each turned image with more than a few words and who decided the turn (the orientation detector or the confidence retry); such an image that reads upright at a different turn than the page is named too, since its words read sideways in the page frame. The render tier reads the page as displayed, so on a `/Rotate` page its `contentRotation` includes `/Rotate`; for any page, displayed coordinates are the reported frame turned clockwise by `rotate - contentRotation`. The same retry applies to `extractTextWithOcrPerPage`.
268
+
269
+ ```typescript
270
+ import { readFileSync } from "fs";
271
+
272
+ import { extractLayoutWithOcrPerPage } from "@d0paminedriven/pdfdown-ocr";
273
+
274
+ for (const page of extractLayoutWithOcrPerPage(readFileSync("scan.pdf"), { render: "Auto" })) {
275
+ console.log(`page ${page.page} (${page.source})`);
276
+ for (const line of page.lines) {
277
+ const confidence = page.words.slice(line.firstWord, line.firstWord + line.wordCount).map((w) => w.confidence ?? 1);
278
+ console.log(` ${Math.min(...confidence).toFixed(2)} ${line.text}`);
279
+ }
280
+ }
281
+ ```
282
+
283
+ ## Invoices from scans
284
+
285
+ `invoice()` and `invoiceAsync()` read the header fields of a PDF from its pages (see the base README's "Invoices" section). In this package they run the OCR cascade with default options on the **first and the last page only**, the two pages the header track reads, so a long scan does not cost a whole-document OCR; `source` then reports `Ocr`, `Rendered` or `Mixed` and every OCR'd field's confidence is scaled by its words' Tesseract confidence. For other OCR options, call `layoutWithOcr(opts)` yourself and hand the pages to `invoiceFromLayout(pages)`.
286
+
287
+ ## Workbooks
288
+
289
+ This package inherits the base package's workbook support: `detectFormat`, `PdfDown.openAsync`, `format`, `spreadsheetCells`, `layout` on a workbook and the standalone `layoutFromXlsx`, with the same options, number-format subset, logical-page contract and limits (see the base README's "Workbooks" section). A workbook's text is already text, so it never needs OCR: the OCR methods read PDFs, and on a workbook `textWithOcrPerPage`, `documentOcr` and `layoutWithOcr` fail with `unsupported operation: <method> reads a PDF; this document is a workbook` (the sync methods throw it, the async ones reject with it).
244
290
 
245
291
  ## How it works
246
292
 
247
- 1. **Text extraction:** Each page is first attempted with native PDF text extraction. If a page yields fewer non-whitespace characters than `minTextLength`, its embedded images are decoded and fed to Tesseract for OCR. Each result is tagged with `source: 'Native'` or `source: 'Ocr'`.
293
+ 1. **Text extraction (the cascade):** Each page is read natively first. A page goes to OCR when its native text is under `minTextLength` non-whitespace characters, or when its native words cover under 2% of the page while images cover more than half of it or the content stream paints 200 or more path operators (a scan with a stamp on it, or text printed as outlines); a few words on an otherwise empty cover sheet stay native. Tier 2 decodes the embedded rasters and feeds them to Tesseract; tier 3, with PDFium, renders the page when the page has no rasters but painted paths, or when tier 2 found nothing or only a weak result on a path-heavy page. On a hybrid page the native words stay and OCR adds only what they do not cover (duplicates dropped at IoU > 0.5); `source` reports the deepest tier that ran (`Native`, `Ocr` or `Rendered`), even when OCR added no words; OCR words carry `confidence`, native words do not, and a warning counts the native words kept. Orientation is decided per raster: an upright pass with a mean Tesseract confidence of 80 or more stands; below that the raster is shown to Tesseract's orientation detector (OSD), and only when OSD cannot decide and the upright pass scored under 55 is the raster read again at 90°, 270° and 180° with the best score winning.
248
294
 
249
295
  2. **Structured text:** After text extraction, repeated header/footer lines are detected across pages using frequency analysis (requires 3+ pages). Each page's text is split into `header`, `body`, and `footer` sections. For OCR results, the `source` tag is preserved so you know whether each page's content came from native extraction or OCR.
250
296
 
251
- 3. **Parallelism:** OCR runs on a dedicated capped Rayon thread pool (default 4 threads, configurable via `maxThreads`) to prevent CPU oversubscription. Text extraction, image extraction, and annotation extraction run concurrently via `rayon::join` when using `documentOcr` / `documentOcrAsync`.
297
+ 3. **Parallelism:** OCR runs on a dedicated capped Rayon thread pool (default 4 threads, configurable via `maxThreads`) to prevent CPU oversubscription. Text extraction, image extraction, and annotation extraction run concurrently via `rayon::join` when using `documentOcr` / `documentOcrAsync`. The package entry point also sets `OMP_THREAD_LIMIT=1` before the native module loads, because Ubuntu's libtesseract otherwise starts one OpenMP thread per core inside every recognise call and four workers on an eight-core box thrash it (measured: 7.8 s per page down to 0.6 s). Parallelism therefore comes from `maxThreads`, not from OpenMP; set `OMP_THREAD_LIMIT` or `OMP_NUM_THREADS` yourself before requiring the package to override this.
252
298
 
253
299
  4. **Tessdata discovery:** On first OCR invocation, the tessdata path is resolved once and cached in a `OnceLock`. The `TESSDATA_PREFIX` environment variable is checked first; if unset, `tesseract --list-langs` is executed and its output is parsed to extract the path. No environment variables are mutated -- the path is passed directly to Tesseract's init function.
254
300
 
@@ -256,9 +302,13 @@ Both methods extract everything from a PDF in a single call. The difference is h
256
302
 
257
303
  Prebuilt binaries are provided for:
258
304
 
259
- - macOS (x64, ARM64)
305
+ - macOS (ARM64)
260
306
  - Linux glibc (x64, ARM64)
261
307
 
308
+ Intel macOS is not built: the OCR package links the system Tesseract, and Homebrew no longer
309
+ ships Intel bottles, so there is no supported way to obtain the library on that platform.
310
+ The base `@d0paminedriven/pdfdown` package still ships an Intel macOS binary.
311
+
262
312
  ## Relationship to `@d0paminedriven/pdfdown`
263
313
 
264
314
  Same Rust codebase, compiled with the `ocr` Cargo feature flag enabled. This package is a strict superset -- you can use it as a drop-in replacement for the base package if you need OCR capabilities.