Introduction

PDF files are widely used to store invoices, reports, contracts, application forms, product documents, and business records. Although these files contain useful information, extracting that information into an application is not always straightforward. A PDF may contain paragraphs, tables, headings, images, and scanned pages. Reading all of this as plain text often removes the relationships between different parts of the document.

For example, an invoice may contain a customer name, invoice number, date, and a table of purchased products. A basic text extraction tool can retrieve the words, but it may not preserve which values belong to which table columns. This becomes a problem when an application needs to process the information automatically.

.NET now provides a common abstraction for document extraction through DocumentExtractionClient, available in the Microsoft.Extensions.DocumentExtraction package. It allows applications to extract document content into a shared structure without tightly coupling the application to one extraction provider.

This article explains how to use DocumentExtractionClient to extract structured content from PDFs, inspect headings and tables, access source information, and choose an extraction provider based on the type of PDF being processed.

What Is DocumentExtractionClient?

DocumentExtractionClient is a .NET abstraction designed to extract content from documents through a consistent API. Instead of writing separate application logic for every PDF parser or document processing service, developers can work with a common result structure.

The API accepts a document stream, an identifier, and a media type. It then returns an ExtractionDocument containing sections and elements representing the extracted content.

The result can include:

  • Text paragraphs and headings.

  • Tables with rows, columns, and cell information.

  • Images and figures.

  • Source information identifying the page and document region.

  • Nested sections representing the document structure.

The important benefit is that the application does not need to understand the internal result format of every provider. A local PDF parser, a vision model, or a cloud document processing service can produce results through the same abstraction.

DocumentExtractionClient is currently a preview API, so its package versions and provider implementations may change. Review the package documentation before using it in a production application.

Understanding the Available Extraction Providers

DocumentExtractionClient defines the common API, but an extraction provider performs the actual document processing. Different providers have different capabilities, performance characteristics, and infrastructure requirements.

Some providers work locally, while others send documents to cloud services or AI models.

Provider

Processing location

Suitable use case

PdfPig

Local application

PDFs containing selectable text

Vision language model

Local or hosted model

Scanned pages and image-based documents

Azure Content Understanding

Azure

Documents requiring layout, table, and image analysis

Azure AI Document Intelligence

Azure

OCR, tables, and page-level coordinates

Mistral OCR

Hosted service

OCR for PDFs and images

The PdfPig provider is a useful starting point when PDFs already contain a text layer. It can extract text without requiring an external service. However, it relies on layout heuristics and may not identify complex tables or document sections as accurately as a layout-aware provider.

For scanned PDFs, a provider that supports optical character recognition is necessary. A scanned page is essentially an image, so a normal text parser may return little or no useful content.

Setting Up a .NET File-Based Application

You can experiment with document extraction without creating a complete solution containing multiple projects. A .NET file-based application is sufficient for a small extraction utility.

Install the .NET 11 SDK and create a file named ExtractPdf.cs.

Add the required package references at the beginning of the file:

Code
#!/usr/bin/env dotnet
#:package [email protected]
#:package [email protected]

These package references provide the common document extraction abstraction and the PdfPig provider.

The exact preview package versions may change. Use compatible versions from the current package releases when setting up your application.

Extracting Content From a PDF

The first implementation creates a PdfPigDocumentExtractionClient, opens a PDF file, and passes its stream to ExtractAsync.

C#
using CommunityToolkit.DocumentExtraction.PdfPig;
using Microsoft.Extensions.DocumentExtraction;
using Microsoft.Extensions.Documents;

string filePath = args.Length > 0
    ? args[0]
    : "invoice.pdf";

if (!File.Exists(filePath))
{
    Console.WriteLine("PDF file not found.");
    return;
}

using DocumentExtractionClient extractor =
    new PdfPigDocumentExtractionClient();

await using FileStream input =
    File.OpenRead(filePath);

ExtractionDocument document =
    await extractor.ExtractAsync(
        input,
        Path.GetFileName(filePath),
        "application/pdf");

Console.WriteLine($"Document: {document.Identifier}");
Console.WriteLine($"Sections: {document.Sections.Count}");

The implementation starts by creating the extraction client. The client is responsible for processing the document through the selected provider.

The PDF is opened as a stream rather than being loaded into a string. This is useful because document extraction APIs work with streams and can process the source without requiring the application to convert the entire file into text first.

The ExtractAsync method receives three important values:

  • The input stream containing the PDF.

  • An identifier, usually the file name.

  • The media type, which identifies the document format.

The method returns an ExtractionDocument. This object represents the extracted content and provides access to its sections and elements.

Reading Text and Headings From the Extracted Document

After extraction, the next step is to inspect the document structure.

A section can contain multiple elements, including text, tables, images, and nested sections. Text elements can also include heading information when the provider is able to identify it.

The following example walks through the top-level sections and prints their content:

C#
foreach (var section in document.Sections)
{
    Console.WriteLine("Section");

    foreach (var element in section.Elements)
    {
        if (element is ExtractionDocumentTextElement textElement)
        {
            string text = textElement.Content is TextContent content
                ? content.Text
                : string.Empty;

            if (textElement.HeadingLevel.HasValue)
            {
                Console.WriteLine(
                    $"Heading: {text}");
            }
            else
            {
                Console.WriteLine(
                    $"Text: {text}");
            }
        }
    }
}

This example checks whether an element is an ExtractionDocumentTextElement before reading its content.

The HeadingLevel property helps distinguish headings from ordinary text. This is particularly useful when building search indexes or preparing documents for AI applications because headings provide context about the paragraphs that follow them.

However, heading detection depends on the provider. A basic PDF parser may use font size and text position as clues, while a layout-aware service may use additional document structure information. Therefore, applications should not assume that every extracted paragraph will have a heading classification.

Reading Tables From PDF Documents

Tables are one of the most important parts of structured document extraction.

Consider an invoice containing a table with product names, quantities, unit prices, and totals. Extracting these values as independent text lines makes it difficult to determine which quantity belongs to which product.

DocumentExtractionClient represents extracted tables through ExtractionDocumentTableElement. Its Cells collection provides information about the table structure.

The following example identifies tables and reads their cells:

C#
foreach (var element in document.EnumerateContent())
{
    if (element is not ExtractionDocumentTableElement table)
    {
        continue;
    }

    Console.WriteLine(
        $"Table: {table.Cells.RowCount} rows, " +
        $"{table.Cells.ColumnCount} columns");

    foreach (var cell in table.Cells)
    {
        if (cell is null)
        {
            continue;
        }

        string cellText = cell.Content is TextContent content
            ? content.Text
            : string.Empty;

        Console.WriteLine(
            $"Row: {cell.RowIndex}, " +
            $"Column: {cell.ColumnIndex}, " +
            $"Value: {cellText}");
    }
}

The table exposes its row and column counts, while each cell provides its position within the grid.

Some documents contain merged cells. For example, a table may have one heading covering multiple columns. The RowSpan and ColumnSpan properties help identify these cases.

This information is important when converting extracted tables into JSON, database records, or spreadsheet data. Without cell positions and spans, the application may lose the original relationships between values.

Why EnumerateContent Is Important

One common mistake when working with extracted documents is assuming that all content exists directly inside the first level of document sections.

DocumentExtractionClient supports nested sections. A provider may organize a document using multiple levels, such as chapters, sections, and subsections. A simple loop over the top-level sections may therefore miss content stored deeper in the document structure.

The EnumerateContent method provides a convenient way to access content elements throughout the document tree.

For example, you can find all extracted tables without manually writing recursive code:

C#
var tables = document.EnumerateContent()
    .OfType<ExtractionDocumentTableElement>();

foreach (var table in tables)
{
    Console.WriteLine(
        $"Found table with {table.Cells.RowCount} rows.");
}

The same approach can be used to locate text elements and images.

For production applications, this method is useful when the input documents have different structures. You can process all available content without depending on how a particular provider organizes its sections.

Accessing the Original Source Information

Extracted text is useful, but applications sometimes need to identify where the information came from.

For example, an invoice processing application may extract a total amount and display the original PDF page where that value appeared. A document search application may show the page number alongside a matching paragraph.

Document extraction elements can contain Sources information. These source references identify the page and, when available, the region associated with the extracted element.

A simple example is:

C#
foreach (var element in document.EnumerateContent())
{
    if (element is not ExtractionDocumentTextElement textElement)
    {
        continue;
    }

    string text = textElement.Content is TextContent content
        ? content.Text
        : string.Empty;

    var source = textElement.Sources.FirstOrDefault();

    int? pageNumber = source?.Page.PageNumber;

    Console.WriteLine(
        $"Page: {pageNumber?.ToString() ?? "Unknown"}");

    Console.WriteLine(text);
}

The exact source details available depend on the provider. Some providers can return page coordinates or region information, while others may provide only page-level references.

This information can support document previews, audit trails, and source citations in AI-powered applications.

Choosing the Right Provider for Your Application

The common API makes it easier to change providers, but it does not make their capabilities identical.

Before selecting a provider, consider the documents your application receives and the level of accuracy required.

Requirement

Recommended approach

Extract text from normal PDFs

Local PdfPig provider

Process scanned PDFs

OCR-capable provider

Identify complex tables

Layout-aware document service

Analyze figures and images

Vision language model or document service

Keep processing within your environment

Local provider, where its capabilities are sufficient

Process different document formats

Provider that supports those formats

For example, a small internal tool that reads digitally generated PDF reports may work well with PdfPig. A financial application that processes scanned invoices may need an OCR service with table recognition.

It is also important to consider data privacy. A local provider can process supported documents without sending their content to an external service. Hosted providers may offer more advanced extraction features, but the document is sent outside the application environment. Review the provider's data handling requirements before processing confidential business documents.

Best Practices for Production Applications

Validate the input file

Do not assume that every uploaded file is a valid PDF. Check file size, extension, media type, and any application-specific restrictions before starting extraction.

Handle scanned documents

A PDF can open normally in a viewer but still contain no selectable text. A text-based parser may return almost nothing in this situation. Detect insufficient extracted content and route the document to an OCR-capable provider when appropriate.

Preserve table structure

Avoid converting every extracted element into a plain string immediately. Keep row positions, column positions, and merged-cell information until the application has completed its required processing.

Use cancellation tokens

Document extraction may involve file processing, OCR, or remote service calls. Pass cancellation tokens through asynchronous operations so that requests can stop when a user cancels an upload or a service request times out.

Review extracted values

Document extraction is not the same as business validation. An invoice total, tax amount, or account number should be checked against application rules before being saved or used in financial calculations.

Log processing details without exposing document content

Record the document identifier, provider name, processing status, duration, and errors. Avoid logging confidential document text or sensitive extracted values unless the application has a clear and approved requirement.

Common Mistakes to Avoid

One common mistake is using a text-only parser for scanned PDFs. Since scanned pages contain images rather than an embedded text layer, the parser may return empty or incomplete results.

Another mistake is assuming that every provider identifies headings and tables in the same way. The common extraction model provides a consistent structure, but the quality and detail of the results depend on the provider.

Developers should also avoid processing only the top-level sections. Nested content can be missed unless the application walks the complete document structure through EnumerateContent or an equivalent recursive traversal.

Finally, do not treat extracted values as verified business data. A parser can misread characters, miss a table boundary, or return an incorrect value from a low-quality scan. Important fields should pass through validation before they affect business operations.

Advantages and Disadvantages

Advantages

  • Provides a common API for different document extraction providers.

  • Supports structured content such as text, headings, tables, and images.

  • Makes it easier to replace one provider without rewriting the entire application.

  • Supports source information that can help identify the original page or region.

  • Can be integrated with other .NET AI and data ingestion components.

Disadvantages

  • The API and starter providers are currently in preview.

  • Extraction quality depends on the selected provider and input document.

  • Basic local PDF parsing may not recognize complex layouts accurately.

  • OCR and hosted services can introduce additional processing time and infrastructure costs.

  • Applications still need validation and error-handling logic for extracted business data.

Summary

DocumentExtractionClient provides a common approach to extracting structured content from PDFs and other supported document formats in .NET. Instead of building application logic around one specific parser or cloud service, developers can work with a shared ExtractionDocument structure.

The API supports text, headings, tables, images, nested sections, and source information. Methods such as ExtractAsync and EnumerateContent make it possible to build document processing utilities without depending on a provider-specific result format.

The most important design decision is choosing the right provider. A local parser may be sufficient for digitally generated PDFs, while scanned documents and complex layouts may require OCR or a layout-aware service.

For applications that process invoices, reports, contracts, and other business documents, DocumentExtractionClient offers a useful foundation for building document extraction, search, automation, and AI-powered workflows in .NET.