DEV Community

Cover image for How to Extract Specific Fields from PDFs Using Open-Source AI and LLMs
Lyraethyx
Lyraethyx

Posted on

How to Extract Specific Fields from PDFs Using Open-Source AI and LLMs

How to Extract Specific Fields from PDFs Using Open-Source AI and LLMs

Moving beyond PDF-to-text conversion: a technical guide to semantic field extraction, document preprocessing, LLM orchestration, confidence scoring, and human validation using elDoc IDP OSS.

1. Why Extracting Text from a PDF Is Not Enough

Extracting text from PDFs is a well-established capability. Libraries such as Apache PDFBox, Docling, PyMuPDF, and PaddleOCR provide developers with several approaches to accessing document content.

However, most business applications do not need the entire text of a document.

They need specific information:

  • Invoice numbers and payment amounts.
  • Customer names and account identifiers.
  • Contract dates and reference numbers.
  • Insurance policy details.
  • Bank transaction information.
  • Purchase order numbers.
  • Product descriptions and quantities.

The engineering challenge is not simply recognizing text. It is identifying the correct value for each required field, regardless of where that value appears in the document.

Traditional approaches rely heavily on regular expressions, positional coordinates, and document-specific templates. These methods can work well for predictable layouts but become increasingly difficult to maintain when processing documents from hundreds of different organisations.

Large Language Models (LLMs) introduce an alternative approach to this challenge: semantic field extraction, where information is identified based on its business meaning and contextual relationships rather than predefined coordinates or rigid document templates.

This approach is incorporated into elDoc IDP OSS (https://github.com/elDocAI/elDoc-idp-oss), an open-source, self-hosted Intelligent Document Processing application that serves as the technical case study for this article. Its architecture combines Java-based document processing, advanced image preprocessing, configurable OCR engines, LLM-agnostic integration, MongoDB persistence, and human-in-the-loop validation within a unified, end-to-end document extraction workflow.


2. Understanding the Difference Between Text Extraction and Field Extraction

Consider the following invoice content:

NORTHWIND TECHNOLOGIES LTD.

Invoice Reference: INV-2026-00482
Issued: 15 November 2026
Payment Due: 15 December 2026

Customer: Contoso Limited
Purchase Order: PO-78452

Net Amount: 12,500.00
VAT: 2,500.00
Gross Amount: 15,000.00

Previous Payment: 5,000.00
Outstanding Balance: 10,000.00
Enter fullscreen mode Exit fullscreen mode

A PDF parser can successfully recover the text.

An OCR engine can recognize the same information from a scanned image.

But neither operation alone determines which value should populate the total_invoice_amount field.

The document contains several monetary values, each with a different business meaning.

A field-oriented extraction system must produce something closer to:

Target field Extracted value
Supplier name Northwind Technologies Ltd.
Customer name Contoso Limited
Invoice number INV-2026-00482
Invoice date 2026-11-15
Due date 2026-12-15
Purchase order PO-78452
Net amount 12500.00
Tax amount 2500.00
Total invoice amount 15000.00
Outstanding balance 10000.00

This transformation requires semantic understanding.

The extraction system must distinguish the supplier from the customer, the invoice date from the payment deadline, and the gross invoice amount from the outstanding balance.

Field-level extraction is a document understanding problem, not merely a text recognition problem.


3. Three Technical Approaches to Extracting Specific PDF Fields

Approach 1: Regular expression-based extraction

A common implementation uses regular expressions to identify values following known labels.

import re

text = """
Invoice Number: INV-2026-00482
Total Amount: 15000.00
"""

invoice_number = re.search(
    r"Invoice Number:\s*(\S+)",
    text
)

total_amount = re.search(
    r"Total Amount:\s*([\d,.]+)",
    text
)
Enter fullscreen mode Exit fullscreen mode

This approach is computationally inexpensive, deterministic, and easy to test.

However, it depends on predictable document content.

The same invoice identifier could appear under several labels:

Invoice Number
Invoice Reference
Invoice ID
Document No.
Billing Reference
Enter fullscreen mode Exit fullscreen mode

Every additional variation can introduce another rule or require existing rules to become more complex.

Regular expressions remain useful for well-defined patterns, but they are difficult to scale across highly variable document layouts.

Approach 2: Coordinate-based extraction

Another traditional approach extracts information from predefined regions of a document.

invoice_number:
    page: 1
    x: 420
    y: 110
    width: 150
    height: 30
Enter fullscreen mode Exit fullscreen mode

This can be effective for standardised forms.

However, changes in layout, page dimensions, scan orientation, or field position may invalidate the configuration.

Maintaining coordinate-based templates across hundreds of document formats can introduce substantial engineering overhead.

Approach 3: LLM-powered semantic extraction

LLM-based extraction attempts to identify fields according to their meaning rather than their fixed position.

A conceptual extraction instruction might describe the required fields as follows:

Field: invoice_number
Description: Unique invoice identifier assigned
by the supplier.

Field: invoice_date
Description: Date on which the invoice was issued,
not the payment due date.

Field: total_invoice_amount
Description: Full invoice amount including tax,
before deducting previous payments.

Field: outstanding_balance
Description: Remaining amount payable after
previous payments or credits.
Enter fullscreen mode Exit fullscreen mode

Instead of relying exclusively on labels or coordinates, the extraction model evaluates the surrounding document context.

This approach is particularly relevant when processing documents with heterogeneous layouts.

It does not eliminate extraction errors, but it reduces dependence on document-specific positional templates.


4. Designing a Technical Pipeline for AI-Based PDF Field Extraction

A functional document extraction architecture requires several processing stages.

              PDF / TIFF / Image
                       |
                       v
              Document Ingestion
                       |
                       v
           PDF Parsing / Page Decoding
                       |
                       v
              Image Normalization
                       |
                       v
             OCR / Visual Recognition
                       |
                       v
             Document Classification
                       |
                       v
             Semantic Field Extraction
                       |
                       v
               Field Validation
                       |
                       v
              Exception Detection
                       |
                       v
            Human-in-the-Loop Review
                       |
                       v
              Structured Data Export
Enter fullscreen mode Exit fullscreen mode

Each stage addresses a separate technical problem.

Processing stage Technical responsibility
Document ingestion Accept supported input formats
PDF parsing Access embedded text and page content
Image normalization Improve visual input consistency
OCR Recognize text from scanned pages
Document classification Determine the business document type
Semantic extraction Associate document values with required fields
Validation Identify potentially incorrect or missing values
Persistence Maintain document processing results
Human review Inspect and correct extracted information
Export Deliver structured business data

A developer can implement this architecture by combining individual libraries and AI services.

Alternatively, an integrated application such as elDoc IDP OSS provides an existing implementation covering these processing stages.


5. Open-Source Technology Stack for Field-Level PDF Extraction

The architecture of elDoc IDP OSS is particularly interesting because it combines modern generative AI capabilities with established Java and native document processing technologies.

Architectural component Technology
Backend runtime Java 21
Application framework Jakarta EE
Application server Payara Micro
Web interface Jakarta Faces / PrimeFaces
PDF processing Apache PDFBox
Image format handling TwelveMonkeys ImageIO
Computer vision OpenCV
Native library integration Bytedeco / JavaCPP
Default OCR engine Tesseract
Alternative recognition options PaddleOCR and vision-language models
LLM integration LangChain4j
Document-oriented persistence MongoDB
Build and dependency management Apache Maven
Structured output CSV

This architecture illustrates an important distinction between a document extraction library and an integrated IDP application.

Java provides the application infrastructure, while specialised libraries and AI models perform individual recognition and document understanding tasks.

Developers can therefore work with an existing application rather than independently implementing document ingestion, processing orchestration, model integration, persistence, and validation interfaces.


6. Handling Machine-Generated PDFs, Scanned PDFs and Multipage TIFFs

Not all PDFs contain accessible text.

A machine-generated PDF may contain text objects and embedded fonts, whereas a scanned PDF may consist entirely of raster images.

A hybrid PDF may contain both.

These differences affect the extraction architecture.

Document type Primary technical challenge
Machine-generated PDF Text extraction and reading order
Scanned PDF Image preprocessing and OCR
Hybrid PDF Combining embedded and image-based content
Multipage TIFF Decoding multiple image frames
Complex PDF Understanding relationships between visual elements
Low-quality scan Recognition under noise and distortion

An application designed exclusively around PDF text extraction may fail when the source document contains no usable text layer.

elDoc IDP OSS supports digital and scanned PDFs, image formats, and multipage TIFF inputs.

Its underlying document processing technologies include Apache PDFBox and TwelveMonkeys ImageIO.

Cross-page field extraction

Consider a five-page invoice:

Page 1: Supplier information and invoice number
Page 2: Product descriptions
Page 3: Continued line items
Page 4: Additional charges
Page 5: Tax and final invoice total
Enter fullscreen mode Exit fullscreen mode

Extracting individual pages independently may lose the relationship between the invoice identifier and its final amount.

A document-level extraction workflow must preserve sufficient context to associate information distributed across multiple pages.

Developers should evaluate this behaviour explicitly, particularly for long documents, tables spanning multiple pages, and files containing several logically distinct business documents.

Supporting a multipage file format is not automatically equivalent to accurately reconstructing every cross-page relationship.


7. Image Normalization: Improving the Input Before AI Extraction

The quality of field extraction often depends on the quality of upstream recognition.

Low-quality scans may contain rotated pages, skewed text, compression artefacts, or inconsistent contrast.

How to extract specific fields from PDFs using open-source AI and LLMs with elDoc IDP OSS, Java, MongoDB, OCR and LangChain4j

These defects can propagate through the processing pipeline:

Poor image quality
        |
        v
Incorrect OCR recognition
        |
        v
Ambiguous document content
        |
        v
Incorrect semantic interpretation
        |
        v
Incorrect extracted field
Enter fullscreen mode Exit fullscreen mode

For example, an OCR error may transform an invoice identifier:

Original:   INV-10058
Recognized: INV-I0058
Enter fullscreen mode Exit fullscreen mode

A model may correctly identify the invoice number field but still return an incorrect value because the source recognition was inaccurate.

elDoc incorporates normalization, deskewing, and rotation correction.

Its use of OpenCV and Bytedeco provides a native computer vision foundation accessible from the Java application.

Preprocessing should nevertheless be evaluated against representative documents. Aggressive image transformations can sometimes remove information that is important for recognition.


8. Choosing Between Tesseract, PaddleOCR and Vision-Language Models

Different recognition engines can produce substantially different results depending on the document characteristics.

Tesseract

Tesseract is an established open-source OCR engine based on traditional recognition techniques and LSTM neural networks.

It is suitable for many local text recognition workloads and does not require a commercial OCR API.

PaddleOCR

PaddleOCR uses deep-learning-based recognition and document understanding models.

Its ecosystem includes text detection, recognition, document structure analysis, and visual document understanding.

It is particularly relevant when evaluating more challenging layouts and image-based inputs.

Vision-language models

Vision-language models can interpret visual information alongside linguistic context.

This can be valuable for documents containing complex tables, visually grouped information, and irregular field relationships.

However, multimodal inference may introduce higher computational costs, latency, and additional reliability considerations.

elDoc uses embedded Tesseract by default while offering configurable PaddleOCR and vision-language recognition options.

PaddleOCR can therefore operate as a component within the elDoc processing chain rather than as an alternative to the entire application.

             Document Image
                    |
                    v
            Recognition Layer
          /         |         \
   Tesseract    PaddleOCR     VLM
          \         |         /
                    v
           Semantic Extraction
                    |
                    v
            Business Field Data
Enter fullscreen mode Exit fullscreen mode

This is a conceptual representation of the recognition alternatives, not a requirement to execute all three engines simultaneously.


9. Defining Specific Fields for LLM-Powered Extraction

Field definition is one of the most important elements of semantic data extraction.

A field name alone may not provide sufficient context for an AI model.

For example:

Date
Amount
Reference
Name
Enter fullscreen mode Exit fullscreen mode

These fields are ambiguous because a document may contain multiple dates, amounts, references, and names.

A more precise extraction configuration defines the intended business meaning.

Field identifier Semantic definition Expected data type
invoice_number Identifier assigned by the invoice issuer String
supplier_name Organisation issuing the invoice String
invoice_date Date the invoice was issued Date
due_date Deadline for invoice payment Date
tax_amount Tax charged on the invoice Decimal
total_amount Full invoice amount including tax Decimal
currency Currency explicitly specified in the document String
purchase_order Customer purchase order reference String

Clear field definitions can help reduce semantic ambiguity.

Developers should also define expected behaviour when a value is missing.

For instance, an extraction policy should distinguish between a missing value, an empty value, and a numeric zero.

A missing tax amount is not necessarily equivalent to a tax amount of zero.

Similarly, identifiers should generally be treated as strings because numeric conversion can remove leading zeros.

Example of semantic extraction requirements

Extract the invoice number assigned by the supplier.

Do not confuse it with:
- Purchase order number
- Customer account number
- Tax registration number
- Payment reference

Preserve the original identifier format.

If the value is not present, leave it empty.
Do not infer or generate a replacement value.
Enter fullscreen mode Exit fullscreen mode

This is an illustrative extraction requirement, not a literal elDoc configuration file.

In elDoc IDP OSS, users can configure document recognition fields through the integrated application or experiment with its automatic processing capabilities.

This provides a practical alternative to developing a separate prompt-management and extraction configuration interface from scratch.


10. LLM-Agnostic Architecture: Why Model Independence Matters

Document extraction performance varies across AI models.

A model that performs well on clean invoices may behave differently when processing handwritten annotations, multilingual documents, or complex financial tables.

Model selection should therefore be considered an architectural configuration rather than a permanent application dependency.

elDoc supports AI configurations for OpenRouter, AWS Bedrock, OpenAI-compatible endpoints, and compatible local model servers.

The application distinguishes between two important model capabilities:

  • Agent models capable of tool calling.
  • Vision-language models capable of interpreting images.

An OpenAI-compatible endpoint does not necessarily guarantee support for both capabilities.

Developers should verify functional compatibility before selecting a model.

Model evaluation criteria

Criterion Why it matters
Semantic extraction accuracy Correct association of values with fields
Vision capabilities Understanding image-based documents
Tool calling Compatibility with agent workflows
Context window Processing long document content
Multilingual understanding Handling documents in different languages
Inference latency Processing responsiveness
Token cost Operational expenditure
Deployment model Local or externally hosted inference

A self-hosted application combined with a compatible local model can provide greater control over document processing infrastructure.

However, self-hosting the application does not automatically mean that document content remains local.

The selected OCR engine, AI provider, network configuration, and external integrations determine the actual data processing boundary.


11. MongoDB: Persisting Heterogeneous Document Extraction Results

Different business documents require different extraction structures.

An invoice may contain monetary amounts and supplier information.

A utility bill may contain account identifiers and consumption values.

An application form may contain personal information, reference numbers, and declarations.

A document-oriented database is relevant to this processing model because the extracted data does not necessarily conform to one universal tabular schema.

Conceptually:

Invoice document
    invoice_number
    supplier_name
    total_amount
    tax_amount

Utility bill
    account_number
    billing_period
    consumption
    amount_due

Application form
    applicant_name
    application_date
    reference_number
Enter fullscreen mode Exit fullscreen mode

MongoDB provides a flexible persistence model for heterogeneous document-oriented application data.

elDoc integrates MongoDB rather than leaving persistence entirely to downstream developers.

A local evaluation can use its embedded database configuration, while production-oriented deployments should use a separately managed MongoDB replica set with appropriate authentication, TLS, backup, monitoring, and availability controls.

The examples above illustrate document-oriented persistence concepts and do not represent elDoc's actual internal database schema.


12. Field-Level Confidence Scoring and Human-in-the-Loop Validation

LLM-powered extraction should not be treated as infallible.

Even when a model correctly identifies the intended business field, the extracted value may be incorrect due to OCR errors, ambiguous document content, or semantic confusion.

Consider the following illustrative extraction result:

Target field Extracted value Field score Validation
Invoice number INV-2026-00482 99% Accepted
Supplier name Northwind Technologies 96% Accepted
Invoice date 2026-11-15 97% Accepted
Tax amount 2,500.00 74% Review
Total amount 15,000.00 98% Accepted

With a hypothetical threshold of 90%, the tax amount would require human attention.

In elDoc, the human-in-the-loop validation interface allows users to inspect extracted fields and correct exceptions.

Field-level scoring and configurable thresholds help identify values requiring attention. Fields falling below the defined threshold can be highlighted in red.

This creates a more practical extraction workflow than simply returning an LLM-generated response.

Confidence scores are not guarantees

A confidence score should not automatically be interpreted as a calibrated probability that a field is correct.

For example, a score of 95% does not necessarily establish that 95 out of every 100 similarly scored fields will be accurate.

Confidence thresholds should be evaluated against real extraction errors.

A useful validation strategy should also consider deterministic business rules.

For an invoice, possible rules include:

subtotal + tax = total

total - previous_payments = outstanding_balance

due_date >= invoice_date
Enter fullscreen mode Exit fullscreen mode

These are examples of recommended validation logic that developers can implement around an extraction workflow.

Combining AI-based interpretation, deterministic validation, and human review can help reduce the risk of incorrect business data entering downstream workflows.


13. Getting Started: Extract Specific PDF Fields Using elDoc IDP OSS

The application is available through its public repository:

https://github.com/elDocAI/elDoc-idp-oss

Step 1: Clone and build the application

Install JDK 21 and clone the repository.

git clone https://github.com/elDocAI/elDoc-idp-oss.git

cd elDoc-idp-oss

./mvnw clean verify
Enter fullscreen mode Exit fullscreen mode

On Windows:

.\mvnw.cmd clean verify
Enter fullscreen mode Exit fullscreen mode

The Maven build produces an executable Payara Micro application with platform-specific native dependencies.

Build the application on the operating system and CPU architecture where it will run.

Step 2: Configure an AI provider

The application configuration is located in:

configs/eldoc-idp-oss.conf
Enter fullscreen mode Exit fullscreen mode

Provider configuration examples are available in the same directory.

The default configuration includes an OpenRouter preset:

configs/eldoc-idp-oss-ai.openrouter.conf
Enter fullscreen mode Exit fullscreen mode

Configure the required credentials and compatible AI models according to the repository documentation.

Keep API tokens outside version control.

Step 3: Launch the application

For the documented Linux build of version 7.2026.4:

java \
  -Dai.eldoc.idp-oss.configDir=configs \
  -jar modules/eldoc-idp-web/target/elDoc-idp-oss-7.2026.4-server-linux.jar
Enter fullscreen mode Exit fullscreen mode

Adjust the executable name for your build version and platform.

During initial startup, the application may download MongoDB binaries and approximately 1.4 GB of Tesseract language data.

If no maintenance password is provided, the application generates one and prints it to the startup console.

Once initialization completes, open:

http://localhost:8080
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure document recognition fields

Define the information you want to extract.

For an invoice processing experiment, begin with:

Invoice Number
Supplier Name
Invoice Date
Due Date
Currency
Tax Amount
Total Amount
Enter fullscreen mode Exit fullscreen mode

Start with a limited number of fields and expand the extraction configuration after evaluating the initial results.

Step 5: Upload representative documents

Test multiple input variations:

  • Digitally generated invoices.
  • Scanned PDF invoices.
  • Multipage invoices.
  • Documents from different suppliers.
  • Rotated or low-quality scans.
  • Documents with missing fields.
  • Multipage TIFF files.

Testing only one clean document provides little evidence about extraction reliability across realistic workloads.

Step 6: Review extracted information

Use the integrated validation interface to inspect the source document and extracted values.

Review exceptions and correct inaccurate results where necessary.

Step 7: Export structured business data

The open-source edition provides CSV export through its web interface.

An illustrative CSV output could look like:

invoice_number,supplier_name,invoice_date,total_amount
INV-2026-00482,Northwind Technologies,2026-11-15,15000.00
INV-2026-00483,Contoso Limited,2026-11-16,8450.00
INV-2026-00484,Fabrikam Services,2026-11-18,6200.00
Enter fullscreen mode Exit fullscreen mode

This transforms heterogeneous document inputs into a consistent business-oriented data structure.

For additional configuration and deployment details, consult the official GitHub repository.


14. How to Measure Field-Level Extraction Accuracy

OCR accuracy and field extraction accuracy are different metrics.

Character Error Rate (CER) measures recognition errors at the character level:

CER = (Substitutions + Deletions + Insertions)
      / Total reference characters
Enter fullscreen mode Exit fullscreen mode

Field-level exact-match accuracy measures whether the extracted business value matches the expected result:

Field Accuracy =
Correctly Extracted Fields / Expected Fields
Enter fullscreen mode Exit fullscreen mode

A document processing system should also be evaluated at the complete document level.

Consider a document containing 15 mandatory fields.

If each field independently has a 98% probability of being correct:

document_accuracy = 0.98 ** 15

print(document_accuracy)
Enter fullscreen mode Exit fullscreen mode

Result:

0.7385691026
Enter fullscreen mode Exit fullscreen mode

Under this simplified assumption, only approximately 73.9% of documents would have every mandatory field extracted correctly.

Real extraction errors may be correlated, but the example demonstrates why high individual field accuracy does not necessarily translate into reliable document-level automation.

Recommended benchmark metrics

Metric Evaluation objective
Character Error Rate OCR recognition quality
Field exact-match accuracy Correct business value extraction
Normalized field accuracy Accuracy after appropriate format normalization
Field precision and recall Incorrect and missing extraction results
Document-level accuracy Documents with all mandatory fields correct
Exception detection rate Errors correctly identified for review
False acceptance rate Incorrect fields accepted without review
Human correction time Manual validation effort
Processing latency Processing time per document
Cost per document AI inference and infrastructure expenditure

For practical IDP workloads, reducing the false acceptance rate can be as important as improving average extraction accuracy.


Final Thoughts: Extract Business Information, Not Just Document Content

Open-source technologies have made PDF parsing, OCR, and document understanding increasingly accessible.

However, extracting specific fields from PDFs requires more than converting documents into machine-readable text.

A practical solution needs to combine recognition, semantic interpretation, configurable extraction requirements, validation, and structured data delivery.

elDoc IDP OSS represents an application-oriented approach to this challenge.

By integrating established technologies such as Apache PDFBox, OpenCV, Tesseract, PaddleOCR, LangChain4j, Java, and MongoDB, it provides developers with a functional foundation for AI-powered business data extraction.

The application is free to use under its AGPL licence terms, with infrastructure and inference costs depending on the chosen configuration.

For developers looking to move beyond OCR and document parsing towards reliable, field-level AI data extraction, elDoc IDP OSS provides a ready-to-deploy, self-hosted starting point that can be configured, customised, and extended.

Explore the source code, experiment with your own documents, and contribute to the project: https://github.com/elDocAI/elDoc-idp-oss


Technical references

Technical scope: This article focuses on the open-source edition of elDoc IDP. Numerical examples, sample documents, extraction definitions, and validation rules are illustrative.

Top comments (0)