How to Extract Data from Any PDF (Without Losing Formatting)
Quick answer
PDF data extraction is not one problem — it's three, because native, scanned, and hybrid PDFs each break in different ways. Native PDFs have an embedded text layer and can be parsed directly with libraries like pdfplumber and Camelot. Scanned PDFs are page images with no text layer, so OCR is mandatory. Hybrid PDFs mix both and defeat pipelines built for only one. Identify which type you have first — that single question determines whether copy-paste, a Python library, or a vision-first OCR pipeline will preserve your formatting.
In this guide
You have a PDF. You need the data inside it in a spreadsheet, a database, or your accounting software. You try copying and pasting, and the formatting disintegrates. Columns misalign. Line breaks scatter mid-sentence. Tables turn into alphabet soup.
The problem is not your PDF reader. The problem is that you are treating every PDF as if it is the same kind of file.
PDF extraction is not one problem. It is three, and applying the wrong method to the wrong PDF type is what destroys formatting. A bank statement exported from your accounting platform needs a completely different extraction approach than a scanned supplier invoice from 2019. Most guides skip this triage step, recommend a single tool, and lose readers at the first mismatch.
The right first question is always: what kind of PDF am I working with? The answer determines everything from library choice to whether your formatting survives.
PDFs Are Display Containers, Not Data Files
A PDF is designed to look the same everywhere. That is its job. Financial reports, invoices, contracts, and compliance filings are shared as PDFs because they preserve formatting across devices and operating systems. The trade-off is that PDFs are built for presentation, not for structured data analysis.
Under the hood, a PDF is a display container. It positions pixels on a page but carries no semantic meaning about what those pixels represent. A dollar amount in a table cell, a vendor name in a header, and a footnote at the bottom of page 3 all look the same to a PDF parser: they are just glyphs placed at coordinates. There is no concept of “this cell contains a total” or “this text is a column header.”
That is why copy-paste fails. You are asking a presentation format to behave like a database, and it was never built for that.
Three Kinds of PDF, Three Extraction Problems
Before you pick a tool, identify what you are actually looking at. PDFs come in three types, and each demands a different approach.
- Native PDFs contain embedded text that can be extracted directly using parsing libraries. These files are exported from software systems: accounting tools, reporting platforms, office applications. The text already exists digitally, so extraction is relatively reliable. But reading order, multi-column layouts, and merged tables can still break naive extraction.
- Scanned PDFs are page images stored inside a PDF container. There is no text layer. Extraction tools cannot read the content directly. OCR software must first analyze the images and attempt to reconstruct readable text. Skew, blur, handwriting, and fax noise become central problems.
- Hybrid PDFs mix embedded text, scans, overlays, and broken fonts. They are common in real document packets and often defeat pipelines that use only the PDF text layer or only OCR.
A quick diagnostic: open your PDF and try to select text with your cursor. If you can highlight individual words, you have a native or hybrid PDF with at least some machine-readable text. If clicking selects nothing, you are looking at a scanned image and need OCR.
Text and Table Extraction from Native PDFs
If your PDF has a text layer, Python libraries give you direct access. The most commonly used libraries include pdfplumber, PyMuPDF, Camelot, tabula-py, and pytesseract.
For plain text extraction, pdfplumber handles the basics in a few lines:
import pdfplumber
with pdfplumber.open("report.pdf") as pdf:
for page in pdf.pages:
text = page.extract_text()
print(text)This works for reports, contracts, and text-heavy documents with simple layouts. The moment you introduce multi-column layouts, the output scrambles. Text from column one and column two get interleaved because the parser reads top-to-bottom, not left-to-right in each column.
Tables are where extraction gets genuinely difficult. Tables are consistently the hardest element to parse correctly. Dense financial tables, multi-column spans, and merged cells break naive extraction. For any document with tabular data, table quality is the single most important evaluation criterion.
Camelot is one of the most widely used Python libraries for table extraction. It identifies table structures by analyzing page layouts and separates rows and columns automatically, returning data as Pandas DataFrames. From there, export to Excel is one line:
import camelot
tables = camelot.read_pdf("financial_report.pdf", pages="1")
tables[0].df.to_excel("output.xlsx", index=False)The catch is that Camelot works best on clearly bordered tables. Borderless tables, merged cells, and multi-page spans still require custom logic. Real-world PDFs are rarely perfectly structured.
OCR for Scanned and Image-Based PDFs
When there is no text layer, OCR is not optional. It is the only path to extraction. Scanned documents require OCR because there is no machine-readable text available inside the file.
The open-source standard is Tesseract, paired with pytesseract for Python integration. It works by identifying character shapes pixel by pixel, mapping them to text strings. In clean, printed conditions, this works reasonably well. Accuracy drops sharply with skewed scans, low contrast, or varied fonts.
The accuracy gap between approaches is substantial. Traditional OCR achieves 85 to 90% accuracy on clean printed documents with good scan quality. Vision-first architectures, which process the full page as an image using AI models trained on document layouts, reach 95 to 99% accuracy across varied document types.
For tables specifically, the difference is larger. Traditional OCR achieves 65% cell-level accuracy on tables and fails on borderless tables and merged cells without manual configuration. Vision-first approaches achieve 90% or higher cell-level accuracy on structured documents and handle borderless tables and multi-row headers.
Traditional OCR also flattens multi-column layouts by reading content top-to-bottom, losing reading order across columns and sidebars. Vision-first architectures use bounding box coordinates to reconstruct the correct reading sequence.
The practical takeaway: if you have clean, single-column scanned documents, Tesseract works. If you have complex layouts, multi-column text, or tables without borders, you need a vision-first approach.
AI-Powered Extraction: The VLM Trade-Off
Vision language models (VLMs) like GPT-4V and Llama 3.2 11B Vision Instruct have become a popular shortcut for PDF extraction. Upload a page image, describe what you want, and the model returns structured text. The appeal is obvious: no pipeline to build, no library to configure.
The trade-offs are real. VLMs are flexible but prone to errors that specialized pipelines do not make. The VLM approach is prone to incorrect interpretation, failure to extract embedded text, hallucinations, and incomplete extraction, whereas an OCR-based pipeline provides more faithful and complete representations.
NVIDIA benchmarked both approaches for retrieval tasks. The NeMo Retriever OCR pipeline outperformed the VLM-based approach using Llama 3.2 11B by 7.2% in retrieval recall on the DigitalCorpora 10K dataset. The OCR pipeline also demonstrated 32.3 times higher throughput than the VLM pipeline on a single NVIDIA A100 GPU.
VLMs also have a hallucination problem. They can fabricate details, repeat phrases unnecessarily, and miss embedded text that a specialized OCR pipeline would capture. Counterintuitively, scaling up to a larger VLM (Llama 3.2 90B) did not improve retrieval recall in the same benchmarks.
For one-off extraction where you can verify the output, VLMs are fast and convenient. For production pipelines processing hundreds of documents, the accuracy and throughput gap makes specialized OCR the default choice.
ChatGPT illustrates the same pattern at the consumer level. It accepts PDF uploads but has significant limitations for production extraction: no structured output, no confidence scoring, no batch processing, and no accounting integrations. The output format varies between sessions. The same prompt applied to two invoices from the same supplier can produce different field names and different key-value mappings. There is no schema enforcement. (See our full breakdown of ChatGPT vs dedicated extraction tools.)
Preserving Formatting: What Actually Works
When people say they want to “preserve formatting,” they rarely mean the same thing. For some, it means bold, italic, and underline. For others, it means full layout fidelity with fonts, columns, and positioning intact.
The community consensus is consistent: pdftotext-style tools produce plain text with no formatting. Word processors preserve layout but drag along unwanted images. No single free tool does everything. Vision-first, layout-aware parsers and commercial OCR suites are the two paths that keep formatting intact end to end.
The broader lesson: formatting preservation means different things at different levels. If you need bold and italic markers in plain text, a library like PyMuPDF can extract text with font annotations. If you need full page layout preserved in Markdown or HTML, you need a vision-first parser that understands document structure before extracting.
For most accounting and business workflows, the goal is not pixel-perfect layout replication. It is getting clean structured data from a PDF into a spreadsheet or accounting system without manually re-typing every field. That is a data extraction problem, not a formatting replication problem.
When to Code It vs When to Buy It
Python pipelines give you full control. You choose the libraries, write the extraction logic, and own the output. This works when you have engineering resources, a narrow set of document types, and the time to maintain extraction logic as formats change.
The cost is in the edge cases. Every new document layout, every merged cell, and every multi-page table requires code. The extraction pipeline that handled your first 50 invoices perfectly breaks on the 51st because the supplier changed their template.
Dedicated tools take a different approach. Instead of writing extraction rules, you upload documents and get structured data back, with confidence scoring, schema enforcement, and integrations to accounting platforms. The automated data extraction market is projected to reach $4.90 billion globally by 2027.
The build-versus-buy decision comes down to volume and variability. If you process a handful of PDFs per month, all from the same source, Python scripts work. If you process hundreds of PDFs from dozens of suppliers with different layouts, a dedicated extraction tool with confidence scoring and schema enforcement saves more time than any script.
Zerentry's approach targets the middle ground where accounting teams live. The system classifies each document automatically, extracts vendor, amounts, VAT, line items, and tracking categories, then syncs directly to Xero or QuickBooks. No templates, no manual rules, no code. You can test extraction on your own documents without signing up, using the free OCR text extractor.
The right extraction method depends on the PDF type. Start there. The tool choice follows.
Extract data from any PDF without writing a pipeline
Zerentry classifies, extracts, and semantically indexes every document your team uploads, with confidence scoring and direct Xero or QuickBooks sync. Free for 30 documents/month — no credit card required.
Start free →