---
title: "Extract key-value pairs from a PDF in C#"
url: https://recursiveai.org/oneocr/cookbook/extract-key-value-pairs-from-pdf/
description: "Read a scanned PDF into OCR pages and extract labeled fields such as name, date, and city. Keep the key-value pairs grouped by page."
version: "1.1.0"
---

Call `FindKeyValues()` on each PDF page to pair labels with values.

This works on visible text, not on the internal names of interactive PDF form fields.

```shell
dotnet add package RecursiveAI.OneOcr.Pdf
dotnet add package RecursiveAI.OneOcr.Models.Documents
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneOcr;
using OneOcr.Documents;
using OneOcr.Models.Documents;
using OneOcr.Pdf;

DocumentModels.Configure();
var engine = OcrEngine.LoadBundled();
var pages = PdfOcr.Read("form.pdf", engine);
foreach (var page in pages)
{
    string Text(IEnumerable<int> ids) =>
        string.Join(" ", ids.Select(
            i => page.Words[i].Text));
    foreach (var pair in page.FindKeyValues())
    {
        var key = Text(pair.KeyWordIndices);
        var value = Text(pair.ValueWordIndices);
        Console.WriteLine(
            $"{page.Index + 1}: {key} {value}");
    }
}
```

[The example](https://recursiveai.org/oneocr/cookbook/extract-key-value-pairs-from-pdf/extract-key-value-pairs-from-pdf.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into Program.cs of a new `dotnet new console` project and `dotnet run`.

`form.pdf` comes in the zip. The snippet prints:

```text
1: Name: Ada
1: City: Boston
1: Date: 2026-11-21
2: Name: Jay Ford
2: City: Denver
2: Date: 2026-11-22
```

## The full program

The input is a two-page sample scan with no selectable text. Page 1 shows `Name: Ada`, `City: Boston`, and `Date: 2026-11-21`. Page 2 shows `Name: Jay Ford`, `City: Denver`, and `Date: 2026-11-22`. `RecursiveAI.OneOcr.Pdf` brings in the bundled OCR recognizer; the separate document models package supplies the model for pairing words.

```csharp
using OneOcr;
using OneOcr.Documents;
using OneOcr.Models.Documents;
using OneOcr.Pdf;

DocumentModels.Configure();
var engine = OcrEngine.LoadBundled();
var pages = PdfOcr.Read("form.pdf", engine);

foreach (var page in pages)
{
    Console.WriteLine($"Page {page.Index + 1}");
    foreach (var pair in page.FindKeyValues())
    {
        var key = TextAt(pair.KeyWordIndices).TrimEnd(':');
        var value = TextAt(pair.ValueWordIndices);
        Console.WriteLine($"  {key} = {value}");
    }

    string TextAt(IEnumerable<int> indices) =>
        string.Join(" ", indices.Select(i => page.Words[i].Text));
}
```

```text
Page 1
  Name = Ada
  City = Boston
  Date = 2026-11-21
Page 2
  Name = Jay Ford
  City = Denver
  Date = 2026-11-22
```

If the model doesn’t find a pair on a page, the loop has nothing to print for it; an empty result doesn’t establish that the page has no fields.

## Variations

Set the render resolution for pages that need rendering. Replace the `PdfOcr.Read` call in the full example:

```csharp
var options = new PdfOcrOptions { RenderDpi = 250 };
var pages = PdfOcr.Read("form.pdf", engine, options);
```

At 250 DPI, this run omitted `City: Denver` on page 2. Check the recovered fields when changing the resolution, even on familiar scans.

## Related recipes

- [Extract key-value pairs from an image](https://recursiveai.org/oneocr/cookbook/extract-key-value-pairs-from-image/)
- [Read the text on each PDF page](https://recursiveai.org/oneocr/cookbook/ocr-pdf/)
- [Extract fields from an invoice](https://recursiveai.org/oneocr/cookbook/invoices/)

## The short answer

Use `PdfOcr.Read` to get `OcrPage` objects and `FindKeyValues()` on each page to get its pairs. A pair identifies its key and value by indices into that page’s `Words` collection. Join each group of words to recover the text. Keep the page number with the pair so that “City” on the first page doesn’t replace “City” on the second.

## What is the best way to extract data from a PDF?

Match the extraction to your input and your output. If you need the complete wording, read the pages as text. If you need labeled values from a printed form, keep the word positions: the relationship between a label and its value can be lost when you flatten two columns to plain text. `PdfOcr.Read` handles visible PDF text as well as content that needs recognition. It checks existing text rather than blindly trusting an invisible OCR layer over a scan. The resulting pages supply the word collection for the pairing step, whether the words came from PDF text or recognition. See the [OneOcr documentation](https://recursiveai.org/oneocr/docs/) for PDF reading and source information.

Key-value extraction is a model result, not a schema guarantee. A faint scan, unusual layout, or distant label can leave a pair missing or incomplete. If you have interactive form fields and need their exact stored names and values, use a PDF form reader instead of inferring data from their appearance. If you have consistent invoices and need fields with defined meanings such as amount due, consider invoice-specific extraction instead of interpreting every detected label yourself.

## How can I automate data extraction from PDFs?

Treat each page as a unit of output. Store the document identifier, page number, key, and value together. Keep the records as a list if labels may repeat even within one page; a dictionary keyed only by label drops that distinction. The word indices also let you refer back to the page’s word boxes when a reviewer needs to see where a value came from.

Before sending extracted fields downstream, check for required labels and validate values for the document type. For example, a date extracted as text should be parsed and checked by your application rather than assumed valid because it appears next to `Date`. Keep an unrecognized field distinct from a confirmed empty value, and send missing or ambiguous required fields for review. Test on forms with the layouts and scan quality you actually receive, not just on clean samples.
