@d0paminedriven/pdfdown-ocr 0.12.0 → 0.13.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 DELETED
@@ -1,318 +0,0 @@
1
- # `@d0paminedriven/pdfdown-ocr`
2
-
3
- Rust-powered PDF extraction for Node.js with Tesseract OCR fallback for image-only pages. A superset of [`@d0paminedriven/pdfdown`](https://www.npmjs.com/package/@d0paminedriven/pdfdown) -- includes all base extraction APIs (text, images, annotations, structured text, metadata) plus OCR.
4
-
5
- **System requirement:** [Tesseract](https://github.com/tesseract-ocr/tesseract) 5.x must be installed on the host.
6
-
7
- ## Install
8
-
9
- ```bash
10
- npm install @d0paminedriven/pdfdown-ocr
11
- ```
12
-
13
- ### Tesseract setup
14
-
15
- ```bash
16
- # Ubuntu/Debian (22.04 ships pre v5 > -- use the PPA for 5.x)
17
- sudo add-apt-repository ppa:alex-p/tesseract-ocr5
18
- sudo apt update
19
- sudo apt install tesseract-ocr tesseract-ocr-eng -y
20
- # Optional: all language packs
21
- # sudo apt install tesseract-ocr-all
22
-
23
- # macOS
24
- brew install tesseract
25
-
26
- # Arch
27
- sudo pacman -S tesseract tesseract-data-eng
28
- ```
29
-
30
- Verify with `tesseract --version` -- you should see 5.x.
31
-
32
- ### Tessdata auto-detection
33
-
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
-
36
- **Resolution order:**
37
-
38
- 1. `TESSDATA_PREFIX` environment variable (if set, used as-is -- no auto-detection runs)
39
- 2. Auto-detection via `tesseract --list-langs` (parses the path from `List of available languages in "/path/to/tessdata/"`)
40
- 3. Tesseract's compiled-in default (if neither of the above yields a path)
41
-
42
- Most users will not need to set `TESSDATA_PREFIX` at all. The auto-detection handles standard installations on Ubuntu (`/usr/share/tesseract-ocr/5/tessdata/`), macOS Homebrew (`/opt/homebrew/share/tessdata/`), Arch, and any other layout where `tesseract` is on `PATH`.
43
-
44
- Set `TESSDATA_PREFIX` explicitly only if:
45
-
46
- - Tesseract is not on `PATH` but the tessdata directory exists elsewhere
47
- - You want to override the detected path (e.g., pointing to a custom-trained data directory)
48
-
49
- ```bash
50
- # Override example (not usually needed)
51
- export TESSDATA_PREFIX="/opt/custom/tessdata"
52
- ```
53
-
54
- ## API
55
-
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
-
58
- ### OCR standalone functions
59
-
60
- ```typescript
61
- // Per-page OCR text extraction
62
- export declare function extractTextWithOcrPerPage(buffer: Buffer, opts?: OcrOptions): Array<OcrPageText>;
63
-
64
- export declare function extractTextWithOcrPerPageAsync(buffer: Buffer, opts?: OcrOptions): Promise<Array<OcrPageText>>;
65
-
66
- // Full document extraction with OCR text fallback
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>>;
75
- ```
76
-
77
- ### `PdfDown` class (includes OCR methods)
78
-
79
- ```typescript
80
- export declare class PdfDown {
81
- constructor(buffer: Buffer); // a PDF or an .xlsx workbook
82
- static openAsync(buffer: Buffer): Promise<PdfDown>;
83
- readonly format: DocumentFormat; // "Pdf" | "Xlsx"
84
-
85
- // ── Base methods ──
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>>;
108
-
109
- // ── OCR methods ──
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>>;
116
- }
117
- ```
118
-
119
- ### Types
120
-
121
- ```typescript
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";
125
-
126
- export interface OcrPageText {
127
- page: number;
128
- text: string;
129
- source: TextSource;
130
- }
131
-
132
- export interface OcrStructuredPageText {
133
- page: number;
134
- header: string;
135
- body: string;
136
- footer: string;
137
- source: TextSource;
138
- }
139
-
140
- export interface OcrOptions {
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]
144
- }
145
-
146
- export interface PdfDocumentOcr {
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>;
166
- }
167
- ```
168
-
169
- ## Usage
170
-
171
- > **Use the async API for OCR.** The sync variants block the Node.js event loop for the duration of OCR processing, which can be significant for multi-page scanned documents.
172
-
173
- ### Standalone
174
-
175
- ```typescript
176
- import { readFile } from "fs/promises";
177
-
178
- import { extractTextWithOcrPerPageAsync } from "@d0paminedriven/pdfdown-ocr";
179
-
180
- const pdf = await readFile("scanned-document.pdf");
181
- const pages = await extractTextWithOcrPerPageAsync(pdf, { lang: "eng", minTextLength: 10 });
182
-
183
- for (const { page, text, source } of pages) {
184
- console.log(`Page ${page} [${source}]: ${text.slice(0, 100)}...`);
185
- }
186
- ```
187
-
188
- ### Class-based (parse once, extract many)
189
-
190
- ```typescript
191
- import { readFile } from "fs/promises";
192
-
193
- import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
194
-
195
- const pdf = new PdfDown(await readFile("scanned-document.pdf"));
196
-
197
- // OCR text extraction
198
- const pages = await pdf.textWithOcrPerPageAsync({ lang: "eng", minTextLength: 10 });
199
-
200
- // All base methods work too
201
- const images = await pdf.imagesPerPageAsync();
202
- const meta = pdf.metadata();
203
- ```
204
-
205
- ### Extract everything with OCR in one call
206
-
207
- ```typescript
208
- import { readFile } from "fs/promises";
209
-
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 });
214
-
215
- // result.text — OcrPageText[] (page, text, source per page)
216
- // result.structuredText — OcrStructuredPageText[] (header/body/footer + source per page)
217
- // result.images — PageImage[] (decoded PNGs with dimensions and color space)
218
- // result.annotations — PageAnnotation[] (links, destinations, rects)
219
- // result.pageCount, result.version, result.creator, ...
220
- ```
221
-
222
- ### Combined: OCR text + images for multimodal pipelines
223
-
224
- ```typescript
225
- import { readFile } from "fs/promises";
226
-
227
- import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
228
-
229
- const pdf = new PdfDown(await readFile("scanned-document.pdf"));
230
-
231
- const [ocrText, images] = await Promise.all([
232
- pdf.textWithOcrPerPageAsync({ minTextLength: 10 }),
233
- pdf.imagesPerPageAsync()
234
- ]);
235
-
236
- const imagesByPage = Map.groupBy(images, (img) => img.page);
237
-
238
- for (const { page, text, source } of ocrText) {
239
- const pageImages = (imagesByPage.get(page) ?? []).map((img) => ({
240
- dataUrl: `data:image/png;base64,${img.data.toString("base64")}`,
241
- width: img.width,
242
- height: img.height
243
- }));
244
- // Send { page, text, source, images: pageImages } to your embedding pipeline
245
- }
246
- ```
247
-
248
- ### `document()` vs `documentOcr()`
249
-
250
- Both methods extract everything from a PDF in a single call. The difference is how text is extracted:
251
-
252
- | Method | Text extraction | Return type | Use when |
253
- | -------------------------------------- | ------------------------ | ---------------- | ---------------------------------------- |
254
- | `document()` / `documentAsync()` | Native PDF text only | `PdfDocument` | PDF has selectable text |
255
- | `documentOcr()` / `documentOcrAsync()` | Native with OCR fallback | `PdfDocumentOcr` | PDF may contain scanned/image-only pages |
256
-
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).
290
-
291
- ## How it works
292
-
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.
294
-
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.
296
-
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.
298
-
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.
300
-
301
- ## Supported platforms
302
-
303
- Prebuilt binaries are provided for:
304
-
305
- - macOS (ARM64)
306
- - Linux glibc (x64, ARM64)
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
-
312
- ## Relationship to `@d0paminedriven/pdfdown`
313
-
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.
315
-
316
- ## License
317
-
318
- MIT