Building RAG from Scanned PDFs
Engineering

Building RAG from Scanned PDFs

Retrieval cannot be better than the text OCR reads from the page. Here is how to decide which pages need OCR, how to measure quality, and where pages that fail should go.

Short answer

To build RAG from scanned PDFs, first turn the pages into text you can trust. Separate pages without a text layer, run OCR with the right language and resolution, and store the page, position and confidence with every passage. Before indexing, gate quality on critical fields such as amounts, dates, negations and handwriting, and send failing pages to a review queue instead of the index.

Why are scanned PDFs a separate problem for RAG?

A scanned PDF contains no searchable text; every page is an image. The only text a RAG system can search is the text OCR reads from that image, and that text is all the model ever sees as evidence. If OCR misreads an amount, skips a line or fails to recognise handwriting, retrieval does not notice: it returns the wrong text with the same confidence as the right text. With a digital PDF, most of the work is splitting the text well. With a scanned PDF, you first need to know whether you can trust the text at all.

That changes the order of work: classify the pages, run OCR with the right settings, pass the output through quality gates, and only then index it. Keep the original page image available for verification; extracted text is a derived representation of the evidence, not the evidence itself.

Which pages actually need OCR?

Separate digital PDFs with selectable text from image-only pages. Organisational archives usually mix four kinds of page:

  • Born-digital page: The text layer was written by the software that produced the document; no OCR is needed, the text is extracted directly.
  • Image-only page: It came from a scanner or a photo; OCR is required.
  • Mixed file: Scanned pages with signatures, stamps or handwritten notes have been inserted between digital pages. Decide per page, not per file.
  • Page with an old OCR layer: The text looks selectable but was produced years ago by weak OCR. "Has text" does not mean "has correct text". The open-source OCRmyPDF tool offers a --redo-ocr option for regenerating that layer in files that were OCRed by other software.

Then sample pages across scanners, dates, languages and document types. Record skew, blur, cropped margins, faint handwriting, stamps, rotated pages and low contrast. A uniform OCR pipeline may work well for typed pages while silently losing handwritten approvals or tiny footnotes. Send unreadable scans to a remediation queue instead of indexing empty or invented text.

How good does the scan quality need to be?

At least as good as the minimum your OCR engine documents, and good enough to read the smallest critical text in your archive. Tesseract's guide to improving output quality says the engine works best on images of at least 300 dpi; the same guide recommends straightening skewed pages, cropping borders and removing noise. The documentation for Microsoft Document Intelligence's layout model sets a minimum text height of 12 pixels; for a 1024 × 768 pixel image, that corresponds to roughly 8-point text at 150 dpi.

Those figures are the engines' lower limits, not your acceptance threshold. Build a trial set that contains the smallest footnote, the faintest stamp and the worst faxed page in your archive. OCR the same pages with different resolutions and preprocessing settings and compare the results. If rescanning is possible, it is often the cheapest fix. If not, try deskewing and page rotation; in OCRmyPDF these are the --deskew and --rotate-pages options.

What should you store alongside the OCR output?

Store where each piece of text came from and how it was produced, not just the text. Document-analysis services can return words, lines, paragraphs, tables, page numbers and positions. Microsoft's layout model also returns a confidence score for each word, whether each line is handwritten, and the page's rotation angle. Keep at least these fields with every passage:

  • Document ID and version: Which file and which scan the passage came from.
  • Page number and region coordinates: So a citation can open the page and highlight the relevant area.
  • Extraction method: Digital text or OCR; for OCR, the engine, model version and language setting.
  • Confidence and review status: The share of low-confidence words, the handwriting flag, and whether a person has corrected the text.
  • Link to the original page image: So a reviewer can compare the text with the image side by side.

Set the language explicitly. The Azure AI Search OCR skill treats the language as English when no language code is given, and OCRmyPDF also assumes English unless told otherwise, noting that the wrong language can make OCR quality poor. For Turkish archives, use the Turkish language setting or automatic language detection so that letters such as ı, ş and ğ are read correctly. The same skill can extract text from images embedded in a PDF, but that text is appended after the rest of the page's text. Putting it back where it belongs in the document takes a separate merge step. Verify the supported inputs and service configuration for your own deployment. A citation should open the page and ideally the relevant region, not merely name a file.

How do you measure OCR quality?

With a manually transcribed sample, measured both at character level and at the level of critical fields. Pick representative pages and have a person type out the correct text. Character error rate (CER) is the number of substitutions, deletions and insertions needed to turn the OCR output into that correct text, divided by the number of characters in the correct text. It summarises overall quality well, but it is not enough on its own. Compare the OCR output separately on names, amounts, dates, section headings, table headers and negation words.

A hypothetical example: on a 2,000-character page, OCR misreads 14 characters, drops 4 and inserts 2 extra ones. CER = (14 + 4 + 2) / 2,000 = 1%, which looks good on paper. But if two of those 20 errors turn "not approved" into "approved", or if 18,500 is read as 13,500, the page is unusable. Character accuracy can hide a dangerous error: few characters change, but the decision does.

So pass every page through the following gates before indexing:

GateWhat it checksWhat happens to a page that fails
ImageResolution, skew, cropped margins, blank or upside-down pagesGoes to a rescan or preprocessing queue
Language and orientationCorrect language setting, page rotation angleSettings are fixed and the page is OCRed again
Word confidenceShare of low-confidence words on the pageGoes to human review above the share you set
Critical fieldsAmounts, dates, ID numbers, negation and approval wordingNot indexed if formats or totals don't add up; goes to review
StructureTable headers, column order, page orderThe table is processed separately or checked by hand
Handwriting and stampsLines flagged as handwritten, signatures and approval notesA person confirms before it is used as evidence in an answer

Derive the thresholds from your own sample; a figure set for someone else's archive says nothing about your documents. Require human review for pages below the quality threshold, pages missing expected fields and pages whose totals don't add up. Store corrected text as a separate version with the reviewer's name and reason; never overwrite the raw OCR output without a trail.

Hypothetical example: an insurance claim file

Suppose an insurer has scanned claim files containing a cover form, a repair estimate and a handwritten note. A user asks which repairs were approved. The system must connect the note and the estimate to the same file, distinguish the estimate from the approval, and cite the page where the approval is written.

In a good pipeline, retrieval returns the typed pages with the estimate items together with the page carrying the handwritten note. If the note line is flagged as handwritten and was read with low confidence, the answer should look like this: "The estimate items are on pages 3 and 4. The approval note on page 7 is handwritten and could not be read reliably by OCR; check that page by hand to confirm which items were approved." If the handwriting is uncertain, the system should answer with the reliable typed evidence and leave the approval to manual inspection. A plausible number taken from the estimate is not a grounded approval answer.

How do you test retrieval after OCR?

By measuring separately whether retrieval returns the right passage from the OCR text and whether the answer uses that passage correctly. Split text at document and section boundaries while keeping page references. Then put these kinds of question in the test set:

  1. Questions whose answer depends on a small qualifier ("excluding", "at most", "not approved").
  2. Questions answered by a table cell; the header and the value must arrive in the same passage.
  3. Questions whose answer spans several pages.
  4. Questions that rely on handwriting; the expected behaviour is a limited answer with a review warning.
  5. Questions about pages that failed the quality gates; the system must not invent evidence and should say no readable source was found.
  6. Questions about a document that exists as both a digital and a scanned copy; the two should not repeat the same fact, and any conflict should be visible.

Score retrieval of the correct passage and faithful use of it in the answer separately; our article on RAG evaluation metrics explains how to set up both measures. Track the OCR rejection rate and correction time as operational metrics. When the OCR settings or engine change, reprocess only the affected documents and compare their answers before replacing the old index. Retrieval quality cannot exceed the quality of the page text it receives.

Common mistakes

  • Assuming every PDF with a text layer contains correct text.
  • Leaving the OCR language on its English default.
  • Silently indexing empty or garbled OCR output.
  • Judging quality by character error rate alone, without checking critical fields.
  • Showing only a file name in citations instead of the page and region.
  • Editing raw OCR text without recording who changed it, when and why.

The document preparation step in which scanned documents go through OCR is part of the setup described on our RAG and semantic search solutions page.

Key takeaways

  • Classify PDFs page by page, not file by file, and measure an old OCR layer before trusting it.
  • Set the OCR language explicitly to Turkish or auto-detect; several tools default to English.
  • Store the page, region, extraction method, confidence and a link to the original image with every passage.
  • Measure quality on critical fields such as amounts, dates, negations and handwriting, not only by character error rate.
  • Send pages that fail a quality gate to review instead of the index, and keep corrections as separate versions.

Frequently asked questions

Can I load scanned PDFs straight into a RAG system?

You can, and many services run OCR automatically. The real question is whether the extracted text can be trusted. Without quality checks, blank pages, misread amounts and lost handwriting enter the index silently, so check the language setting, word confidence and critical fields before indexing.

What scan resolution does OCR need?

Tesseract's documentation says it works best on images of at least 300 dpi, and Microsoft's layout model needs text at least 12 pixels high. Treat these as lower limits and set your own threshold by testing the smallest critical text in your archive.

Can handwriting be read by OCR and used in RAG?

Some services read printed and handwritten text together and flag handwritten lines with a confidence score. Handwriting still carries a higher risk of error, so have a person confirm handwritten approvals, signatures and amounts before an answer relies on them.

How do you measure OCR accuracy?

Compute character error rate (CER) on manually transcribed, representative pages, and check critical fields such as amounts, dates and negations separately. A low CER can hide a single error that changes the decision.

Do I need to keep the original page image after OCR?

Yes. Extracted text is a copy derived from the image, so a reviewer must be able to open the page image and the relevant region from the citation to verify a doubtful answer.

Do I have to rebuild the whole index when OCR settings change?

No. Reprocess only the documents affected by the change, compare their answers on your test questions with the old index, and swap in the new text only if results do not get worse.

All articles