Invoice processing is a common requirement in business applications. Organizations receive hundreds or thousands of invoices from vendors, customers, and service providers. These invoices contain important information such as invoice numbers, customer details, dates, product descriptions, quantities, tax amounts, and payment totals.
Traditionally, employees manually read invoices and enter the information into accounting or ERP systems. This process takes time and can introduce human errors. Developers can automate much of this work by building document processing applications that extract invoice information and convert it into structured data.
.NET provides several libraries and services for document processing. One of the newer options is DocumentExtractionClient, available through the Microsoft.Extensions.DocumentExtraction package. It provides a common interface for extracting document content through different providers.
In this article, we will build an invoice processing workflow using DocumentExtractionClient in C#. We will extract information from invoice PDFs, identify important fields, convert the extracted content into C# objects, validate financial values, and prepare the information for database storage.
Understanding Invoice PDF Processing
An invoice PDF usually contains multiple types of information. Some information appears as ordinary text, while other information is arranged in tables.
Consider the following invoice:
INVOICE
Invoice Number: INV-2026-105
Invoice Date: 15 November 2026
Customer: ABC Technologies
Email: [email protected]
Product Quantity Price
Keyboard 2 1500
Mouse 3 500
Monitor 1 12000
Subtotal: 15000
Tax: 2700
Total Amount: 17700
A business application needs to extract these values and represent them in a structured format.
For example, the invoice number should be stored as a string, the invoice date as a DateTime value, and the total amount as a decimal.
The processing workflow generally includes the following operations:
Receive an invoice PDF.
Extract text and document structure.
Identify invoice fields and line items.
Convert the extracted values into C# objects.
Validate the extracted information.
Store the validated invoice in a database.
Track processing status and errors.
DocumentExtractionClient handles the document extraction part. Additional application logic is required to identify business-specific fields and validate the invoice.
What Is DocumentExtractionClient?
DocumentExtractionClient is a common document extraction abstraction available through Microsoft.Extensions.DocumentExtraction.
It allows developers to extract document content without tightly coupling application code to a particular extraction provider.
The ExtractAsync() method accepts a document stream, an identifier, and a media type. It returns an ExtractionDocument containing structured content.
The extracted document can contain:
Text paragraphs and headings.
Tables and table cells.
Images and figures.
Nested document sections.
Source information containing page references and available coordinates.
For invoice processing, this structure is useful because an invoice contains both individual text fields and tabular information.
The .NET AI Community Toolkit provides several starter providers:
Provider | Invoice processing use case |
|---|
PdfPig | Extracting text from digitally generated invoices |
Vision Language Model | Reading scanned invoices using images |
Azure AI Document Intelligence | Extracting invoice layouts and structured fields |
Azure Content Understanding | Understanding document structure and tables |
Mistral OCR | Extracting text and layout information |
The provider selection depends on the invoice format.
For example, PdfPig is suitable when an invoice contains selectable PDF text. Scanned invoices require an OCR-capable provider.
Setting Up the .NET Project
Let's create a console application that extracts invoice information from a PDF.
First, create the project:
dotnet new console -n InvoiceProcessingApp
cd InvoiceProcessingApp
Install the required NuGet packages:
dotnet add package Microsoft.Extensions.DocumentExtraction --version 11.0.0-preview.1.26560.3
dotnet add package CommunityToolkit.DocumentExtraction.PdfPig --version 1.0.0-preview
These packages provide the document extraction abstraction and the PdfPig implementation.
For this example, we will use a digitally generated invoice containing selectable text.
Add a PDF named invoice.pdf to the project directory.
Extracting Invoice Content Using DocumentExtractionClient
The first step is to configure the extraction client and read the invoice PDF.
Create a Program.cs file with the following implementation:
using CommunityToolkit.DocumentExtraction.PdfPig;
using Microsoft.Extensions.DocumentExtraction;
using Microsoft.Extensions.Documents;
string filePath = "invoice.pdf";
if (!File.Exists(filePath))
{
Console.WriteLine("Invoice PDF not found.");
return;
}
using DocumentExtractionClient extractor =
new PdfPigDocumentExtractionClient();
await using FileStream stream = File.OpenRead(filePath);
ExtractionDocument document =
await extractor.ExtractAsync(
stream,
Path.GetFileName(filePath),
"application/pdf"
);
Console.WriteLine("Invoice extraction completed.");
foreach (var element in document.EnumerateContent())
{
if (element.Content is TextContent text)
{
Console.WriteLine(text.Text);
}
}
Let's understand the important parts.
Creating the Extraction Client
using DocumentExtractionClient extractor =
new PdfPigDocumentExtractionClient();
The PdfPigDocumentExtractionClient implementation reads the existing text layer from a PDF.
We declare the variable using the DocumentExtractionClient abstraction. This makes it easier to replace the provider later without changing the overall extraction workflow.
Reading the Invoice PDF
await using FileStream stream = File.OpenRead(filePath);
The PDF is opened as a stream instead of loading the complete file into memory manually.
This approach is useful when processing larger documents because the application can work directly with the input stream.
Calling ExtractAsync()
ExtractionDocument document =
await extractor.ExtractAsync(
stream,
Path.GetFileName(filePath),
"application/pdf"
);
The extraction method receives the PDF stream, file identifier, and MIME type.
The returned ExtractionDocument contains the extracted document structure.
Reading Extracted Text
foreach (var element in document.EnumerateContent())
{
if (element.Content is TextContent text)
{
Console.WriteLine(text.Text);
}
}
EnumerateContent() walks through the document hierarchy and returns its content elements in document order.
This is important because an invoice may contain nested sections. Reading only the first-level elements may cause the application to miss content.
Creating a C# Invoice Model
After extracting the invoice content, the next step is to convert it into a structured C# object.
Instead of storing all extracted information in a single string, create separate classes for invoice details and line items.
public class InvoiceData
{
public string InvoiceNumber { get; set; } = "";
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; } = "";
public string CustomerEmail { get; set; } = "";
public decimal Subtotal { get; set; }
public decimal Tax { get; set; }
public decimal TotalAmount { get; set; }
public List<InvoiceItem> Items { get; set; } = [];
}
public class InvoiceItem
{
public string ProductName { get; set; } = "";
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}
The InvoiceData class represents the complete invoice, while InvoiceItem represents individual products or services.
Separating these models makes the application easier to maintain and allows invoice information to be mapped to relational database tables.
Extracting Invoice Fields Using C#
DocumentExtractionClient extracts document content, but it does not automatically know that a particular paragraph represents an invoice number or total amount.
For a fixed invoice format, regular expressions can help identify common fields.
First, combine the extracted text elements:
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
StringBuilder contentBuilder = new();
foreach (var element in document.EnumerateContent())
{
if (element.Content is TextContent text)
{
contentBuilder.AppendLine(text.Text);
}
}
string invoiceText = contentBuilder.ToString();
Now create a helper method to extract values using regular expressions:
static string ExtractValue(
string text,
string pattern)
{
Match match = Regex.Match(
text,
pattern,
RegexOptions.IgnoreCase
);
return match.Success
? match.Groups[1].Value.Trim()
: "";
}
This method searches the extracted text and returns the first matching value.
Use it to identify invoice information:
string invoiceNumber = ExtractValue(
invoiceText,
@"Invoice\s+Number\s*:\s*([A-Z0-9-]+)"
);
string customerName = ExtractValue(
invoiceText,
@"Customer\s*:\s*(.+)"
);
string email = ExtractValue(
invoiceText,
@"Email\s*:\s*([\w.+-]+@[\w.-]+\.[A-Z]{2,})"
);
string invoiceDateText = ExtractValue(
invoiceText,
@"Invoice\s+Date\s*:\s*(.+)"
);
string totalText = ExtractValue(
invoiceText,
@"Total\s+Amount\s*:\s*([\d,]+(?:\.\d{1,2})?)"
);
The patterns identify values following known invoice labels.
However, regular expressions work best when invoice layouts are relatively consistent. Different vendors may use different labels, ordering, and formatting. A production application should not assume that every invoice follows the same structure.
Converting Extracted Values Into InvoiceData
Once the individual values have been extracted, convert them into their appropriate .NET types.
bool validDate = DateTime.TryParse(
invoiceDateText,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime invoiceDate
);
bool validAmount = decimal.TryParse(
totalText,
NumberStyles.Number,
CultureInfo.InvariantCulture,
out decimal totalAmount
);
if (!validDate || !validAmount ||
string.IsNullOrWhiteSpace(invoiceNumber))
{
Console.WriteLine(
"Invoice contains missing or invalid information."
);
return;
}
InvoiceData invoice = new()
{
InvoiceNumber = invoiceNumber,
InvoiceDate = invoiceDate,
CustomerName = customerName,
CustomerEmail = email,
TotalAmount = totalAmount
};
Console.WriteLine(
$"Invoice Number: {invoice.InvoiceNumber}"
);
Console.WriteLine(
$"Customer: {invoice.CustomerName}"
);
Console.WriteLine(
$"Total: {invoice.TotalAmount}"
);
TryParse() is preferable to directly converting strings because it allows the application to handle invalid values without throwing an exception.
For financial applications, decimal should be used instead of double or float because decimal is designed for decimal arithmetic and is generally more appropriate for currency calculations.
The example uses a fixed invoice format. Real applications should also support different date formats, currency symbols, locale-specific number formats, and vendor-specific field labels.
Processing Invoice Line Items and Tables
Invoices frequently contain multiple products or services. These details are usually presented in tables.
For example:
Product | Quantity | Unit Price |
|---|
Keyboard | 2 | 1,500 |
Mouse | 3 | 500 |
Monitor | 1 | 12,000 |
A layout-aware extraction provider can identify this information as an ExtractionDocumentTableElement.
You can locate table elements using the following code:
foreach (var element in document.EnumerateContent())
{
if (element is ExtractionDocumentTableElement table)
{
Console.WriteLine(
$"Rows: {table.Cells.RowCount}"
);
Console.WriteLine(
$"Columns: {table.Cells.ColumnCount}"
);
foreach (var cell in table.Cells)
{
if (cell == null)
continue;
Console.WriteLine(
$"Row: {cell.RowIndex}, " +
$"Column: {cell.ColumnIndex}"
);
}
}
}
The table provides row and column information, and individual cells can also contain nested document elements.
A production implementation should map cells according to their column headers instead of assuming that every invoice uses the same column order.
It should also account for merged cells, missing values, multiple tables, discounts, and tax columns.
Handling Scanned Invoice PDFs
Not every invoice PDF contains selectable text.
Some suppliers send scanned invoices, where the content is stored as page images. In this situation, PdfPig alone cannot recognize the invoice information.
You need an OCR-capable provider such as Azure AI Document Intelligence, Azure Content Understanding, or a vision language model.
The general workflow becomes:
Receive the scanned invoice.
Render PDF pages as images when required by the selected provider.
Submit the document to an OCR-capable extraction service.
Receive the extracted text and document structure.
Map the extracted information to InvoiceData.
Validate the results before saving them.
For example, Azure AI Document Intelligence provides invoice-oriented analysis capabilities through its dedicated invoice model. It can identify common invoice fields and line items.
DocumentExtractionClient provides a common document representation, but provider-specific invoice models may offer additional business-oriented fields. Select the appropriate integration when you need specialized invoice recognition.
Validating Invoice Information Before Saving
Extracting invoice values does not guarantee that they are correct.
Before saving an invoice, validate important business rules.
For example:
static bool ValidateInvoice(InvoiceData invoice)
{
if (string.IsNullOrWhiteSpace(invoice.InvoiceNumber))
return false;
if (invoice.InvoiceDate == default)
return false;
if (invoice.TotalAmount <= 0)
return false;
if (invoice.Subtotal < 0 || invoice.Tax < 0)
return false;
if (invoice.Items.Any(item =>
item.Quantity <= 0 ||
item.UnitPrice < 0))
{
return false;
}
return true;
}
This validation checks required invoice information and basic financial constraints.
For a real accounting application, additional checks should verify that the subtotal matches the line items, tax calculations are correct, and the total amount matches the expected financial calculation.
You should also check whether the invoice number already exists for the same supplier to avoid duplicate processing.
Do not automatically approve payments based only on OCR or AI-generated results. Important financial workflows should include appropriate approval and verification steps.
Best Practices for Production Invoice Processing
Use the Right Extraction Provider
Do not use the same extraction strategy for every invoice. Use local PDF parsing for digitally generated documents and OCR or invoice-specific services for scanned documents.
Separate Extraction and Business Logic
Keep document extraction, field mapping, validation, and database operations in separate components.
This makes the application easier to test and allows the extraction provider to change without affecting invoice business rules.
Use Background Processing
Invoice extraction can take time, particularly when using remote OCR services.
For applications that process multiple invoices, use a background worker or message queue. Store the processing status so users can check whether an invoice is pending, completed, or requires manual review.
Keep Original Documents
Store the original PDF securely along with the extracted invoice information.
This allows users to verify extracted values and investigate incorrect results.
Protect Financial Information
Invoices may contain confidential customer information, bank details, and business transactions.
Apply appropriate access controls, encryption, secure storage, and data retention policies. Avoid logging complete invoice content.
Make Processing Idempotent
The same invoice may be uploaded more than once because of network retries or user actions.
Use an appropriate business key, such as supplier identity combined with invoice number, to detect duplicates. Database constraints should enforce uniqueness where required.
Common Mistakes and Troubleshooting
Problem | Possible reason | Recommended solution |
|---|
Invoice number is missing | Different vendor label | Support multiple field patterns |
Total amount is incorrect | Currency or number formatting | Use culture-aware decimal parsing |
Line items are incomplete | Table extraction limitations | Use a layout-aware provider |
No content is extracted | PDF contains scanned images | Use OCR |
Invoice date is invalid | Different date formats | Support multiple date patterns |
Duplicate invoices are stored | No duplicate validation | Add database uniqueness checks |
OCR returns incorrect values | Poor scan quality | Improve image quality and validate results |
Extraction request fails | Provider timeout or service issue | Add retry policies and error tracking |
One common mistake is assuming that extracting a PDF successfully means the invoice has been processed successfully. Extraction and business validation are separate operations.
Another mistake is relying entirely on fixed regular expressions. They are useful for predictable layouts, but vendor invoices often contain different structures. For larger systems, combine structured extraction, vendor-specific mapping, and carefully validated AI-assisted field identification.
Advantages and Disadvantages
Advantages
Reduces manual invoice data entry.
Provides a common extraction interface for different providers.
Supports text, tables, and structured document elements.
Makes it easier to integrate OCR into existing .NET applications.
Helps automate invoice data ingestion and accounting workflows.
Supports local and cloud-based extraction strategies.
Disadvantages
Extraction accuracy depends on document quality and provider capabilities.
Different vendors may use different invoice layouts.
Regular expressions require maintenance when document formats change.
OCR and AI services can introduce additional processing costs.
Extracted financial values require business validation.
Preview APIs and provider packages may change.
Summary
Invoice PDF processing is an important automation requirement for accounting, ERP, procurement, and business management applications.
DocumentExtractionClient provides a common abstraction for extracting document content in C#. By combining it with PDF parsing or OCR-capable providers, developers can extract invoice text, identify tables, and prepare document information for further processing.
In this article, we explored how to configure DocumentExtractionClient, extract invoice content, create C# invoice models, identify important fields, process table elements, and validate financial information.
The most important consideration is that document extraction alone does not complete invoice processing. A reliable application must also handle field mapping, financial validation, duplicate detection, secure storage, and manual review when necessary.
With these components in place, .NET developers can build maintainable invoice processing solutions that reduce manual work and improve business data management.
Join the conversation! Your thoughts help the community grow.