Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(ocr): rasterize scanned PDF pages with PDFium instead of pulling their images
Elian Doran2faa9407c563
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 980dcda391..636989796c 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -36,6 +36,7 @@"@ai-sdk/google": "4.0.64","@ai-sdk/openai": "4.0.59","@anthropic-ai/claude-agent-sdk": "^0.3.207",+ "@hyzyla/pdfium": "2.1.13","@modelcontextprotocol/sdk": "^1.12.1","ai": "7.0.93","better-sqlite3": "13.0.3",diff --git a/apps/server/scripts/build.ts b/apps/server/scripts/build.tsindex 17d2bae316..5af3be1ded 100644--- a/apps/server/scripts/build.ts+++ b/apps/server/scripts/build.ts@@ -23,6 +23,10 @@ async function main() {// Same story for the LLM skill sheets: core owns them, the server reads them// from RESOURCE_DIR at runtime. See core_assets.ts.build.copy("/packages/trilium-core/src/assets/llm/skills", "assets/llm/skills/");+ // PDFium rasterizes scanned PDF pages for OCR. Its own loader resolves the wasm relative to+ // `import.meta.url`, which in a split bundle is a hash-named file under chunks/, so the bytes+ // are handed to it explicitly from here instead. See pdf_renderer.ts.+ build.copy("/node_modules/@hyzyla/pdfium/dist/pdfium.wasm", "assets/pdfium.wasm");build.triggerBuildAndCopyTo("packages/share-theme", "share-theme/assets/");build.copy("/packages/share-theme/src/templates", "share-theme/templates/");diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).htmlindex 4f60f7581b..a24a6fc4ca 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).html@@ -35,7 +35,9 @@<ul><li>PDFs with text information (e.g. a PDF created by a browser or a wordprocessing application), in which the text is extracted.</li>- <li>Scanned PDFs, in which the text is extracted through an OCR process.</li>+ <li>Scanned PDFs, and other PDFs whose text cannot be selected (such as documents+ whose text was converted to outlines), in which the text is extracted through+ an OCR process.</li><li>Mixed PDFs, containing both text and images with text content.</li></ul><p>Note that OCR extraction is limited to 50 pages per PDF, pages containingdiff --git a/apps/server/src/services/ocr/pdf_renderer.ts b/apps/server/src/services/ocr/pdf_renderer.tsnew file mode 100644index 0000000000..104baef973--- /dev/null+++ b/apps/server/src/services/ocr/pdf_renderer.ts@@ -0,0 +1,119 @@+import { getLog } from "@triliumnext/core";+import fs from "fs";+import path from "path";++import { RESOURCE_DIR } from "../resource_dir.js";++/** A page rasterized to 8-bit BGRA, four bytes per pixel. */+export interface RenderedPage {+ data: Uint8Array;+ width: number;+ height: number;+}++/**+ * Multiplier applied to a page's natural size (72 dpi) when rasterizing it for OCR, giving about+ * 144 dpi. Recognition confidence climbs steeply below this and is flat above it: across a scanned+ * document and a vector-drawn one, scale 1 scored 82/54, scale 1.5 scored 93/89 and scale 2 scored+ * 94/93, while scale 3 and 4 added nothing but two to four times the pixels to encode and read.+ */+const RENDER_SCALE = 2;++/**+ * Pages are rasterized in colour even though Tesseract reads them as grey. PDFium's own grayscale+ * conversion flattens coloured text into its background — on the demo document it costs the whole+ * "Organize your thoughts" panel, 60 characters that colour rendering and Tesseract's own greyscale+ * conversion both keep. Raising the scale does not bring them back.+ */+const RENDER_COLOR_SPACE = "BGRA";++/**+ * Renders PDF pages for OCR through PDFium compiled to WebAssembly.+ *+ * Rasterizing the page, rather than pulling out the images it paints, is what lets a scan be read+ * at all when its text is drawn as vector outlines, when the scan is split across several images,+ * or when the page carries a rotation the images themselves know nothing about. It also bounds the+ * work: a page becomes a fixed number of pixels no matter what resolution it was scanned at.+ */+class PdfRenderer {+ private library: Promise<PdfiumLibrary> | null = null;+ // Serializes renders. The library holds one wasm heap that grows to fit the largest page it has+ // been asked for, so overlapping renders would size it to their sum rather than their maximum.+ private queue: Promise<unknown> = Promise.resolve();++ /**+ * Rasterize one page, numbered from 1. Renders are queued so only one runs at a time.+ */+ renderPage(pdf: Uint8Array, pageNum: number): Promise<RenderedPage> {+ const result = this.queue.then(async () => {+ const library = await this.ensureLibrary();+ const document = await library.loadDocument(pdf);+ try {+ const page = document.getPage(pageNum - 1);+ const { data, width, height } = await page.render({+ scale: RENDER_SCALE,+ render: "bitmap",+ colorSpace: RENDER_COLOR_SPACE+ });+ return { data, width, height };+ } finally {+ document.destroy();+ }+ });+ // Keep the chain going regardless of this render's outcome, without swallowing the+ // result/error the caller receives.+ this.queue = result.catch(() => {});+ return result;+ }++ /**+ * Loads PDFium once and keeps it. Its heap settles at the size of the largest page rendered and+ * is reused from then on, so a long-lived instance costs no more than the biggest single page.+ */+ private ensureLibrary(): Promise<PdfiumLibrary> {+ if (!this.library) {+ this.library = this.loadLibrary().catch((error) => {+ // A failed load must not be cached, or every later page would fail with it.+ this.library = null;+ throw error;+ });+ }+ return this.library;+ }++ private async loadLibrary(): Promise<PdfiumLibrary> {+ // Dynamically imported so PDFium only loads when a page actually needs rasterizing.+ const { PDFiumLibrary } = await import("@hyzyla/pdfium");+ getLog().info("Initializing PDFium for scanned-page rendering");+ return PDFiumLibrary.init({ wasmBinary: readWasm() });+ }+}++export default new PdfRenderer();++/** The subset of PDFium's API this renderer uses. */+interface PdfiumLibrary {+ loadDocument(bytes: Uint8Array): Promise<{+ getPage(index: number): {+ render(options: { scale: number; render: "bitmap"; colorSpace: typeof RENDER_COLOR_SPACE }):+ Promise<{ data: Uint8Array; width: number; height: number }>;+ };+ destroy(): void;+ }>;+}++/**+ * The PDFium wasm, read the way `core_assets.ts` reads schema.sql: copied beside the server's own+ * assets by the build, resolved through node_modules when running from source. PDFium would+ * otherwise locate it relative to `import.meta.url`, which in the split ESM bundle is a hash-named+ * file under chunks/ rather than anywhere the wasm was copied to.+ */+function readWasm(): ArrayBuffer {+ const productionPath = path.join(RESOURCE_DIR, "pdfium.wasm");+ const bytes = fs.existsSync(productionPath)+ ? fs.readFileSync(productionPath)+ : fs.readFileSync(require.resolve("@hyzyla/pdfium/dist/pdfium.wasm"));+ // Copied into an ArrayBuffer of its own: readFileSync can hand back a view into a pooled+ // buffer, whose remainder has nothing to do with the module PDFium is about to compile.+ return new Uint8Array(bytes).buffer;+}diff --git a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts b/apps/server/src/services/ocr/processors/pdf_processor.spec.tsindex 9fdbc3c307..3736246344 100644--- a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts+++ b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts@@ -2,12 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mockGetDocumentProxy = vi.fn();const mockExtractText = vi.fn();-const mockExtractImages = vi.fn();vi.mock('unpdf', () => ({getDocumentProxy: mockGetDocumentProxy,- extractText: mockExtractText,- extractImages: mockExtractImages+ extractText: mockExtractText}));const mockGetBuffer = vi.fn().mockResolvedValue(Buffer.from('png-bytes'));@@ -17,6 +15,12 @@ vi.mock('jimp', () => ({Jimp: { fromBitmap: mockFromBitmap }}));+const mockRenderPage = vi.fn();++vi.mock('../pdf_renderer.js', () => ({+ default: { renderPage: mockRenderPage }+}));+const mockRecognize = vi.fn();vi.mock('../tesseract_recognizer.js', () => ({@@ -48,6 +52,7 @@ beforeEach(async () => {mockGetPage.mockImplementation(async () => ({ getViewport: mockGetViewport }));mockGetDocumentProxy.mockResolvedValue(pdfProxy);mockGetBuffer.mockResolvedValue(Buffer.from('png-bytes'));+ mockRenderPage.mockResolvedValue(renderedPage);({ PDFProcessor } = await import('./pdf_processor.js'));});@@ -56,9 +61,8 @@ afterEach(() => {});const buffer = Buffer.from('%PDF-1.4 fake');-// A full-page grayscale scan, as unpdf's extractImages returns it — comfortably-// above the minimum OCR dimension so it isn't skipped as a decorative image.-const scannedImage = { data: new Uint8ClampedArray(100 * 100), width: 100, height: 100, channels: 1, key: 'img_0' };+/** A page as the renderer returns it: four BGRA bytes per pixel. */+const renderedPage = { data: new Uint8Array(100 * 60 * 4), width: 100, height: 60 };/** Embedded text dense enough for a Letter page to read as a real text layer rather than a scan. */function densePage(marker: string): string {@@ -89,8 +93,8 @@ describe('PDFProcessor', () => {expect(result.pageCount).toBe(2);expect(result.language).toBe('fra');expect(mockExtractText).toHaveBeenCalledWith(pdfProxy, { mergePages: false });- // No scanned page → no image extraction and no OCR.- expect(mockExtractImages).not.toHaveBeenCalled();+ // No scanned page → nothing rendered and no OCR.+ expect(mockRenderPage).not.toHaveBeenCalled();expect(mockRecognize).not.toHaveBeenCalled();// buffer is wrapped into a Uint8Array carrying the SAME bytes before being passed to unpdfconst [docArg] = mockGetDocumentProxy.mock.calls[0];@@ -98,37 +102,70 @@ describe('PDFProcessor', () => {expect(Buffer.from(docArg as Uint8Array).toString()).toBe('%PDF-1.4 fake');});- it('OCRs a scanned (text-less) page via its embedded images', async () => {+ it('OCRs a scanned (text-less) page by rendering it', async () => {const processor = new PDFProcessor();mockExtractText.mockResolvedValue({ totalPages: 1, text: [' '] });- mockExtractImages.mockResolvedValue([scannedImage]);mockRecognize.mockResolvedValue({ text: 'recognized text', confidence: 0.9 });const result = await processor.extractText(buffer, { language: 'eng' });- expect(mockExtractImages).toHaveBeenCalledWith(pdfProxy, 1);- expect(mockFromBitmap).toHaveBeenCalledOnce();+ expect(mockRenderPage).toHaveBeenCalledWith(expect.any(Uint8Array), 1);expect(mockRecognize).toHaveBeenCalledWith(Buffer.from('png-bytes'), 'eng');expect(result.text).toBe('recognized text');expect(result.confidence).toBeCloseTo(0.9);expect(result.pageCount).toBe(1);});+ it('turns the rendered BGRA page into the RGBA bitmap Jimp encodes', async () => {+ const processor = new PDFProcessor();+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });+ mockRenderPage.mockResolvedValue({+ // Two pixels, BGRA: an orange and a teal. The second is transparent, to prove alpha is+ // forced opaque rather than carried through.+ data: Uint8Array.from([16, 128, 240, 255, 200, 160, 32, 0]),+ width: 2,+ height: 1+ });+ mockRecognize.mockResolvedValue({ text: 'x', confidence: 0.5 });++ await processor.extractText(buffer, { language: 'eng' });++ const [bitmap] = mockFromBitmap.mock.calls[0] as unknown as [{ data: Buffer; width: number; height: number }];+ expect(bitmap.width).toBe(2);+ expect(bitmap.height).toBe(1);+ expect([...bitmap.data]).toEqual([+ 240, 128, 16, 255,+ 32, 160, 200, 255+ ]);+ });++ it('hands the renderer bytes of its own, since pdf.js takes ownership of what it is given', async () => {+ const processor = new PDFProcessor();+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });+ mockRecognize.mockResolvedValue({ text: 'ocr', confidence: 0.9 });++ await processor.extractText(buffer, { language: 'eng' });++ const [unpdfBytes] = mockGetDocumentProxy.mock.calls[0];+ const [renderBytes] = mockRenderPage.mock.calls[0];+ expect(renderBytes).not.toBe(unpdfBytes);+ expect(Buffer.from(renderBytes as Uint8Array).toString()).toBe('%PDF-1.4 fake');+ });+it('handles a mixed PDF, combining embedded text and OCR per page', async () => {const processor = new PDFProcessor();mockExtractText.mockResolvedValue({totalPages: 2,text: [densePage('a real text page'), '']});- mockExtractImages.mockResolvedValue([scannedImage]);mockRecognize.mockResolvedValue({ text: 'scanned page text', confidence: 0.8 });const result = await processor.extractText(buffer, { language: 'eng' });expect(result.text).toBe(`${densePage('a real text page').trim()}\n\nscanned page text`);- // Only the second (scanned) page is OCR'd.- expect(mockExtractImages).toHaveBeenCalledTimes(1);- expect(mockExtractImages).toHaveBeenCalledWith(pdfProxy, 2);+ // Only the second (scanned) page is rendered.+ expect(mockRenderPage).toHaveBeenCalledTimes(1);+ expect(mockRenderPage).toHaveBeenCalledWith(expect.any(Uint8Array), 2);// Average of the embedded-page (0.99) and OCR-page (0.8) confidences.expect(result.confidence).toBeCloseTo((0.99 + 0.8) / 2);});@@ -138,12 +175,11 @@ describe('PDFProcessor', () => {// A scanner stamps this much text on a page whose body is pure raster. Any flat character// bound low enough to be safe is cleared by it, and the page would never be recognized.mockExtractText.mockResolvedValue({ totalPages: 1, text: ['ACME Corp — Invoice 2024-11-03'] });- mockExtractImages.mockResolvedValue([scannedImage]);mockRecognize.mockResolvedValue({ text: 'the body of the invoice', confidence: 0.9 });const result = await processor.extractText(buffer, { language: 'eng' });- expect(mockExtractImages).toHaveBeenCalledWith(pdfProxy, 1);+ expect(mockRenderPage).toHaveBeenCalledWith(expect.any(Uint8Array), 1);expect(result.text).toBe('the body of the invoice');});@@ -152,13 +188,12 @@ describe('PDFProcessor', () => {// Four times the area of Letter, so the same text is four times as sparse on it.mockGetViewport.mockReturnValue({ width: 1224, height: 1584 });mockExtractText.mockResolvedValue({ totalPages: 1, text: [densePage('sparse on a large page')] });- mockExtractImages.mockResolvedValue([scannedImage]);mockRecognize.mockResolvedValue({ text: 'recognized', confidence: 0.9 });const result = await processor.extractText(buffer, { language: 'eng' });// The very same text is kept as-is on a Letter page (see the mixed-PDF case above).- expect(mockExtractImages).toHaveBeenCalledOnce();+ expect(mockRenderPage).toHaveBeenCalledOnce();expect(result.text).toBe('recognized');});@@ -169,75 +204,32 @@ describe('PDFProcessor', () => {const result = await processor.extractText(buffer, { language: 'eng' });- expect(mockExtractImages).not.toHaveBeenCalled();+ expect(mockRenderPage).not.toHaveBeenCalled();expect(result.text).toBe(densePage('still a text page').trim());expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('Could not measure PDF page 1'));});- it('reports zero confidence and empty text for a scanned page with nothing recognizable', async () => {+ it('reports zero confidence and empty text when the page holds nothing recognizable', async () => {const processor = new PDFProcessor();mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- mockExtractImages.mockResolvedValue([]);+ mockRecognize.mockResolvedValue({ text: '', confidence: 0 });const result = await processor.extractText(buffer, { language: 'eng' });expect(result.text).toBe('');expect(result.confidence).toBe(0);- expect(mockRecognize).not.toHaveBeenCalled();});- it('tolerates an image extraction failure on a page without aborting the document', async () => {+ it('tolerates a render failure on a page without aborting the document', async () => {const processor = new PDFProcessor();mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- mockExtractImages.mockRejectedValue(new Error('broken page'));+ mockRenderPage.mockRejectedValue(new Error('broken page'));const result = await processor.extractText(buffer, { language: 'eng' });expect(result.text).toBe('');expect(result.confidence).toBe(0);- expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('PDF OCR failed for page 1'));- });-- it('skips embedded images below the minimum OCR dimension', async () => {- const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- // A 20x20 icon — too small to hold recognizable text.- mockExtractImages.mockResolvedValue([- { data: new Uint8ClampedArray(20 * 20), width: 20, height: 20, channels: 1, key: 'icon' }- ]);-- const result = await processor.extractText(buffer, { language: 'eng' });-- expect(mockFromBitmap).not.toHaveBeenCalled();expect(mockRecognize).not.toHaveBeenCalled();- expect(result.text).toBe('');- });-- it('OCRs an RGBA page image', async () => {- const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- mockExtractImages.mockResolvedValue([- { data: new Uint8ClampedArray(60 * 60 * 4), width: 60, height: 60, channels: 4, key: 'rgba' }- ]);- mockRecognize.mockResolvedValue({ text: 'rgba text', confidence: 0.7 });-- const result = await processor.extractText(buffer, { language: 'eng' });-- expect(mockFromBitmap).toHaveBeenCalledOnce();- expect(result.text).toBe('rgba text');- });-- it('skips a page whose image has an unsupported channel count, logging the failure', async () => {- const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- mockExtractImages.mockResolvedValue([- { data: new Uint8ClampedArray(50 * 50 * 2), width: 50, height: 50, channels: 2, key: 'weird' }- ]);-- const result = await processor.extractText(buffer, { language: 'eng' });-- expect(mockRecognize).not.toHaveBeenCalled();- expect(result.text).toBe('');expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('PDF OCR failed for page 1'));});@@ -245,13 +237,12 @@ describe('PDFProcessor', () => {const processor = new PDFProcessor();const totalPages = 55;mockExtractText.mockResolvedValue({ totalPages, text: Array(totalPages).fill('') });- mockExtractImages.mockResolvedValue([scannedImage]);mockRecognize.mockResolvedValue({ text: 'p', confidence: 0.9 });const result = await processor.extractText(buffer, { language: 'eng' });- // MAX_OCR_PAGES = 50; the remaining 5 scanned pages are skipped, not OCR'd.- expect(mockRecognize).toHaveBeenCalledTimes(50);+ // MAX_OCR_PAGES = 50; the remaining 5 scanned pages are skipped, not rendered.+ expect(mockRenderPage).toHaveBeenCalledTimes(50);expect(result.text.split('\n\n')).toHaveLength(50);expect(mockLog.info).toHaveBeenCalledWith(expect.stringContaining('page cap reached'));});diff --git a/apps/server/src/services/ocr/processors/pdf_processor.ts b/apps/server/src/services/ocr/processors/pdf_processor.tsindex 78ab28be92..7051258af6 100644--- a/apps/server/src/services/ocr/processors/pdf_processor.ts+++ b/apps/server/src/services/ocr/processors/pdf_processor.ts@@ -1,6 +1,7 @@import { getLog } from "@triliumnext/core";import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';+import renderer, { RenderedPage } from '../pdf_renderer.js';import recognizer from '../tesseract_recognizer.js';import { FileProcessor } from './file_processor.js';@@ -11,8 +12,7 @@ type PdfDocument = Awaited<ReturnType<typeof import('unpdf').getDocumentProxy>>;* sent to OCR. A flat character count cannot separate the two cases: a scan carrying a header, a* watermark or a partial text layer clears any small bound while the body of the page stays unread.* This works out to roughly 240 characters on Letter and A4 — far below a sparse but genuine text- * page, far above a header. A text page misjudged by it still keeps its text, because a page with- * no image large enough to recognize yields no OCR text and falls back to what it had.+ * page, far above a header.*/const MIN_EMBEDDED_TEXT_DENSITY = 0.0005;@@ -31,18 +31,15 @@ const MAX_OCR_PAGES = 50;/** An embedded-text page is exact, so it is reported at the same high confidence the previous text-only path used. */const EMBEDDED_TEXT_CONFIDENCE = 0.99;-/**- * Embedded images smaller than this on either side are skipped: scanned pages are- * full-page raster, whereas tiny images are almost always icons, bullets or rules- * that hold no recognizable text and would only waste an OCR pass.- */-const MIN_OCR_IMAGE_DIM = 50;-/*** PDF processor. Prefers the PDF's embedded text layer (fast and exact) and falls back to OCR for- * pages carrying too little text for their size, by extracting each page's embedded images and- * running them through the shared Tesseract recognizer. Detection is per page, so mixed PDFs (some- * real-text pages, some scans) are handled correctly.+ * pages carrying too little text for their size, rasterizing those through PDFium and reading them+ * with the shared Tesseract recognizer. Detection is per page, so mixed PDFs (some real-text pages,+ * some scans) are handled correctly.+ *+ * Reading the rendered page rather than the images it paints is what lets a scan be recognized when+ * its text is drawn as vector outlines, when it is split across several images, or when the page+ * carries a rotation the images know nothing about.*/export class PDFProcessor extends FileProcessor {@@ -65,6 +62,9 @@ export class PDFProcessor extends FileProcessor {const pageResults: string[] = [];const pageConfidences: number[] = [];+ // pdf.js takes ownership of the bytes it is handed, so the renderer gets a copy of its own.+ // Made on the first page that needs it, since a PDF with a full text layer never renders.+ let renderBytes: Uint8Array | null = null;let ocrPagesProcessed = 0;let ocrPagesSkipped = 0;@@ -88,7 +88,8 @@ export class PDFProcessor extends FileProcessor {}ocrPagesProcessed++;- const ocr = await this.ocrPage(pdf, pageNum, language);+ renderBytes ??= new Uint8Array(buffer);+ const ocr = await this.ocrPage(renderBytes, pageNum, language);if (ocr.text.length > 0) {pageResults.push(ocr.text);pageConfidences.push(ocr.confidence);@@ -122,39 +123,13 @@ export class PDFProcessor extends FileProcessor {}/**- * OCR a single scanned page by recognizing each embedded image it paints and- * concatenating the results. Failures on an individual page are logged and- * treated as "no text" so one bad page never aborts the whole document.+ * OCR a single page by rasterizing it and recognizing the result. Failures on an individual page+ * are logged and treated as "no text" so one bad page never aborts the whole document.*/- private async ocrPage(pdf: PdfDocument, pageNum: number, language: string): Promise<{ text: string; confidence: number }> {+ private async ocrPage(pdf: Uint8Array, pageNum: number, language: string): Promise<{ text: string; confidence: number }> {try {- const { extractImages } = await import('unpdf');- const images = await extractImages(pdf, pageNum);- if (images.length === 0) {- return { text: "", confidence: 0 };- }-- const parts: string[] = [];- const confidences: number[] = [];-- for (const image of images) {- if (image.width < MIN_OCR_IMAGE_DIM || image.height < MIN_OCR_IMAGE_DIM) {- continue;- }- const png = await toPngBuffer(image);- const { text, confidence } = await recognizer.recognize(png, language);- if (text.length > 0) {- parts.push(text);- confidences.push(confidence);- }- }-- return {- text: parts.join("\n"),- confidence: confidences.length > 0- ? confidences.reduce((sum, c) => sum + c, 0) / confidences.length- : 0- };+ const page = await renderer.renderPage(pdf, pageNum);+ return await recognizer.recognize(await toPngBuffer(page), language);} catch (error) {getLog().error(`PDF OCR failed for page ${pageNum}: ${error}`);return { text: "", confidence: 0 };@@ -176,52 +151,22 @@ async function getPageArea(pdf: PdfDocument, pageNum: number): Promise<number> {}}-interface ExtractedImage {- data: Uint8ClampedArray;- width: number;- height: number;- // Typed as a plain number rather than `1 | 3 | 4`: the value is whatever unpdf- // hands us at runtime, so it is validated below rather than trusted here.- channels: number;-}-/**- * Encode a raw image extracted from a PDF into a PNG buffer that Tesseract can- * decode. unpdf returns 1- (grayscale), 3- (RGB) or 4-channel (RGBA) pixel data;- * Jimp bitmaps are always RGBA, so narrower formats are expanded here. An- * unexpected channel count throws rather than silently producing garbled pixels.+ * Encode a rendered page into a PNG buffer that Tesseract can decode. The renderer produces BGRA+ * and Jimp bitmaps are RGBA, so the blue and red channels swap places. Alpha is forced opaque: a+ * transparent page background would otherwise reach Tesseract as black.*/-async function toPngBuffer(image: ExtractedImage): Promise<Buffer> {- const { data, width, height, channels } = image;- const pixelCount = width * height;-- let rgba: Buffer;- if (channels === 4) {- // Already RGBA — reuse the underlying bytes instead of copying pixel by pixel.- rgba = Buffer.from(data.buffer, data.byteOffset, data.byteLength);- } else if (channels === 3 || channels === 1) {- rgba = Buffer.alloc(pixelCount * 4);- for (let i = 0; i < pixelCount; i++) {- const out = i * 4;- if (channels === 1) {- const value = data[i];- rgba[out] = value;- rgba[out + 1] = value;- rgba[out + 2] = value;- } else {- const src = i * 3;- rgba[out] = data[src];- rgba[out + 1] = data[src + 1];- rgba[out + 2] = data[src + 2];- }- rgba[out + 3] = 255;- }- } else {- throw new Error(`Unsupported image channel count: ${channels}`);+async function toPngBuffer({ data, width, height }: RenderedPage): Promise<Buffer> {+ const rgba = Buffer.alloc(width * height * 4);+ for (let i = 0; i < width * height; i++) {+ const out = i * 4;+ rgba[out] = data[out + 2];+ rgba[out + 1] = data[out + 1];+ rgba[out + 2] = data[out];+ rgba[out + 3] = 255;}- // Dynamically imported so jimp only loads when a scanned page is actually rasterized.+ // Dynamically imported so jimp only loads when a page is actually rasterized.const { Jimp } = await import("jimp");- const jimpImage = Jimp.fromBitmap({ data: rgba, width, height });- return jimpImage.getBuffer("image/png");+ return Jimp.fromBitmap({ data: rgba, width, height }).getBuffer("image/png");}diff --git a/docs/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).md b/docs/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).mdindex 14f0faac78..beb98285e3 100644--- a/docs/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).md+++ b/docs/User Guide/User Guide/Advanced Usage/Text Extraction (OCR).md@@ -30,7 +30,7 @@ OCR in Trilium supports the following formats:The PDF extraction supports:* PDFs with text information (e.g. a PDF created by a browser or a word processing application), in which the text is extracted.-* Scanned PDFs, in which the text is extracted through an OCR process.+* Scanned PDFs, and other PDFs whose text cannot be selected (such as documents whose text was converted to outlines), in which the text is extracted through an OCR process.* Mixed PDFs, containing both text and images with text content.Note that OCR extraction is limited to 50 pages per PDF, pages containing text information (not as an image) are not subject to this limitation.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6c7c3d7a40..d85494ea1d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -607,6 +607,9 @@ importers:'@anthropic-ai/claude-agent-sdk':specifier: ^0.3.207version: 0.3.259(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected])+ '@hyzyla/pdfium':+ specifier: 2.1.13+ version: 2.1.13'@modelcontextprotocol/sdk':specifier: ^1.12.1version: 1.30.0([email protected])([email protected])@@ -2884,6 +2887,9 @@ packages:resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==}engines: {node: '>=18.18'}+ '@hyzyla/[email protected]':+ resolution: {integrity: sha512-4J+xMFJW6V+jktxor6Lsk/2YdPCpeY+Ga69J98uyNQwYESkAsUDxz8BeFU0ZbZJIJ+fK3J6bm61gmwWnUzVU1g==}+'@iconify/[email protected]':resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==}@@ -14181,6 +14187,8 @@ snapshots:'@humanwhocodes/[email protected]': {}+ '@hyzyla/[email protected]': {}+'@iconify/[email protected]': {}'@iconify/[email protected]':