# Invoice Processing in C#: Generate, Extract, and Automate PDF Invoices with .NET
**Invoice processing** in **C# .NET** with IronPDF covers the full document lifecycle: generating professional **PDF invoices** from HTML templates, complying with **ZUGFeRD** and **Factur-X** e-invoicing standards, extracting structured data from received invoices using text parsing and **AI-powered processing**, and building **batch automation pipelines** that integrate with accounting systems like QuickBooks, Xero, and SAP.
*as-heading:2(TL;DR: Quickstart Guide)*
This tutorial covers generating, extracting, and automating PDF invoices in C# .NET, including e-invoicing compliance, AI-powered parsing, and accounting system integration.
- **Who this is for:** .NET developers building invoicing modules, accounts payable automation, or e-invoicing compliance.
- **What you'll build:** HTML-templated invoice generation with line items and tax calculations, QR codes for payment links, ZUGFeRD/Factur-X compliant PDF/A-3 output, text extraction with regex, AI-powered invoice parsing, and batch processing with accounting system integration.
- **Where it runs:** .NET 10, .NET 8 LTS, .NET Framework 4.6.2+, and .NET Standard 2.0. No external service dependencies.
- **When to use this approach:** When you need to *generate invoice PDFs*, meet EU e-invoicing mandates, or extract data from vendor invoices for accounts payable.
- **Why it matters technically:** IronPDF renders *HTML to PDF* with pixel-perfect accuracy, supports PDF/A-3 for embedded XML, and provides text extraction APIs that pair with regex or AI to turn unstructured invoices into structured data.
Generate your first PDF invoice with just a few lines of code:
```cs
:title=Generate an Invoice PDF with IronPDF
var renderer = new IronPdf.ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice #1001</h1><p>Total: $500.00</p>");
pdf.SaveAs("invoice.pdf");
```
After you've purchased or signed up for a 30-day trial of IronPDF, add your license key at the start of your application.
```cs
IronPdf.License.LicenseKey = "KEY";
```
!!!--LIBRARY_START_TRIAL_BLOCK--!!!
!!!--LIBRARY_NUGET_INSTALL_BLOCK--!!!
*as-heading:2(Table of Contents)*
- **TL;DR: Quickstart Guide**
- [Quick Overview](#anchor-tldr-quickstart-guide)
- **Generate Professional PDF Invoices**
- [Build an Invoice HTML Template](#anchor-build-an-invoice-html-template)
- [Add Dynamic Line Items and Calculate Totals](#anchor-add-dynamic-line-items-and-calculate-totals)
- [Add Company Branding and Watermarks](#anchor-add-company-branding-and-watermarks)
- [Embed QR Codes for Payment Links](#anchor-embed-qr-codes-for-payment-links)
- **Comply with E-Invoicing Standards**
- [What is ZUGFeRD and How Does It Work?](#anchor-what-is-zugferd)
- [What is Factur-X?](#anchor-what-is-factur-x)
- [Embed XML Data in PDF/A-3 Invoices](#anchor-embed-xml-data-in-pdfa3)
- [Future-Proof Invoices for EU Mandates](#anchor-future-proof-invoices-for-eu-mandates)
- **Extract Data from PDF Invoices**
- [Extract Text from a PDF Invoice](#anchor-extract-text-from-a-pdf-invoice)
- [Extract Table Data for Line Items](#anchor-extract-table-data-for-line-items)
- [Pattern Matching for Invoice Numbers, Dates, and Totals](#anchor-pattern-matching-for-invoice-data)
- **AI-Powered Invoice Processing**
- [Integrate AI for Invoice Parsing](#anchor-integrate-ai-for-invoice-parsing)
- [Extract Structured JSON Data](#anchor-extract-structured-json-data)
- [Handle Inconsistent Invoice Formats](#anchor-handle-inconsistent-invoice-formats)
- [Build an Accounts Payable Automation Pipeline](#anchor-build-accounts-payable-automation-pipeline)
- **Integrate with Accounting Systems**
- [Integration Patterns for QuickBooks, Xero, and SAP](#anchor-integration-patterns-quickbooks-xero-sap)
- [Batch Process Hundreds of Invoices](#anchor-batch-process-hundreds-of-invoices)
!!!--LIBRARY_NUGET_INSTALL_BLOCK--!!!
<a id="anchor-invoice-lifecycle"></a>
## What is the Invoice Lifecycle and Why Does PDF remain the Standard?
Before diving into code, it helps to understand the full journey an invoice takes through a modern business system. The invoice lifecycle consists of five distinct phases: generation, distribution, receipt, data extraction, and accounting integration.
The invoice process starts with generation. A business creates an invoice that includes line items, pricing, tax calculations, payment terms, and branding. The invoice needs to look professional and meet all legal requirements. Next comes distribution, where the invoice is sent to the customer by email, through a customer portal, or by traditional mail. When the customer receives it, the accounts payable team captures the document and gets it ready for processing. Data extraction pulls key information from the invoice such as vendor details, line items, totals, and due dates, so it can be checked and matched against purchase orders. Finally, accounting integration moves this data into financial systems like QuickBooks, Xero, or SAP for payment and record keeping.
Why is PDF still the most widely used format after so many years? It comes down to a unique mix of advantages. PDFs keep your invoice formatting consistent no matter what device or operating system you use. Whether someone opens your invoice on Windows, Mac, or their phone, it looks exactly as you designed it. PDFs are also hard to change by mistake, so they protect the integrity of your documents better than formats like Word or Excel. You can add digital signatures for authenticity and use encryption for security. Most importantly, PDFs have become a universal standard that every business system recognizes and supports.
Of course, there's a challenge. PDFs are made to be easy for people to read, not for computers to process. Instead of storing information in structured data, a PDF saves text, lines, shapes, and images based on where they appear on the page. That's why tools like IronPDF are so helpful, they make it possible to turn human-friendly documents into data that software can work with.
---
## How to Generate Professional PDF Invoices in C#
Generating invoices programmatically requires transforming structured data, such as customer information, line items, and calculations, into a polished PDF document. IronPDF makes this remarkably straightforward by leveraging HTML and CSS, technologies that most developers already know well.
In this tutorial, we'll go through likely scenarios you'll encounter in the real world. You can also download the project shown below [here](/static-assets/pdf/tutorials/csharp-invoice-processing/InvoiceProcessingTutorial.zip).
<a id="anchor-build-an-invoice-html-template"></a>
### How to Build an Invoice HTML Template
The foundation of invoice generation with IronPDF is HTML. Rather than wrestling with low-level PDF drawing commands, you design your invoice using standard HTML and CSS, then let IronPDF's Chrome-based rendering engine convert it to a pixel-perfect PDF.
Here's a basic invoice template that demonstrates the approach:
```cs
using IronPdf;
// Define the HTML template for a basic invoice
// Uses inline CSS for styling headers, tables, and totals
string invoiceHtml = @"
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.header { text-align: right; margin-bottom: 40px; }
.company-name { font-size: 24px; font-weight: bold; color: #333; }
.invoice-title { font-size: 32px; margin: 20px 0; }
.bill-to { margin: 20px 0; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th { background-color: #2A95D5; color: white; padding: 10px; text-align: left; }
td { padding: 10px; border-bottom: 1px solid #ddd; }
.total { text-align: right; font-size: 20px; font-weight: bold; margin-top: 20px; }
</style>
</head>
<body>
<div class='header'>
<div class='company-name'>Your Company Name</div>
<div>123 Business Street</div>
<div>City, State 12345</div>
</div>
<div class='invoice-title'>INVOICE</div>
<div class='bill-to'>
<strong>Bill To:</strong><br>
Customer Name<br>
456 Customer Avenue<br>
City, State 67890
</div>
<table>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td>Web Development Services</td>
<td>10 hours</td>
<td>$100.00</td>
<td>$1,000.00</td>
</tr>
<tr>
<td>Consulting</td>
<td>5 hours</td>
<td>$150.00</td>
<td>$750.00</td>
</tr>
</table>
<div class='total'>Total: $1,750.00</div>
</body>
</html>";
// Initialize the Chrome-based PDF renderer
var renderer = new ChromePdfRenderer();
// Convert the HTML string to a PDF document
var pdf = renderer.RenderHtmlAsPdf(invoiceHtml);
// Save the generated PDF to disk
pdf.SaveAs("basic-invoice.pdf");
```
#### Sample Output
<iframe loading="lazy" src="/static-assets/pdf/tutorials/csharp-invoice-processing/basic-invoice.pdf"width="100%" height="400px">
</iframe>
This approach offers tremendous flexibility. Any CSS that works in Chrome will work in your PDF, including modern features like flexbox, grid layouts, and custom fonts. You can even use external stylesheets and images by referencing URLs or local file paths.
<a id="anchor-add-dynamic-line-items-and-calculate-totals"></a>
### How to Add Dynamic Line Items and Calculate Totals
Real invoices rarely have static content. You need to populate line items from a database, calculate subtotals, apply tax rates, and format currency values. The following example demonstrates a production-ready pattern for dynamic invoice generation:
```cs
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
// Represents a single line item on an invoice
public class InvoiceLineItem
{
public string Description { get; set; }
public decimal Quantity { get; set; }
public decimal UnitPrice { get; set; }
// Auto-calculates line total from quantity and unit price
public decimal Total => Quantity * UnitPrice;
}
// Represents a complete invoice with customer details and line items
public class Invoice
{
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public List<InvoiceLineItem> LineItems { get; set; }
// Computed properties for invoice totals
public decimal Subtotal => LineItems.Sum(item => item.Total);
public decimal TaxRate { get; set; } = 0.08m; // Default 8% tax rate
public decimal Tax => Subtotal * TaxRate;
public decimal Total => Subtotal + Tax;
}
// Generates PDF invoices from Invoice objects using HTML templates
public class InvoiceGenerator
{
public PdfDocument GenerateInvoice(Invoice invoice)
{
// Build HTML table rows dynamically from line items
string lineItemsHtml = string.Join("", invoice.LineItems.Select(item => $@"
<tr>
<td>{item.Description}</td>
<td>{item.Quantity}</td>
<td>${item.UnitPrice:F2}</td>
<td>${item.Total:F2}</td>
</tr>
"));
// Build the complete HTML invoice using string interpolation
// All invoice data is injected into the template dynamically
string invoiceHtml = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
.header {{ text-align: right; margin-bottom: 40px; }}
.company-name {{ font-size: 24px; font-weight: bold; color: #333; }}
.invoice-details {{ margin: 20px 0; }}
table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
th {{ background-color: #2A95D5; color: white; padding: 10px; text-align: left; }}
td {{ padding: 10px; border-bottom: 1px solid #ddd; }}
.totals {{ text-align: right; margin-top: 20px; }}
.totals div {{ margin: 5px 0; }}
.grand-total {{ font-size: 20px; font-weight: bold; color: #2A95D5; }}
</style>
</head>
<body>
<div class='header'>
<div class='company-name'>Your Company Name</div>
</div>
<h1>INVOICE</h1>
<div class='invoice-details'>
<strong>Invoice Number:</strong> {invoice.InvoiceNumber}<br>
<strong>Date:</strong> {invoice.InvoiceDate:MMM dd, yyyy}<br>
<strong>Bill To:</strong> {invoice.CustomerName}<br>
{invoice.CustomerAddress}
</div>
<table>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
{lineItemsHtml}
</table>
<div class='totals'>
<div>Subtotal: ${invoice.Subtotal:F2}</div>
<div>Tax ({invoice.TaxRate:P0}): ${invoice.Tax:F2}</div>
<div class='grand-total'>Total: ${invoice.Total:F2}</div>
</div>
</body>
</html>";
// Render HTML to PDF and return the document
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(invoiceHtml);
}
}
```
#### Sample Output
<iframe loading="lazy" src="/static-assets/pdf/tutorials/csharp-invoice-processing/invoice-INV-2026-001.pdf"width="100%" height="400px">
</iframe>
The `Invoice` class encapsulates all invoice data with calculated properties for subtotal, tax, and total. The generator transforms this data into HTML using string interpolation, then renders it to PDF. This separation of concerns makes the code maintainable and testable.
<a id="anchor-add-company-branding-and-watermarks"></a>
### How to Add Company Branding and Watermarks to Invoices
Professional invoices need branding elements like logos and, in some cases, watermarks to indicate payment status. IronPDF supports both embedded images in HTML and programmatic watermarking after rendering.
```cs
using IronPdf;
var renderer = new ChromePdfRenderer();
// Invoice HTML template with company logo embedded via URL
// Logo can also be Base64-encoded or a local file path
string htmlWithLogo = @"
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.logo { width: 200px; margin-bottom: 20px; }
</style>
</head>
<body>
<div style='text-align: center;'>
<img src='https://yourcompany.com/logo.png' alt='Company Logo' class='logo' />
</div>
<h1>INVOICE</h1>
<p><strong>Invoice Number:</strong> INV-2024-001</p>
<p><strong>Total:</strong> $1,250.00</p>
</body>
</html>";
// Render the HTML to PDF
var pdf = renderer.RenderHtmlAsPdf(htmlWithLogo);
// Apply a diagonal "UNPAID" watermark to mark invoice status
// 30% opacity keeps the content readable while the watermark is visible
pdf.ApplyWatermark("<h1 style='color: red;'>UNPAID</h1>",
opacity: 30,
rotation: 45,
verticalAlignment: IronPdf.Editing.VerticalAlignment.Middle);
pdf.SaveAs("invoice-with-watermark.pdf");
```
#### Sample Output
<iframe loading="lazy" src="/static-assets/pdf/tutorials/csharp-invoice-processing/invoice-with-watermark.pdf"width="100%" height="400px">
</iframe>
The `ApplyWatermark` method accepts HTML content, giving you complete control over the watermark's appearance. You can adjust opacity, rotation, and positioning to achieve exactly the look you need. This is particularly useful for marking invoices as "PAID," "DRAFT," or "CANCELLED" without regenerating the entire document.
<a id="anchor-embed-qr-codes-for-payment-links"></a>
### How to Embed QR Codes for Payment Links
Modern invoices often include QR codes that customers can scan to make payments quickly. While IronPDF focuses on PDF generation, it works with IronQR for barcode creation:
```cs
using IronPdf;
using IronQr;
using IronSoftware.Drawing;
string invoiceNumber = "INV-2026-002";
decimal amount = 1500.00m;
// Create a payment URL with invoice details as query parameters
string paymentUrl = $"https://yourcompany.com/pay?invoice={invoiceNumber}&amount={amount}";
// Generate QR code from the payment URL using IronQR
QrCode qrCode = QrWriter.Write(paymentUrl);
AnyBitmap qrImage = qrCode.Save();
qrImage.SaveAs("payment-qr.png", AnyBitmap.ImageFormat.Png);
// Build invoice HTML with the QR code image embedded
// Customers can scan the QR to pay directly from their phone
string invoiceHtml = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
.payment-section {{ margin-top: 40px; text-align: center;
border-top: 2px solid #eee; padding-top: 20px; }}
.qr-code {{ width: 150px; height: 150px; }}
</style>
</head>
<body>
<h1>INVOICE {invoiceNumber}</h1>
<p><strong>Amount Due:</strong> ${amount:F2}</p>
<div class='payment-section'>
<p><strong>Scan to Pay Instantly:</strong></p>
<img src='payment-qr.png' alt='Payment QR Code' class='qr-code' />
<p style='font-size: 12px; color: #666;'>
Or visit: {paymentUrl}
</p>
</div>
</body>
</html>";
// Convert HTML to PDF and save
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(invoiceHtml);
pdf.SaveAs($"invoice-{invoiceNumber}.pdf");
```
#### Sample Output
<iframe loading="lazy" src="/static-assets/pdf/tutorials/csharp-invoice-processing/invoice-INV-2026-002.pdf"width="100%" height="400px">
</iframe>
The QR code links directly to a payment page, reducing friction for customers and accelerating your cash flow. This pattern works with any payment provider that supports URL-based payment initiation.
---
## How to Comply with ZUGFeRD and Factur-X E-Invoicing Standards in C#
Electronic invoicing is rapidly becoming mandatory across Europe. Germany led the way with ZUGFeRD, and France followed with Factur-X. These standards embed machine-readable XML data within PDF invoices, enabling automated processing while maintaining human-readable documents. Understanding and implementing these standards is increasingly essential for businesses operating in European markets.
<a id="anchor-what-is-zugferd"></a>
### What is ZUGFeRD and How Does It Work?
ZUGFeRD (Zentraler User Guide des Forums elektronische Rechnung Deutschland) is a German e-invoicing standard that embeds invoice data as an XML file attachment within a PDF/A-3 compliant document. The embedded XML enables automated data extraction without OCR or parsing.
The standard defines three conformance levels, each offering progressively more structured data:
- **Basic:** Contains core invoice data suitable for simple automated processing
- **Comfort:** Adds detailed information enabling fully automated invoice handling
- **Extended:** Includes comprehensive data for complex business scenarios across industries
The XML follows the UN/CEFACT Cross-Industry Invoice (CII) schema, which has become the basis for European e-invoicing standardization.
<a id="anchor-what-is-factur-x"></a>
### What is Factur-X and How Does It Differ from ZUGFeRD?
Factur-X is the French implementation of the same underlying standard. ZUGFeRD 2.0 and Factur-X are technically identical. They share the same XML schema and conformance profiles based on the European Norm EN 16931. The difference is purely regional naming: an invoice created to ZUGFeRD specifications will be valid under Factur-X, and vice versa.
<a id="anchor-embed-xml-data-in-pdfa3"></a>
### How to Embed XML Data in PDF/A-3 Invoices
IronPDF provides the attachment capabilities needed to create compliant e-invoices. The process involves generating your invoice PDF, creating the XML data according to the CII schema, and embedding the XML as an attachment with the correct naming conventions:
```cs
using System;
using System.Xml.Linq;
// Generates ZUGFeRD-compliant invoices by embedding structured XML data
// ZUGFeRD allows automated processing while keeping a human-readable PDF
public class ZUGFeRDInvoiceGenerator
{
public void GenerateZUGFeRDInvoice(Invoice invoice)
{
// First, create the visual PDF that humans will read
var renderer = new ChromePdfRenderer();
string invoiceHtml = BuildInvoiceHtml(invoice);
var pdf = renderer.RenderHtmlAsPdf(invoiceHtml);
// Define the UN/CEFACT namespaces required by the ZUGFeRD standard
// These are mandatory for compliance with European e-invoicing regulations
XNamespace rsm = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100";
XNamespace ram = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100";
XNamespace udt = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100";
// Build the ZUGFeRD XML structure following the Cross-Industry Invoice schema
var zugferdXml = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement(rsm + "CrossIndustryInvoice",
new XAttribute(XNamespace.Xmlns + "rsm", rsm.NamespaceName),
new XAttribute(XNamespace.Xmlns + "ram", ram.NamespaceName),
new XAttribute(XNamespace.Xmlns + "udt", udt.NamespaceName),
// Document context identifies which e-invoicing guideline is being followed
new XElement(rsm + "ExchangedDocumentContext",
new XElement(ram + "GuidelineSpecifiedDocumentContextParameter",
new XElement(ram + "ID", "urn:cen.eu:en16931:2017")
)
),
// Core document identification: invoice number, type, and date
new XElement(rsm + "ExchangedDocument",
new XElement(ram + "ID", invoice.InvoiceNumber),
new XElement(ram + "TypeCode", "380"), // 380 = Commercial Invoice per UN/CEFACT
new XElement(ram + "IssueDateTime",
new XElement(udt + "DateTimeString",
new XAttribute("format", "102"),
invoice.InvoiceDate.ToString("yyyyMMdd")
)
)
),
// A complete implementation would include additional sections:
// - Seller information (ram:SellerTradeParty)
// - Buyer information (ram:BuyerTradeParty)
// - Line items (ram:IncludedSupplyChainTradeLineItem)
// - Payment terms (ram:SpecifiedTradePaymentTerms)
// - Tax summaries (ram:ApplicableTradeTax)
// Financial summary with all monetary totals
new XElement(rsm + "SupplyChainTradeTransaction",
new XElement(ram + "ApplicableHeaderTradeSettlement",
new XElement(ram + "InvoiceCurrencyCode", "EUR"),
new XElement(ram + "SpecifiedTradeSettlementHeaderMonetarySummation",
new XElement(ram + "TaxBasisTotalAmount", invoice.Subtotal),
new XElement(ram + "TaxTotalAmount",
new XAttribute("currencyID", "EUR"),
invoice.Tax),
new XElement(ram + "GrandTotalAmount", invoice.Total),
new XElement(ram + "DuePayableAmount", invoice.Total)
)
)
)
)
);
// Save the XML to a temp file for embedding
string xmlPath = $"zugferd-{invoice.InvoiceNumber}.xml";
zugferdXml.Save(xmlPath);
// Attach the XML to the PDF - filename must follow ZUGFeRD conventions
byte[] xmlData = System.IO.File.ReadAllBytes(xmlPath);
pdf.Attachments.AddAttachment("zugferd-invoice.xml", xmlData);
// Final PDF contains both visual invoice and machine-readable XML
pdf.SaveAs($"invoice-{invoice.InvoiceNumber}-zugferd.pdf");
}
// Generates simple HTML for the visual portion of the invoice
private string BuildInvoiceHtml(Invoice invoice)
{
return $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
h1 {{ color: #333; }}
.zugferd-notice {{
margin-top: 30px; padding: 10px;
background: #f0f0f0; font-size: 11px;
}}
</style>
</head>
<body>
<h1>RECHNUNG / INVOICE</h1>
<p><strong>Rechnungsnummer:</strong> {invoice.InvoiceNumber}</p>
<p><strong>Datum:</strong> {invoice.InvoiceDate:dd.MM.yyyy}</p>
<p><strong>Betrag:</strong> €{invoice.Total:F2}</p>
<div class='zugferd-notice'>
This invoice contains embedded ZUGFeRD data for automated processing.
</div>
</body>
</html>";
}
}
```
#### Sample Output
<iframe loading="lazy" src="/static-assets/pdf/tutorials/csharp-invoice-processing/invoice-DE-2026-001-zugferd.pdf"width="100%" height="400px">
</iframe>
The key aspects of compliance are using the correct XML namespaces, following the CII schema structure, and embedding the XML with an appropriate filename. The TypeCode "380" specifically identifies the document as a commercial invoice within the UN/CEFACT standard.
<a id="anchor-future-proof-invoices-for-eu-mandates"></a>
### How to Future-Proof Invoices for EU Mandates
The European Union is progressively mandating e-invoicing across member states. Italy already requires it for B2B transactions, France is phasing in requirements through 2026, and Germany has announced mandatory B2B e-invoicing starting in 2025. Building ZUGFeRD/Factur-X support now prepares your system for these regulatory requirements.
Here's a pattern for a compliance-aware invoice generator that can target different standards:
```csharp
using IronPdf;
using System;
// Enum representing supported European e-invoicing standards
public enum InvoiceStandard
{
None,
ZUGFeRD, // German standard - uses CII XML format
FacturX, // French standard - technically identical to ZUGFeRD 2.0
Peppol // Pan-European standard - uses UBL XML format
}
// Factory class that generates invoices compliant with different e-invoicing standards
// Allows switching between standards without changing core invoice generation logic
public class CompliantInvoiceGenerator
{
public PdfDocument GenerateCompliantInvoice(Invoice invoice, InvoiceStandard standard)
{
// Generate the base PDF from HTML
var renderer = new ChromePdfRenderer();
string html = BuildInvoiceHtml(invoice);
var pdf = renderer.RenderHtmlAsPdf(html);
// Attach the appropriate XML format based on target market/regulation
switch (standard)
{
case InvoiceStandard.ZUGFeRD:
case InvoiceStandard.FacturX:
// Both use Cross-Industry Invoice format, just different filenames
EmbedCIIXmlData(pdf, invoice, standard);
break;
case InvoiceStandard.Peppol:
// Peppol uses Universal Business Language format
EmbedUBLXmlData(pdf, invoice);
break;
}
return pdf;
}
// Creates and embeds CII-format XML (used by ZUGFeRD and Factur-X)
private void EmbedCIIXmlData(PdfDocument pdf, Invoice invoice, InvoiceStandard standard)
{
string xml = GenerateCIIXml(invoice);
// Filename convention differs between German and French standards
string filename = standard == InvoiceStandard.ZUGFeRD
? "zugferd-invoice.xml"
: "factur-x.xml";
System.IO.File.WriteAllText("temp-invoice.xml", xml);
byte[] xmlData = System.IO.File.ReadAllBytes("temp-invoice.xml");
pdf.Attachments.AddAttachment(filename, xmlData);
}
// Creates and embeds UBL-format XML for Peppol network compliance
private void EmbedUBLXmlData(PdfDocument pdf, Invoice invoice)
{
// UBL (Universal Business Language) is the Peppol standard format
string xml = $@"<?xml version='1.0' encoding='UTF-8'?>
<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2'>
<ID>{invoice.InvoiceNumber}</ID>
<IssueDate>{invoice.InvoiceDate:yyyy-MM-dd}</IssueDate>
<DocumentCurrencyCode>EUR</DocumentCurrencyCode>
<LegalMonetaryTotal>
<PayableAmount currencyID='EUR'>{invoice.Total}</PayableAmount>
</LegalMonetaryTotal>
</Invoice>";
System.IO.File.WriteAllText("peppol-invoice.xml", xml);
pdf.Attachments.AddFile("peppol-invoice.xml", "invoice.xml", "Peppol UBL Invoice");
}
// Generates minimal CII XML structure for demonstration
private string GenerateCIIXml(Invoice invoice)
{
return $@"<?xml version='1.0' encoding='UTF-8'?>
<rsm:CrossIndustryInvoice
xmlns:rsm='urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'
xmlns:ram='urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'>
<rsm:ExchangedDocument>
<ram:ID>{invoice.InvoiceNumber}</ram:ID>
<ram:TypeCode>380</ram:TypeCode>
</rsm:ExchangedDocument>
</rsm:CrossIndustryInvoice>";
}
private string BuildInvoiceHtml(Invoice invoice)
{
return $"<html><body><h1>Invoice {invoice.InvoiceNumber}</h1></body></html>";
}
}
```
This architecture allows you to add new standards as they emerge without restructuring your core invoice generation logic. The enum-based approach makes it easy to let users or configuration determine which compliance mode to use.
---
## How to Extract Data from PDF Invoices in C#
Generating invoices is only half the equation. Most businesses also receive invoices from vendors and need to extract data for processing. IronPDF provides powerful text extraction capabilities that form the foundation of invoice data capture.
<a id="anchor-extract-text-from-a-pdf-invoice"></a>
### How to Extract Text from a PDF Invoice
The most fundamental extraction operation retrieves all text content from a PDF. IronPDF's `ExtractAllText` method handles the complexity of PDF text encoding and positioning:
```csharp
using IronPdf;
using System;
// Extracts raw text content from PDF invoices for further processing
public class InvoiceTextExtractor
{
// Extracts all text from a PDF in one operation
// Best for single-page invoices or when you need the complete content
public string ExtractInvoiceText(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
// IronPDF handles the complexity of PDF text encoding and positioning
string allText = pdf.ExtractAllText();
Console.WriteLine("Full invoice text:");
Console.WriteLine(allText);
return allText;
}
// Extracts text page by page - useful for multi-page invoices
// Allows you to process header info separately from line items
public void ExtractTextByPage(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
// Iterate through each page (0-indexed)
for (int i = 0; i < pdf.PageCount; i++)
{
string pageText = pdf.ExtractTextFromPage(i);
Console.WriteLine($"\n--- Page {i + 1} ---");
Console.WriteLine(pageText);
}
}
}
```
Page-by-page extraction is particularly useful for multi-page invoices where you need to locate specific sections, such as finding line items that span multiple pages whereas header information appears only on the first page.
<a id="anchor-extract-table-data-for-line-items"></a>
### How to Extract Table Data for Line Items
Invoice line items typically appear in tabular format. PDFs lack a native table structure, but you can extract text and parse it to reconstruct table data:
```csharp
using IronPdf;
using System;
using System.Collections.Generic;
// Data model for a single invoice line item
public class InvoiceLineItem
{
public string Description { get; set; }
public decimal Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total { get; set; }
}
// Extracts tabular line item data from PDF invoices
// Note: PDFs don't have native table structure, so this uses text parsing
public class InvoiceTableExtractor
{
public List<InvoiceLineItem> ExtractLineItems(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
var lineItems = new List<InvoiceLineItem>();
string[] lines = text.Split('\n');
foreach (string line in lines)
{
// Currency symbols indicate potential line items with amounts
if (line.Contains("$") || line.Contains("€"))
{
Console.WriteLine($"Potential line item: {line.Trim()}");
// Split on whitespace to separate columns
// Actual parsing logic depends on your invoice format
string[] parts = line.Split(new[] { '\t', ' ' },
StringSplitOptions.RemoveEmptyEntries);
// Try to find numeric values that could be amounts
foreach (string part in parts)
{
string cleaned = part.Replace("$", "").Replace("€", "").Replace(",", "");
if (decimal.TryParse(cleaned, out decimal amount))
{
Console.WriteLine($" Found amount: {amount:C}");
}
}
}
}
return lineItems;
}
}
```
The parsing logic will vary based on your invoice formats. For invoices with consistent layouts from known vendors, you can build format-specific parsers. For varied formats, consider the AI-powered extraction covered later in this article.
<a id="anchor-pattern-matching-for-invoice-data"></a>
### How to Use Pattern Matching for Invoice Numbers, Dates, and Totals
Regular expressions are invaluable for extracting specific data points from invoice text. Key fields like invoice numbers, dates, and totals often follow recognizable patterns:
```csharp
using IronPdf;
using System;
using System.Text.RegularExpressions;
// Data model for extracted invoice information
public class InvoiceData
{
public string InvoiceNumber { get; set; }
public string InvoiceDate { get; set; }
public decimal TotalAmount { get; set; }
public string VendorName { get; set; }
}
// Extracts key invoice fields using regex pattern matching
// Multiple patterns handle variations across different vendors
public class InvoiceParser
{
public InvoiceData ParseInvoice(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
var invoiceData = new InvoiceData();
// Try multiple patterns to find invoice number
// Handles: "Invoice #123", "INV-123", "Invoice Number: 123", German "Rechnungsnummer"
string[] invoiceNumberPatterns = new[]
{
@"Invoice\s*#?\s*:?\s*([A-Z0-9-]+)",
@"INV[-\s]?(\d+)",
@"Invoice\s+Number\s*:?\s*([A-Z0-9-]+)",
@"Rechnungsnummer\s*:?\s*([A-Z0-9-]+)"
};
foreach (string pattern in invoiceNumberPatterns)
{
var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
invoiceData.InvoiceNumber = match.Groups[1].Value;
Console.WriteLine($"Found Invoice Number: {invoiceData.InvoiceNumber}");
break;
}
}
// Date patterns for US, European, and written formats
string[] datePatterns = new[]
{
@"Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
@"Invoice\s+Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
@"(\d{1,2}\.\d{1,2}\.\d{4})", // European: DD.MM.YYYY
@"(\w+\s+\d{1,2},?\s+\d{4})" // Written: January 15, 2024
};
foreach (string pattern in datePatterns)
{
var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
invoiceData.InvoiceDate = match.Groups[1].Value;
Console.WriteLine($"Found Date: {invoiceData.InvoiceDate}");
break;
}
}
// Look for total amount with various labels
string[] totalPatterns = new[]
{
@"Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
@"Amount\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
@"Grand\s+Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
@"Balance\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})"
};
foreach (string pattern in totalPatterns)
{
var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
// Remove commas before parsing
string amountStr = match.Groups[1].Value.Replace(",", "");
if (decimal.TryParse(amountStr, out decimal amount))
{
invoiceData.TotalAmount = amount;
Console.WriteLine($"Found Total: ${invoiceData.TotalAmount:F2}");
break;
}
}
}
return invoiceData;
}
}
```
This pattern-based approach works well for invoices with predictable formats. The multiple pattern variations handle common formatting differences across vendors, such as "Invoice #" and "Invoice Number:"
### What about Scanned or Image-Based Invoices?
The text extraction methods shown above work with PDFs that contain embedded text. However, scanned documents and image-based PDFs don't have extractable text. They're essentially pictures of invoices.
[[i:(For processing scanned invoices, you'll need OCR (Optical Character Recognition) capabilities. IronOCR, part of the Iron Suite, integrates with IronPDF for these scenarios. Visit [https://ironsoftware.com/csharp/ocr/](https://ironsoftware.com/csharp/ocr/) to learn more about extracting text from scanned documents and images.)]]
---
## How to Use AI to Process Invoices in .NET
Traditional pattern matching works well for standardized invoices, but real-world accounts payable departments receive documents in countless formats. This is where AI-powered extraction shines. Large language models can understand invoice semantics and extract structured data even from unfamiliar layouts.
<a id="anchor-integrate-ai-for-invoice-parsing"></a>
### How to Integrate AI for Invoice Parsing
The pattern for AI-powered invoice processing combines IronPDF's text extraction with LLM API calls. Here's a generic implementation that works with any OpenAI-compatible API:
```csharp
using IronPdf;
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
// Data model for extracted invoice information
public class InvoiceData
{
public string InvoiceNumber { get; set; }
public string InvoiceDate { get; set; }
public string VendorName { get; set; }
public decimal TotalAmount { get; set; }
}
// Leverages AI/LLM APIs to extract structured data from any invoice format
// Works with OpenAI or any compatible API endpoint
public class AIInvoiceParser
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _apiUrl;
public AIInvoiceParser(string apiKey, string apiUrl = "https://api.openai.com/v1/chat/completions")
{
_apiKey = apiKey;
_apiUrl = apiUrl;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
}
public async Task<InvoiceData> ParseInvoiceWithAI(string pdfPath)
{
// First extract raw text from the PDF using IronPDF
var pdf = PdfDocument.FromFile(pdfPath);
string invoiceText = pdf.ExtractAllText();
// Construct a prompt that instructs the AI to return structured JSON
// Being explicit about the format reduces parsing errors
string prompt = $@"Extract the following information from this invoice text.
Return ONLY valid JSON with no additional text or markdown formatting.
Required fields:
- InvoiceNumber: The invoice or document number
- InvoiceDate: The invoice date in YYYY-MM-DD format
- VendorName: The company or person who sent the invoice
- TotalAmount: The total amount due as a number (no currency symbols)
Invoice text:
{invoiceText}
JSON response:";
// Build the API request with a system prompt for context
var requestBody = new
{
model = "gpt-4",
messages = new[]
{
new {
role = "system",
content = "You are an invoice data extraction assistant. Extract structured data from invoices and return valid JSON only."
},
new { role = "user", content = prompt }
},
temperature = 0.1 // Low temperature ensures consistent, deterministic results
};
var json = JsonSerializer.Serialize(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(_apiUrl, content);
var responseJson = await response.Content.ReadAsStringAsync();
// Navigate the API response structure to get the extracted content
using var doc = JsonDocument.Parse(responseJson);
var messageContent = doc.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString();
Console.WriteLine("AI Extracted Data:");
Console.WriteLine(messageContent);
// Deserialize the AI's JSON response into our data class
var invoiceData = JsonSerializer.Deserialize<InvoiceData>(messageContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
return invoiceData;
}
}
```
The low temperature setting (0.1) encourages deterministic outputs, which is important for data extraction tasks where you want consistent results for the same input.
<a id="anchor-extract-structured-json-data"></a>
### How to Extract Structured JSON Data from Invoices
For more complex invoices with line items, vendor details, and customer information, you can request a richer JSON structure:
```csharp
using IronPdf;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
// Comprehensive invoice data model with all details
public class DetailedInvoiceData
{
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public DateTime DueDate { get; set; }
public VendorInfo Vendor { get; set; }
public CustomerInfo Customer { get; set; }
public List<LineItem> LineItems { get; set; }
public decimal Subtotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
}
public class VendorInfo
{
public string Name { get; set; }
public string Address { get; set; }
public string TaxId { get; set; }
}
public class CustomerInfo
{
public string Name { get; set; }
public string Address { get; set; }
}
public class LineItem
{
public string Description { get; set; }
public decimal Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total { get; set; }
}
// Extracts comprehensive invoice data including line items and party details
public class StructuredInvoiceExtractor
{
private readonly AIInvoiceParser _aiParser;
public StructuredInvoiceExtractor(string apiKey)
{
_aiParser = new AIInvoiceParser(apiKey);
}
public async Task<DetailedInvoiceData> ExtractDetailedData(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
// Define the exact JSON structure we want the AI to return
// This schema guides the AI to extract all relevant fields
string jsonSchema = @"{
""InvoiceNumber"": ""string"",
""InvoiceDate"": ""YYYY-MM-DD"",
""DueDate"": ""YYYY-MM-DD"",
""Vendor"": {
""Name"": ""string"",
""Address"": ""string"",
""TaxId"": ""string or null""
},
""Customer"": {
""Name"": ""string"",
""Address"": ""string""
},
""LineItems"": [
{
""Description"": ""string"",
""Quantity"": 0.0,
""UnitPrice"": 0.00,
""Total"": 0.00
}
],
""Subtotal"": 0.00,
""Tax"": 0.00,
""Total"": 0.00
}";
// Prompt includes both the schema and the extracted text
string prompt = $@"Extract all invoice data and return it in this exact JSON structure:
{jsonSchema}
Invoice text:
{text}
Return only valid JSON, no markdown formatting or additional text.";
// Call AI API and parse response (implementation as shown above)
// Return deserialized DetailedInvoiceData
return new DetailedInvoiceData(); // Placeholder
}
}
```
<a id="anchor-handle-inconsistent-invoice-formats"></a>
### How to Handle Inconsistent Invoice Formats
The real power of AI extraction emerges when processing invoices from multiple vendors, each with unique formats. A smart processor can attempt pattern-based extraction first (faster and free) and fall back to AI only when needed:
```csharp
using IronPdf;
using System.Threading.Tasks;
// Hybrid processor that optimizes for cost and capability
// Tries fast regex patterns first, uses AI only when patterns fail
public class SmartInvoiceProcessor
{
private readonly AIInvoiceParser _aiParser;
public SmartInvoiceProcessor(string aiApiKey)
{
_aiParser = new AIInvoiceParser(aiApiKey);
}
public async Task<InvoiceData> ProcessAnyInvoice(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
// First attempt: regex patterns (fast and free)
var patternParser = new InvoiceParser();
var standardResult = patternParser.ParseInvoiceFromText(text);
// If pattern matching found all required fields, use that result
if (IsComplete(standardResult))
{
Console.WriteLine("Pattern extraction successful");
return standardResult;
}
// Fallback: use AI for complex or unusual invoice formats
// This costs money but handles any layout
Console.WriteLine("Using AI extraction for complex invoice format");
var aiResult = await _aiParser.ParseInvoiceWithAI(pdfPath);
return aiResult;
}
// Validates that we have the minimum required fields
private bool IsComplete(InvoiceData data)
{
return !string.IsNullOrEmpty(data.InvoiceNumber) &&
!string.IsNullOrEmpty(data.InvoiceDate) &&
data.TotalAmount > 0;
}
}
```
<a id="anchor-build-accounts-payable-automation-pipeline"></a>
### How to Build an Accounts Payable Automation Pipeline
Bringing all these pieces together, here's a complete automation pipeline that processes incoming invoices, extracts data, validates it, and prepares it for your accounting system:
```csharp
using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
// Tracks the outcome of processing each invoice
public class ProcessingResult
{
public string FileName { get; set; }
public bool Success { get; set; }
public string InvoiceNumber { get; set; }
public string ErrorMessage { get; set; }
}
// Complete automation pipeline for accounts payable
// Watches a folder, extracts data, validates, and routes to accounting system
public class InvoiceAutomationPipeline
{
private readonly SmartInvoiceProcessor _processor;
private readonly string _inputFolder;
private readonly string _processedFolder;
private readonly string _errorFolder;
public InvoiceAutomationPipeline(string apiKey, string inputFolder)
{
_processor = new SmartInvoiceProcessor(apiKey);
_inputFolder = inputFolder;
_processedFolder = Path.Combine(inputFolder, "processed");
_errorFolder = Path.Combine(inputFolder, "errors");
// Create output directories if they don't exist
Directory.CreateDirectory(_processedFolder);
Directory.CreateDirectory(_errorFolder);
}
// Main entry point - processes all PDFs in the input folder
public async Task<List<ProcessingResult>> ProcessInvoiceBatch()
{
string[] invoiceFiles = Directory.GetFiles(_inputFolder, "*.pdf");
Console.WriteLine($"Found {invoiceFiles.Length} invoices to process");
var results = new List<ProcessingResult>();
foreach (string invoicePath in invoiceFiles)
{
string fileName = Path.GetFileName(invoicePath);
try
{
Console.WriteLine($"Processing: {fileName}");
// Extract data using smart processor (patterns first, then AI)
var invoiceData = await _processor.ProcessAnyInvoice(invoicePath);
// Ensure we have minimum required fields before proceeding
if (ValidateInvoiceData(invoiceData))
{
// Send to accounting system (QuickBooks, Xero, etc.)
await SaveToAccountingSystem(invoiceData);
// Archive successful invoices
string destPath = Path.Combine(_processedFolder, fileName);
File.Move(invoicePath, destPath, overwrite: true);
results.Add(new ProcessingResult
{
FileName = fileName,
Success = true,
InvoiceNumber = invoiceData.InvoiceNumber
});
Console.WriteLine($"✓ Processed: {invoiceData.InvoiceNumber}");
}
else
{
throw new Exception("Validation failed - missing required fields");
}
}
catch (Exception ex)
{
Console.WriteLine($"✗ Failed: {fileName} - {ex.Message}");
// Quarantine failed invoices for manual review
string destPath = Path.Combine(_errorFolder, fileName);
File.Move(invoicePath, destPath, overwrite: true);
results.Add(new ProcessingResult
{
FileName = fileName,
Success = false,
ErrorMessage = ex.Message
});
}
}
GenerateReport(results);
return results;
}
// Checks for minimum required fields
private bool ValidateInvoiceData(InvoiceData data)
{
return !string.IsNullOrEmpty(data.InvoiceNumber) &&
!string.IsNullOrEmpty(data.VendorName) &&
data.TotalAmount > 0;
}
// Placeholder for accounting system integration
private async Task SaveToAccountingSystem(InvoiceData data)
{
// Integrate with your accounting system here
// Examples: QuickBooks API, Xero API, SAP, or database storage
Console.WriteLine($" Saved invoice {data.InvoiceNumber} to accounting system");
await Task.CompletedTask;
}
// Outputs a summary of the batch processing results
private void GenerateReport(List<ProcessingResult> results)
{
int successful = results.Count(r => r.Success);
int failed = results.Count(r => !r.Success);
Console.WriteLine($"\n========== Processing Complete ==========");
Console.WriteLine($"Total Processed: {results.Count}");
Console.WriteLine($"Successful: {successful}");
Console.WriteLine($"Failed: {failed}");
if (failed > 0)
{
Console.WriteLine("\nFailed invoices requiring review:");
foreach (var failure in results.Where(r => !r.Success))
{
Console.WriteLine($" • {failure.FileName}: {failure.ErrorMessage}");
}
}
}
}
```
This pipeline implements a complete workflow: it scans a folder for incoming PDFs, processes each one, validates the extracted data, routes successful extractions to your accounting system, and quarantines failures for manual review. The summary report gives visibility into processing outcomes.
---
## How to Integrate C# Invoice Processing with Accounting Systems
The extracted invoice data ultimately needs to flow into accounting systems for payment and record-keeping. The specifics vary by platform, but the integration patterns are consistent.
<a id="anchor-integration-patterns-quickbooks-xero-sap"></a>
### What are Common Integration Patterns for QuickBooks, Xero, and SAP?
Most accounting platforms offer REST APIs for creating bills or invoices programmatically. Here's a generalized pattern that you can adapt for your specific platform:
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
// Generic integration layer for pushing invoice data to accounting systems
// Adapt the API calls based on your specific platform
public class AccountingSystemIntegration
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _baseUrl;
public AccountingSystemIntegration(string apiKey, string baseUrl)
{
_apiKey = apiKey;
_baseUrl = baseUrl;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
}
// Creates a Bill in QuickBooks (vendor invoices are called "Bills")
public async Task SendToQuickBooks(InvoiceData invoice)
{
// QuickBooks Bill structure - see their API docs for full schema
var bill = new
{
VendorRef = new { name = invoice.VendorName },
TxnDate = invoice.InvoiceDate,
DocNumber = invoice.InvoiceNumber,
TotalAmt = invoice.TotalAmount,
Line = new[]
{
new
{
Amount = invoice.TotalAmount,
DetailType = "AccountBasedExpenseLineDetail",
AccountBasedExpenseLineDetail = new
{
AccountRef = new { name = "Accounts Payable" }
}
}
}
};
await PostToApi("/v3/company/{companyId}/bill", bill);
}
// Creates an accounts payable invoice in Xero
public async Task SendToXero(InvoiceData invoice)
{
// ACCPAY type indicates this is a bill to pay (not a sales invoice)
var bill = new
{
Type = "ACCPAY",
Contact = new { Name = invoice.VendorName },
Date = invoice.InvoiceDate,
InvoiceNumber = invoice.InvoiceNumber,
Total = invoice.TotalAmount
};
await PostToApi("/api.xro/2.0/Invoices", bill);
}
// Generic POST helper with error handling
private async Task PostToApi(string endpoint, object payload)
{
string json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{_baseUrl}{endpoint}", content);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
throw new Exception($"API Error: {response.StatusCode} - {error}");
}
Console.WriteLine($"Successfully posted to {endpoint}");
}
}
```
Each platform has its own authentication mechanism (OAuth for QuickBooks and Xero, various methods for SAP), required fields, and API conventions. Consult your target platform's documentation for specifics, but the pattern of transforming extracted invoice data into API payloads remains consistent.
<a id="anchor-batch-process-hundreds-of-invoices"></a>
### How to Batch Process Hundreds of Invoices
High-volume invoice processing requires careful attention to concurrency and resource management. Here's a pattern using parallel processing with controlled concurrency:
```csharp
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
// Tracks the result of processing a single invoice in a batch
public class BatchResult
{
public string FilePath { get; set; }
public bool Success { get; set; }
public string InvoiceNumber { get; set; }
public string Error { get; set; }
}
// High-volume invoice processor with controlled parallelism
// Prevents overwhelming APIs while maximizing throughput
public class BatchInvoiceProcessor
{
private readonly SmartInvoiceProcessor _invoiceProcessor;
private readonly AccountingSystemIntegration _accountingIntegration;
private readonly int _maxConcurrency;
public BatchInvoiceProcessor(string aiApiKey, string accountingApiKey,
string accountingUrl, int maxConcurrency = 5)
{
_invoiceProcessor = new SmartInvoiceProcessor(aiApiKey);
_accountingIntegration = new AccountingSystemIntegration(accountingApiKey, accountingUrl);
_maxConcurrency = maxConcurrency; // Adjust based on API rate limits
}
// Processes multiple invoices in parallel with controlled concurrency
public async Task<List<BatchResult>> ProcessInvoiceBatch(List<string> invoicePaths)
{
// Thread-safe collection for gathering results from parallel tasks
var results = new ConcurrentBag<BatchResult>();
// Semaphore limits how many invoices process simultaneously
var semaphore = new SemaphoreSlim(_maxConcurrency);
// Create a task for each invoice
var tasks = invoicePaths.Select(async path =>
{
// Wait for a slot to become available
await semaphore.WaitAsync();
try
{
var result = await ProcessSingleInvoice(path);
results.Add(result);
}
finally
{
// Release slot for next invoice
semaphore.Release();
}
});
// Wait for all invoices to complete
await Task.WhenAll(tasks);
// Output summary statistics
var resultList = results.ToList();
int successful = resultList.Count(r => r.Success);
int failed = resultList.Count(r => !r.Success);
Console.WriteLine($"\nBatch Processing Complete:");
Console.WriteLine($" Total: {resultList.Count}");
Console.WriteLine($" Successful: {successful}");
Console.WriteLine($" Failed: {failed}");
return resultList;
}
// Processes one invoice: extract data and send to accounting system
private async Task<BatchResult> ProcessSingleInvoice(string pdfPath)
{
try
{
Console.WriteLine($"Processing: {pdfPath}");
var invoiceData = await _invoiceProcessor.ProcessAnyInvoice(pdfPath);
await _accountingIntegration.SendToQuickBooks(invoiceData);
Console.WriteLine($"✓ Completed: {invoiceData.InvoiceNumber}");
return new BatchResult
{
FilePath = pdfPath,
Success = true,
InvoiceNumber = invoiceData.InvoiceNumber
};
}
catch (Exception ex)
{
Console.WriteLine($"✗ Failed: {pdfPath}");
return new BatchResult
{
FilePath = pdfPath,
Success = false,
Error = ex.Message
};
}
}
}
```
The `SemaphoreSlim` ensures you don't overwhelm external APIs or exhaust system resources. Adjust `_maxConcurrency` based on your API rate limits and server capacity. The `ConcurrentBag` safely collects results from parallel operations.
---
## Next Steps
Invoice automation represents a significant opportunity to reduce manual work, minimize errors, and accelerate business processes. This guide has walked you through the complete lifecycle: generating professional invoices from [HTML templates](/tutorials/html-to-pdf/), complying with [ZUGFeRD and Factur-X](/product-updates/milestones-pdf-a3-zugferd/) e-invoicing standards, [extracting data](/how-to/extract-text-and-images/) from received invoices using both pattern matching and [AI-powered processing](/tutorials/ai-powered-pdf-processing-csharp/), and building scalable automation pipelines.
[IronPDF](https://ironpdf.com/) serves as the foundation for these capabilities, providing reliable HTML-to-PDF rendering, reliable [text extraction](/how-to/csharp-parse-pdf/), and the attachment features needed for [PDF/A-3 e-invoicing compliance](/how-to/pdfa/). Its Chrome-based rendering engine ensures your invoices look exactly as designed, while its extraction methods handle the complexity of PDF text encoding automatically.
The patterns shown here are starting points. Real implementations will need adaptation for your specific invoice formats, accounting systems, and business rules. For high-volume scenarios, the [batch processing tutorial](/tutorials/batch-pdf-processing-csharp/) covers parallel execution with controlled concurrency and error recovery.
Ready to start building? [Download IronPDF](download-modal) and try it with a free trial. The library includes a free development license, so you can fully evaluate invoice generation, data extraction, and [PDF report capabilities](/how-to/csharp-pdf-reports/) before committing to a production license. If you have questions about invoice automation or accounting system integration, [reach out to our engineering support team](/troubleshooting/engineering-request-pdf/).
Invoice processing in C# .NET with IronPDF covers the full document lifecycle: generating professional PDF invoices from HTML templates, complying with ZUGFeRD and Factur-X e-invoicing standards, extracting structured data from received invoices using text parsing and AI-powered processing, and building batch automation pipelines that integrate with accounting systems like QuickBooks, Xero, and SAP.
TL;DR: Quickstart Guide
This tutorial covers generating, extracting, and automating PDF invoices in C# .NET, including e-invoicing compliance, AI-powered parsing, and accounting system integration.
Who this is for: .NET developers building invoicing modules, accounts payable automation, or e-invoicing compliance.
What you'll build: HTML-templated invoice generation with line items and tax calculations, QR codes for payment links, ZUGFeRD/Factur-X compliant PDF/A-3 output, text extraction with regex, AI-powered invoice parsing, and batch processing with accounting system integration.
Where it runs: .NET 10, .NET 8 LTS, .NET Framework 4.6.2+, and .NET Standard 2.0. No external service dependencies.
When to use this approach: When you need to generate invoice PDFs, meet EU e-invoicing mandates, or extract data from vendor invoices for accounts payable.
Why it matters technically: IronPDF renders HTML to PDF with pixel-perfect accuracy, supports PDF/A-3 for embedded XML, and provides text extraction APIs that pair with regex or AI to turn unstructured invoices into structured data.
Generate your first PDF invoice with just a few lines of code:
1Install IronPDF with NuGet Package Manager
PM > Install-Package IronPdf
Install-Package IronPdf
2Copy and run this code snippet.
var renderer = new IronPdf.ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice #1001</h1><p>Total: $500.00</p>");pdf.SaveAs("invoice.pdf");
var renderer = new IronPdf.ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice #1001</h1><p>Total: $500.00</p>");
pdf.SaveAs("invoice.pdf");
C#
3Deploy to test on your live environment
Start using IronPDF in your project today with a free trial
After you've purchased or signed up for a 30-day trial of IronPDF, add your license key at the start of your application.
Install IronPDF by running the command above in the NuGet Package Manager Console, or search for the package in the NuGet Package Manager.
What is the Invoice Lifecycle and Why Does PDF remain the Standard?
Before diving into code, it helps to understand the full journey an invoice takes through a modern business system. The invoice lifecycle consists of five distinct phases: generation, distribution, receipt, data extraction, and accounting integration.
The invoice process starts with generation. A business creates an invoice that includes line items, pricing, tax calculations, payment terms, and branding. The invoice needs to look professional and meet all legal requirements. Next comes distribution, where the invoice is sent to the customer by email, through a customer portal, or by traditional mail. When the customer receives it, the accounts payable team captures the document and gets it ready for processing. Data extraction pulls key information from the invoice such as vendor details, line items, totals, and due dates, so it can be checked and matched against purchase orders. Finally, accounting integration moves this data into financial systems like QuickBooks, Xero, or SAP for payment and record keeping.
Why is PDF still the most widely used format after so many years? It comes down to a unique mix of advantages. PDFs keep your invoice formatting consistent no matter what device or operating system you use. Whether someone opens your invoice on Windows, Mac, or their phone, it looks exactly as you designed it. PDFs are also hard to change by mistake, so they protect the integrity of your documents better than formats like Word or Excel. You can add digital signatures for authenticity and use encryption for security. Most importantly, PDFs have become a universal standard that every business system recognizes and supports.
Of course, there's a challenge. PDFs are made to be easy for people to read, not for computers to process. Instead of storing information in structured data, a PDF saves text, lines, shapes, and images based on where they appear on the page. That's why tools like IronPDF are so helpful, they make it possible to turn human-friendly documents into data that software can work with.
How to Generate Professional PDF Invoices in C#
Generating invoices programmatically requires transforming structured data, such as customer information, line items, and calculations, into a polished PDF document. IronPDF makes this remarkably straightforward by leveraging HTML and CSS, technologies that most developers already know well.
In this tutorial, we'll go through likely scenarios you'll encounter in the real world. You can also download the project shown below here.
How to Build an Invoice HTML Template
The foundation of invoice generation with IronPDF is HTML. Rather than wrestling with low-level PDF drawing commands, you design your invoice using standard HTML and CSS, then let IronPDF's Chrome-based rendering engine convert it to a pixel-perfect PDF.
Here's a basic invoice template that demonstrates the approach:
using IronPdf;// Define the HTML template for a basic invoice// Uses inline CSS for styling headers, tables, and totalsstring invoiceHtml = @"<!DOCTYPE html><html><head><style>body { font-family: Arial, sans-serif; padding: 40px; }.header { text-align: right; margin-bottom: 40px; }.company-name { font-size: 24px; font-weight: bold; color: #333; }.invoice-title { font-size: 32px; margin: 20px 0; }.bill-to { margin: 20px 0; }table { width: 100%; border-collapse: collapse; margin: 20px 0; }th { background-color: #2A95D5; color: white; padding: 10px; text-align: left; }td { padding: 10px; border-bottom: 1px solid #ddd; }.total { text-align: right; font-size: 20px; font-weight: bold; margin-top: 20px; }</style></head><body><div class='header'><div class='company-name'>Your Company Name</div><div>123 Business Street</div><div>City, State 12345</div></div><div class='invoice-title'>INVOICE</div><div class='bill-to'><strong>Bill To:</strong><br>Customer Name<br>456 Customer Avenue<br>City, State 67890</div><table><tr> <th>Description</th> <th>Quantity</th> <th>Price</th> <th>Total</th></tr><tr> <td>Web Development Services</td> <td>10 hours</td> <td>$100.00</td> <td>$1,000.00</td></tr><tr> <td>Consulting</td> <td>5 hours</td> <td>$150.00</td> <td>$750.00</td></tr></table><div class='total'>Total: $1,750.00</div></body></html>";// Initialize the Chrome-based PDF renderervar renderer = new ChromePdfRenderer();// Convert the HTML string to a PDF documentvar pdf = renderer.RenderHtmlAsPdf(invoiceHtml);// Save the generated PDF to diskpdf.SaveAs("basic-invoice.pdf");
using IronPdf;
// Define the HTML template for a basic invoice
// Uses inline CSS for styling headers, tables, and totals
string invoiceHtml = @"
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.header { text-align: right; margin-bottom: 40px; }
.company-name { font-size: 24px; font-weight: bold; color: #333; }
.invoice-title { font-size: 32px; margin: 20px 0; }
.bill-to { margin: 20px 0; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th { background-color: #2A95D5; color: white; padding: 10px; text-align: left; }
td { padding: 10px; border-bottom: 1px solid #ddd; }
.total { text-align: right; font-size: 20px; font-weight: bold; margin-top: 20px; }
</style>
</head>
<body>
<div class='header'>
<div class='company-name'>Your Company Name</div>
<div>123 Business Street</div>
<div>City, State 12345</div>
</div>
<div class='invoice-title'>INVOICE</div>
<div class='bill-to'>
<strong>Bill To:</strong><br>
Customer Name<br>
456 Customer Avenue<br>
City, State 67890
</div>
<table>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td>Web Development Services</td>
<td>10 hours</td>
<td>$100.00</td>
<td>$1,000.00</td>
</tr>
<tr>
<td>Consulting</td>
<td>5 hours</td>
<td>$150.00</td>
<td>$750.00</td>
</tr>
</table>
<div class='total'>Total: $1,750.00</div>
</body>
</html>";
// Initialize the Chrome-based PDF renderer
var renderer = new ChromePdfRenderer();
// Convert the HTML string to a PDF document
var pdf = renderer.RenderHtmlAsPdf(invoiceHtml);
// Save the generated PDF to disk
pdf.SaveAs("basic-invoice.pdf");
C#
Sample Output
This approach offers tremendous flexibility. Any CSS that works in Chrome will work in your PDF, including modern features like flexbox, grid layouts, and custom fonts. You can even use external stylesheets and images by referencing URLs or local file paths.
How to Add Dynamic Line Items and Calculate Totals
Real invoices rarely have static content. You need to populate line items from a database, calculate subtotals, apply tax rates, and format currency values. The following example demonstrates a production-ready pattern for dynamic invoice generation:
using IronPdf;using System;using System.Collections.Generic;using System.Linq;// Represents a single line item on an invoicepublic class InvoiceLineItem{ public stringDescription { get; set; } public decimalQuantity { get; set; } public decimalUnitPrice { get; set; } // Auto-calculates line total from quantity and unit price public decimalTotal => Quantity * UnitPrice;}// Represents a complete invoice with customer details and line itemspublic class Invoice{ public stringInvoiceNumber { get; set; } public DateTimeInvoiceDate { get; set; } public stringCustomerName { get; set; } public stringCustomerAddress { get; set; } public List<InvoiceLineItem> LineItems { get; set; } // Computed properties for invoice totals public decimalSubtotal => LineItems.Sum(item => item.Total); public decimalTaxRate { get; set; } = 0.08m; // Default 8% tax rate public decimalTax => Subtotal * TaxRate; public decimalTotal => Subtotal + Tax;}// Generates PDF invoices from Invoice objects using HTML templatespublic class InvoiceGenerator{ public PdfDocumentGenerateInvoice(Invoice invoice) { // Build HTML table rows dynamically from line items string lineItemsHtml = string.Join("", invoice.LineItems.Select(item => $@" <tr> <td>{item.Description}</td> <td>{item.Quantity}</td> <td>${item.UnitPrice:F2}</td> <td>${item.Total:F2}</td> </tr> ")); // Build the complete HTML invoice using string interpolation // All invoice data is injected into the template dynamically string invoiceHtml = $@"<!DOCTYPE html><html><head> <style> body {{ font-family: Arial, sans-serif; padding: 40px; }} .header {{ text-align: right; margin-bottom: 40px; }} .company-name {{ font-size: 24px; font-weight: bold; color: #333; }} .invoice-details {{ margin: 20px 0; }} table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }} th {{ background-color: #2A95D5; color: white; padding: 10px; text-align: left; }} td {{ padding: 10px; border-bottom: 1px solid #ddd; }} .totals {{ text-align: right; margin-top: 20px; }} .totals div {{ margin: 5px 0; }} .grand-total {{ font-size: 20px; font-weight: bold; color: #2A95D5; }} </style></head><body> <div class='header'> <div class='company-name'>Your Company Name</div> </div> <h1>INVOICE</h1> <div class='invoice-details'> <strong>Invoice Number:</strong> {invoice.InvoiceNumber}<br> <strong>Date:</strong> {invoice.InvoiceDate:MMM dd, yyyy}<br> <strong>Bill To:</strong> {invoice.CustomerName}<br> {invoice.CustomerAddress} </div> <table> <tr> <th>Description</th> <th>Quantity</th> <th>Unit Price</th> <th>Total</th> </tr> {lineItemsHtml} </table> <div class='totals'> <div>Subtotal: ${invoice.Subtotal:F2}</div> <div>Tax ({invoice.TaxRate:P0}): ${invoice.Tax:F2}</div> <div class='grand-total'>Total: ${invoice.Total:F2}</div> </div></body></html>"; // Render HTML to PDF and return the document var renderer = new ChromePdfRenderer(); return renderer.RenderHtmlAsPdf(invoiceHtml); }}
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
// Represents a single line item on an invoice
public class InvoiceLineItem
{
public string Description { get; set; }
public decimal Quantity { get; set; }
public decimal UnitPrice { get; set; }
// Auto-calculates line total from quantity and unit price
public decimal Total => Quantity * UnitPrice;
}
// Represents a complete invoice with customer details and line items
public class Invoice
{
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public List<InvoiceLineItem> LineItems { get; set; }
// Computed properties for invoice totals
public decimal Subtotal => LineItems.Sum(item => item.Total);
public decimal TaxRate { get; set; } = 0.08m; // Default 8% tax rate
public decimal Tax => Subtotal * TaxRate;
public decimal Total => Subtotal + Tax;
}
// Generates PDF invoices from Invoice objects using HTML templates
public class InvoiceGenerator
{
public PdfDocument GenerateInvoice(Invoice invoice)
{
// Build HTML table rows dynamically from line items
string lineItemsHtml = string.Join("", invoice.LineItems.Select(item => $@"
<tr>
<td>{item.Description}</td>
<td>{item.Quantity}</td>
<td>${item.UnitPrice:F2}</td>
<td>${item.Total:F2}</td>
</tr>
"));
// Build the complete HTML invoice using string interpolation
// All invoice data is injected into the template dynamically
string invoiceHtml = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
.header {{ text-align: right; margin-bottom: 40px; }}
.company-name {{ font-size: 24px; font-weight: bold; color: #333; }}
.invoice-details {{ margin: 20px 0; }}
table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
th {{ background-color: #2A95D5; color: white; padding: 10px; text-align: left; }}
td {{ padding: 10px; border-bottom: 1px solid #ddd; }}
.totals {{ text-align: right; margin-top: 20px; }}
.totals div {{ margin: 5px 0; }}
.grand-total {{ font-size: 20px; font-weight: bold; color: #2A95D5; }}
</style>
</head>
<body>
<div class='header'>
<div class='company-name'>Your Company Name</div>
</div>
<h1>INVOICE</h1>
<div class='invoice-details'>
<strong>Invoice Number:</strong> {invoice.InvoiceNumber}<br>
<strong>Date:</strong> {invoice.InvoiceDate:MMM dd, yyyy}<br>
<strong>Bill To:</strong> {invoice.CustomerName}<br>
{invoice.CustomerAddress}
</div>
<table>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
{lineItemsHtml}
</table>
<div class='totals'>
<div>Subtotal: ${invoice.Subtotal:F2}</div>
<div>Tax ({invoice.TaxRate:P0}): ${invoice.Tax:F2}</div>
<div class='grand-total'>Total: ${invoice.Total:F2}</div>
</div>
</body>
</html>";
// Render HTML to PDF and return the document
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(invoiceHtml);
}
}
ImportsIronPdfImportsSystemImportsSystem.Collections.GenericImportsSystem.Linq' Represents a single line item on an invoicePublic Class InvoiceLineItem Public Property DescriptionAsString Public Property QuantityAsDecimal Public Property UnitPriceAsDecimal ' Auto-calculates line total from quantity and unit price PublicReadOnlyPropertyTotalAsDecimal Get ReturnQuantity * UnitPriceEnd Get End PropertyEnd Class' Represents a complete invoice with customer details and line itemsPublic Class Invoice Public Property InvoiceNumberAsString Public Property InvoiceDateAsDateTime Public Property CustomerNameAsString Public Property CustomerAddressAsString Public Property LineItemsAsList(OfInvoiceLineItem) ' Computed properties for invoice totals PublicReadOnlyPropertySubtotalAsDecimal Get ReturnLineItems.Sum(Function(item) item.Total)End Get End Property Public Property TaxRateAsDecimal = 0.08D ' Default 8% tax rate PublicReadOnlyPropertyTaxAsDecimal Get ReturnSubtotal * TaxRateEnd Get End Property PublicReadOnlyPropertyTotalAsDecimal Get ReturnSubtotal + TaxEnd Get End PropertyEnd Class' Generates PDF invoices from Invoice objects using HTML templatesPublic Class InvoiceGenerator Public Function GenerateInvoice(invoice AsInvoice) AsPdfDocument ' Build HTML table rows dynamically from line items Dim lineItemsHtml AsString = String.Join("", invoice.LineItems.Select(Function(item) $" <tr> <td>{item.Description}</td> <td>{item.Quantity}</td> <td>${item.UnitPrice:F2}</td> <td>${item.Total:F2}</td> </tr> ")) ' Build the complete HTML invoice using string interpolation ' All invoice data is injected into the template dynamically Dim invoiceHtml AsString = $"<!DOCTYPE html><html><head> <style> body {{ font-family: Arial, sans-serif; padding: 40px; }} .header {{ text-align: right; margin-bottom: 40px; }} .company-name {{ font-size: 24px; font-weight: bold; color: #333; }} .invoice-details {{ margin: 20px 0; }} table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }} th {{ background-color: #2A95D5; color: white; padding: 10px; text-align: left; }} td {{ padding: 10px; border-bottom: 1px solid #ddd; }} .totals {{ text-align: right; margin-top: 20px; }} .totals div {{ margin: 5px 0; }} .grand-total {{ font-size: 20px; font-weight: bold; color: #2A95D5; }} </style></head><body> <div class='header'> <div class='company-name'>Your Company Name</div> </div> <h1>INVOICE</h1> <div class='invoice-details'> <strong>Invoice Number:</strong> {invoice.InvoiceNumber}<br> <strong>Date:</strong> {invoice.InvoiceDate:MMM dd, yyyy}<br> <strong>Bill To:</strong> {invoice.CustomerName}<br> {invoice.CustomerAddress} </div> <table> <tr> <th>Description</th> <th>Quantity</th> <th>Unit Price</th> <th>Total</th> </tr> {lineItemsHtml} </table> <div class='totals'> <div>Subtotal: ${invoice.Subtotal:F2}</div> <div>Tax ({invoice.TaxRate:P0}): ${invoice.Tax:F2}</div> <div class='grand-total'>Total: ${invoice.Total:F2}</div> </div></body></html>" ' Render HTML to PDF and return the document Dim renderer As New ChromePdfRenderer() Return renderer.RenderHtmlAsPdf(invoiceHtml) End FunctionEnd Class
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq
' Represents a single line item on an invoice
Public Class InvoiceLineItem
Public Property Description As String
Public Property Quantity As Decimal
Public Property UnitPrice As Decimal
' Auto-calculates line total from quantity and unit price
Public ReadOnly Property Total As Decimal
Get
Return Quantity * UnitPrice
End Get
End Property
End Class
' Represents a complete invoice with customer details and line items
Public Class Invoice
Public Property InvoiceNumber As String
Public Property InvoiceDate As DateTime
Public Property CustomerName As String
Public Property CustomerAddress As String
Public Property LineItems As List(Of InvoiceLineItem)
' Computed properties for invoice totals
Public ReadOnly Property Subtotal As Decimal
Get
Return LineItems.Sum(Function(item) item.Total)
End Get
End Property
Public Property TaxRate As Decimal = 0.08D ' Default 8% tax rate
Public ReadOnly Property Tax As Decimal
Get
Return Subtotal * TaxRate
End Get
End Property
Public ReadOnly Property Total As Decimal
Get
Return Subtotal + Tax
End Get
End Property
End Class
' Generates PDF invoices from Invoice objects using HTML templates
Public Class InvoiceGenerator
Public Function GenerateInvoice(invoice As Invoice) As PdfDocument
' Build HTML table rows dynamically from line items
Dim lineItemsHtml As String = String.Join("", invoice.LineItems.Select(Function(item) $"
<tr>
<td>{item.Description}</td>
<td>{item.Quantity}</td>
<td>${item.UnitPrice:F2}</td>
<td>${item.Total:F2}</td>
</tr>
"))
' Build the complete HTML invoice using string interpolation
' All invoice data is injected into the template dynamically
Dim invoiceHtml As String = $"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
.header {{ text-align: right; margin-bottom: 40px; }}
.company-name {{ font-size: 24px; font-weight: bold; color: #333; }}
.invoice-details {{ margin: 20px 0; }}
table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
th {{ background-color: #2A95D5; color: white; padding: 10px; text-align: left; }}
td {{ padding: 10px; border-bottom: 1px solid #ddd; }}
.totals {{ text-align: right; margin-top: 20px; }}
.totals div {{ margin: 5px 0; }}
.grand-total {{ font-size: 20px; font-weight: bold; color: #2A95D5; }}
</style>
</head>
<body>
<div class='header'>
<div class='company-name'>Your Company Name</div>
</div>
<h1>INVOICE</h1>
<div class='invoice-details'>
<strong>Invoice Number:</strong> {invoice.InvoiceNumber}<br>
<strong>Date:</strong> {invoice.InvoiceDate:MMM dd, yyyy}<br>
<strong>Bill To:</strong> {invoice.CustomerName}<br>
{invoice.CustomerAddress}
</div>
<table>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
{lineItemsHtml}
</table>
<div class='totals'>
<div>Subtotal: ${invoice.Subtotal:F2}</div>
<div>Tax ({invoice.TaxRate:P0}): ${invoice.Tax:F2}</div>
<div class='grand-total'>Total: ${invoice.Total:F2}</div>
</div>
</body>
</html>"
' Render HTML to PDF and return the document
Dim renderer As New ChromePdfRenderer()
Return renderer.RenderHtmlAsPdf(invoiceHtml)
End Function
End Class
Sample Output
The Invoice class encapsulates all invoice data with calculated properties for subtotal, tax, and total. The generator transforms this data into HTML using string interpolation, then renders it to PDF. This separation of concerns makes the code maintainable and testable.
How to Add Company Branding and Watermarks to Invoices
Professional invoices need branding elements like logos and, in some cases, watermarks to indicate payment status. IronPDF supports both embedded images in HTML and programmatic watermarking after rendering.
using IronPdf;var renderer = new ChromePdfRenderer();// Invoice HTML template with company logo embedded via URL// Logo can also be Base64-encoded or a local file pathstring htmlWithLogo = @"<!DOCTYPE html><html><head><style>body { font-family: Arial, sans-serif; padding: 40px; }.logo { width: 200px; margin-bottom: 20px; }</style></head><body><div style='text-align: center;'><img src='https://yourcompany.com/logo.png' alt='Company Logo' class='logo' /></div><h1>INVOICE</h1><p><strong>Invoice Number:</strong> INV-2024-001</p><p><strong>Total:</strong> $1,250.00</p></body></html>";// Render the HTML to PDFvar pdf = renderer.RenderHtmlAsPdf(htmlWithLogo);// Apply a diagonal "UNPAID" watermark to mark invoice status// 30% opacity keeps the content readable while the watermark is visiblepdf.ApplyWatermark("<h1 style='color: red;'>UNPAID</h1>", opacity: 30, rotation: 45, verticalAlignment: IronPdf.Editing.VerticalAlignment.Middle);pdf.SaveAs("invoice-with-watermark.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Invoice HTML template with company logo embedded via URL
// Logo can also be Base64-encoded or a local file path
string htmlWithLogo = @"
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.logo { width: 200px; margin-bottom: 20px; }
</style>
</head>
<body>
<div style='text-align: center;'>
<img src='https://yourcompany.com/logo.png' alt='Company Logo' class='logo' />
</div>
<h1>INVOICE</h1>
<p><strong>Invoice Number:</strong> INV-2024-001</p>
<p><strong>Total:</strong> $1,250.00</p>
</body>
</html>";
// Render the HTML to PDF
var pdf = renderer.RenderHtmlAsPdf(htmlWithLogo);
// Apply a diagonal "UNPAID" watermark to mark invoice status
// 30% opacity keeps the content readable while the watermark is visible
pdf.ApplyWatermark("<h1 style='color: red;'>UNPAID</h1>",
opacity: 30,
rotation: 45,
verticalAlignment: IronPdf.Editing.VerticalAlignment.Middle);
pdf.SaveAs("invoice-with-watermark.pdf");
C#
Sample Output
The ApplyWatermark method accepts HTML content, giving you complete control over the watermark's appearance. You can adjust opacity, rotation, and positioning to achieve exactly the look you need. This is particularly useful for marking invoices as "PAID," "DRAFT," or "CANCELLED" without regenerating the entire document.
How to Embed QR Codes for Payment Links
Modern invoices often include QR codes that customers can scan to make payments quickly. While IronPDF focuses on PDF generation, it works with IronQR for barcode creation:
using IronPdf;using IronQr;using IronSoftware.Drawing;string invoiceNumber = "INV-2026-002";decimal amount = 1500.00m;// Create a payment URL with invoice details as query parametersstring paymentUrl = $"https://yourcompany.com/pay?invoice={invoiceNumber}&amount={amount}";// Generate QR code from the payment URL using IronQRQrCode qrCode = QrWriter.Write(paymentUrl);AnyBitmap qrImage = qrCode.Save();qrImage.SaveAs("payment-qr.png", AnyBitmap.ImageFormat.Png);// Build invoice HTML with the QR code image embedded// Customers can scan the QR to pay directly from their phonestring invoiceHtml = $@"<!DOCTYPE html><html><head><style>body {{ font-family: Arial, sans-serif; padding: 40px; }}.payment-section {{ margin-top: 40px; text-align: center; border-top: 2px solid #eee; padding-top: 20px; }}.qr-code {{ width: 150px; height: 150px; }}</style></head><body><h1>INVOICE {invoiceNumber}</h1><p><strong>Amount Due:</strong> ${amount:F2}</p><div class='payment-section'><p><strong>Scan to Pay Instantly:</strong></p><img src='payment-qr.png' alt='Payment QR Code' class='qr-code' /><p style='font-size: 12px; color: #666;'> Or visit: {paymentUrl}</p></div></body></html>";// Convert HTML to PDF and savevar renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf(invoiceHtml);pdf.SaveAs($"invoice-{invoiceNumber}.pdf");
using IronPdf;
using IronQr;
using IronSoftware.Drawing;
string invoiceNumber = "INV-2026-002";
decimal amount = 1500.00m;
// Create a payment URL with invoice details as query parameters
string paymentUrl = $"https://yourcompany.com/pay?invoice={invoiceNumber}&amount={amount}";
// Generate QR code from the payment URL using IronQR
QrCode qrCode = QrWriter.Write(paymentUrl);
AnyBitmap qrImage = qrCode.Save();
qrImage.SaveAs("payment-qr.png", AnyBitmap.ImageFormat.Png);
// Build invoice HTML with the QR code image embedded
// Customers can scan the QR to pay directly from their phone
string invoiceHtml = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
.payment-section {{ margin-top: 40px; text-align: center;
border-top: 2px solid #eee; padding-top: 20px; }}
.qr-code {{ width: 150px; height: 150px; }}
</style>
</head>
<body>
<h1>INVOICE {invoiceNumber}</h1>
<p><strong>Amount Due:</strong> ${amount:F2}</p>
<div class='payment-section'>
<p><strong>Scan to Pay Instantly:</strong></p>
<img src='payment-qr.png' alt='Payment QR Code' class='qr-code' />
<p style='font-size: 12px; color: #666;'>
Or visit: {paymentUrl}
</p>
</div>
</body>
</html>";
// Convert HTML to PDF and save
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(invoiceHtml);
pdf.SaveAs($"invoice-{invoiceNumber}.pdf");
C#
Sample Output
The QR code links directly to a payment page, reducing friction for customers and accelerating your cash flow. This pattern works with any payment provider that supports URL-based payment initiation.
How to Comply with ZUGFeRD and Factur-X E-Invoicing Standards in C#
Electronic invoicing is rapidly becoming mandatory across Europe. Germany led the way with ZUGFeRD, and France followed with Factur-X. These standards embed machine-readable XML data within PDF invoices, enabling automated processing while maintaining human-readable documents. Understanding and implementing these standards is increasingly essential for businesses operating in European markets.
What is ZUGFeRD and How Does It Work?
ZUGFeRD (Zentraler User Guide des Forums elektronische Rechnung Deutschland) is a German e-invoicing standard that embeds invoice data as an XML file attachment within a PDF/A-3 compliant document. The embedded XML enables automated data extraction without OCR or parsing.
The standard defines three conformance levels, each offering progressively more structured data:
Basic: Contains core invoice data suitable for simple automated processing
Comfort: Adds detailed information enabling fully automated invoice handling
Extended: Includes comprehensive data for complex business scenarios across industries
The XML follows the UN/CEFACT Cross-Industry Invoice (CII) schema, which has become the basis for European e-invoicing standardization.
What is Factur-X and How Does It Differ from ZUGFeRD?
Factur-X is the French implementation of the same underlying standard. ZUGFeRD 2.0 and Factur-X are technically identical. They share the same XML schema and conformance profiles based on the European Norm EN 16931. The difference is purely regional naming: an invoice created to ZUGFeRD specifications will be valid under Factur-X, and vice versa.
How to Embed XML Data in PDF/A-3 Invoices
IronPDF provides the attachment capabilities needed to create compliant e-invoices. The process involves generating your invoice PDF, creating the XML data according to the CII schema, and embedding the XML as an attachment with the correct naming conventions:
using System;using System.Xml.Linq;// Generates ZUGFeRD-compliant invoices by embedding structured XML data// ZUGFeRD allows automated processing while keeping a human-readable PDFpublic class ZUGFeRDInvoiceGenerator{ public voidGenerateZUGFeRDInvoice(Invoice invoice) { // First, create the visual PDF that humans will read var renderer = new ChromePdfRenderer(); string invoiceHtml = BuildInvoiceHtml(invoice); var pdf = renderer.RenderHtmlAsPdf(invoiceHtml); // Define the UN/CEFACT namespaces required by the ZUGFeRD standard // These are mandatory for compliance with European e-invoicing regulations XNamespace rsm = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"; XNamespace ram = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100"; XNamespace udt = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100"; // Build the ZUGFeRD XML structure following the Cross-Industry Invoice schema var zugferdXml = new XDocument( new XDeclaration("1.0", "UTF-8", null), new XElement(rsm + "CrossIndustryInvoice", new XAttribute(XNamespace.Xmlns + "rsm", rsm.NamespaceName), new XAttribute(XNamespace.Xmlns + "ram", ram.NamespaceName), new XAttribute(XNamespace.Xmlns + "udt", udt.NamespaceName), // Document context identifies which e-invoicing guideline is being followed new XElement(rsm + "ExchangedDocumentContext", new XElement(ram + "GuidelineSpecifiedDocumentContextParameter", new XElement(ram + "ID", "urn:cen.eu:en16931:2017") ) ), // Core document identification: invoice number, type, and date new XElement(rsm + "ExchangedDocument", new XElement(ram + "ID", invoice.InvoiceNumber), new XElement(ram + "TypeCode", "380"), // 380 = Commercial Invoice per UN/CEFACT new XElement(ram + "IssueDateTime", new XElement(udt + "DateTimeString", new XAttribute("format", "102"), invoice.InvoiceDate.ToString("yyyyMMdd") ) ) ), // A complete implementation would include additional sections: // - Seller information (ram:SellerTradeParty) // - Buyer information (ram:BuyerTradeParty) // - Line items (ram:IncludedSupplyChainTradeLineItem) // - Payment terms (ram:SpecifiedTradePaymentTerms) // - Tax summaries (ram:ApplicableTradeTax) // Financial summary with all monetary totals new XElement(rsm + "SupplyChainTradeTransaction", new XElement(ram + "ApplicableHeaderTradeSettlement", new XElement(ram + "InvoiceCurrencyCode", "EUR"), new XElement(ram + "SpecifiedTradeSettlementHeaderMonetarySummation", new XElement(ram + "TaxBasisTotalAmount", invoice.Subtotal), new XElement(ram + "TaxTotalAmount", new XAttribute("currencyID", "EUR"), invoice.Tax), new XElement(ram + "GrandTotalAmount", invoice.Total), new XElement(ram + "DuePayableAmount", invoice.Total) ) ) ) ) ); // Save the XML to a temp file for embedding string xmlPath = $"zugferd-{invoice.InvoiceNumber}.xml"; zugferdXml.Save(xmlPath); // Attach the XML to the PDF - filename must follow ZUGFeRD conventions byte[] xmlData = System.IO.File.ReadAllBytes(xmlPath); pdf.Attachments.AddAttachment("zugferd-invoice.xml", xmlData); // Final PDF contains both visual invoice and machine-readable XML pdf.SaveAs($"invoice-{invoice.InvoiceNumber}-zugferd.pdf"); } // Generates simple HTML for the visual portion of the invoice private stringBuildInvoiceHtml(Invoice invoice) { return $@"<!DOCTYPE html><html><head> <style> body {{ font-family: Arial, sans-serif; padding: 40px; }} h1 {{ color: #333; }} .zugferd-notice {{ margin-top: 30px; padding: 10px; background: #f0f0f0; font-size: 11px; }} </style></head><body> <h1>RECHNUNG / INVOICE</h1> <p><strong>Rechnungsnummer:</strong> {invoice.InvoiceNumber}</p> <p><strong>Datum:</strong> {invoice.InvoiceDate:dd.MM.yyyy}</p> <p><strong>Betrag:</strong> €{invoice.Total:F2}</p> <div class='zugferd-notice'> This invoice contains embedded ZUGFeRD data for automated processing. </div></body></html>"; }}
using System;
using System.Xml.Linq;
// Generates ZUGFeRD-compliant invoices by embedding structured XML data
// ZUGFeRD allows automated processing while keeping a human-readable PDF
public class ZUGFeRDInvoiceGenerator
{
public void GenerateZUGFeRDInvoice(Invoice invoice)
{
// First, create the visual PDF that humans will read
var renderer = new ChromePdfRenderer();
string invoiceHtml = BuildInvoiceHtml(invoice);
var pdf = renderer.RenderHtmlAsPdf(invoiceHtml);
// Define the UN/CEFACT namespaces required by the ZUGFeRD standard
// These are mandatory for compliance with European e-invoicing regulations
XNamespace rsm = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100";
XNamespace ram = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100";
XNamespace udt = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100";
// Build the ZUGFeRD XML structure following the Cross-Industry Invoice schema
var zugferdXml = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement(rsm + "CrossIndustryInvoice",
new XAttribute(XNamespace.Xmlns + "rsm", rsm.NamespaceName),
new XAttribute(XNamespace.Xmlns + "ram", ram.NamespaceName),
new XAttribute(XNamespace.Xmlns + "udt", udt.NamespaceName),
// Document context identifies which e-invoicing guideline is being followed
new XElement(rsm + "ExchangedDocumentContext",
new XElement(ram + "GuidelineSpecifiedDocumentContextParameter",
new XElement(ram + "ID", "urn:cen.eu:en16931:2017")
)
),
// Core document identification: invoice number, type, and date
new XElement(rsm + "ExchangedDocument",
new XElement(ram + "ID", invoice.InvoiceNumber),
new XElement(ram + "TypeCode", "380"), // 380 = Commercial Invoice per UN/CEFACT
new XElement(ram + "IssueDateTime",
new XElement(udt + "DateTimeString",
new XAttribute("format", "102"),
invoice.InvoiceDate.ToString("yyyyMMdd")
)
)
),
// A complete implementation would include additional sections:
// - Seller information (ram:SellerTradeParty)
// - Buyer information (ram:BuyerTradeParty)
// - Line items (ram:IncludedSupplyChainTradeLineItem)
// - Payment terms (ram:SpecifiedTradePaymentTerms)
// - Tax summaries (ram:ApplicableTradeTax)
// Financial summary with all monetary totals
new XElement(rsm + "SupplyChainTradeTransaction",
new XElement(ram + "ApplicableHeaderTradeSettlement",
new XElement(ram + "InvoiceCurrencyCode", "EUR"),
new XElement(ram + "SpecifiedTradeSettlementHeaderMonetarySummation",
new XElement(ram + "TaxBasisTotalAmount", invoice.Subtotal),
new XElement(ram + "TaxTotalAmount",
new XAttribute("currencyID", "EUR"),
invoice.Tax),
new XElement(ram + "GrandTotalAmount", invoice.Total),
new XElement(ram + "DuePayableAmount", invoice.Total)
)
)
)
)
);
// Save the XML to a temp file for embedding
string xmlPath = $"zugferd-{invoice.InvoiceNumber}.xml";
zugferdXml.Save(xmlPath);
// Attach the XML to the PDF - filename must follow ZUGFeRD conventions
byte[] xmlData = System.IO.File.ReadAllBytes(xmlPath);
pdf.Attachments.AddAttachment("zugferd-invoice.xml", xmlData);
// Final PDF contains both visual invoice and machine-readable XML
pdf.SaveAs($"invoice-{invoice.InvoiceNumber}-zugferd.pdf");
}
// Generates simple HTML for the visual portion of the invoice
private string BuildInvoiceHtml(Invoice invoice)
{
return $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
h1 {{ color: #333; }}
.zugferd-notice {{
margin-top: 30px; padding: 10px;
background: #f0f0f0; font-size: 11px;
}}
</style>
</head>
<body>
<h1>RECHNUNG / INVOICE</h1>
<p><strong>Rechnungsnummer:</strong> {invoice.InvoiceNumber}</p>
<p><strong>Datum:</strong> {invoice.InvoiceDate:dd.MM.yyyy}</p>
<p><strong>Betrag:</strong> €{invoice.Total:F2}</p>
<div class='zugferd-notice'>
This invoice contains embedded ZUGFeRD data for automated processing.
</div>
</body>
</html>";
}
}
C#
Sample Output
The key aspects of compliance are using the correct XML namespaces, following the CII schema structure, and embedding the XML with an appropriate filename. The TypeCode "380" specifically identifies the document as a commercial invoice within the UN/CEFACT standard.
How to Future-Proof Invoices for EU Mandates
The European Union is progressively mandating e-invoicing across member states. Italy already requires it for B2B transactions, France is phasing in requirements through 2026, and Germany has announced mandatory B2B e-invoicing starting in 2025. Building ZUGFeRD/Factur-X support now prepares your system for these regulatory requirements.
Here's a pattern for a compliance-aware invoice generator that can target different standards:
using IronPdf;using System;// Enum representing supported European e-invoicing standardspublic enum InvoiceStandard{None,ZUGFeRD, // German standard - uses CII XML formatFacturX, // French standard - technically identical to ZUGFeRD 2.0Peppol// Pan-European standard - uses UBL XML format}// Factory class that generates invoices compliant with different e-invoicing standards// Allows switching between standards without changing core invoice generation logicpublic class CompliantInvoiceGenerator{ public PdfDocumentGenerateCompliantInvoice(Invoice invoice, InvoiceStandard standard) { // Generate the base PDF from HTML var renderer = new ChromePdfRenderer(); string html = BuildInvoiceHtml(invoice); var pdf = renderer.RenderHtmlAsPdf(html); // Attach the appropriate XML format based on target market/regulation switch (standard) { case InvoiceStandard.ZUGFeRD: case InvoiceStandard.FacturX: // Both use Cross-Industry Invoice format, just different filenamesEmbedCIIXmlData(pdf, invoice, standard); break; case InvoiceStandard.Peppol: // Peppol uses Universal Business Language formatEmbedUBLXmlData(pdf, invoice); break; } return pdf; } // Creates and embeds CII-format XML (used by ZUGFeRD and Factur-X) private voidEmbedCIIXmlData(PdfDocument pdf, Invoice invoice, InvoiceStandard standard) { string xml = GenerateCIIXml(invoice); // Filename convention differs between German and French standards string filename = standard == InvoiceStandard.ZUGFeRD ? "zugferd-invoice.xml" : "factur-x.xml";System.IO.File.WriteAllText("temp-invoice.xml", xml); byte[] xmlData = System.IO.File.ReadAllBytes("temp-invoice.xml"); pdf.Attachments.AddAttachment(filename, xmlData); } // Creates and embeds UBL-format XML for Peppol network compliance private voidEmbedUBLXmlData(PdfDocument pdf, Invoice invoice) { // UBL (Universal Business Language) is the Peppol standard format string xml = $@"<?xml version='1.0' encoding='UTF-8'?><Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2'> <ID>{invoice.InvoiceNumber}</ID> <IssueDate>{invoice.InvoiceDate:yyyy-MM-dd}</IssueDate> <DocumentCurrencyCode>EUR</DocumentCurrencyCode> <LegalMonetaryTotal> <PayableAmount currencyID='EUR'>{invoice.Total}</PayableAmount> </LegalMonetaryTotal></Invoice>";System.IO.File.WriteAllText("peppol-invoice.xml", xml); pdf.Attachments.AddFile("peppol-invoice.xml", "invoice.xml", "Peppol UBL Invoice"); } // Generates minimal CII XML structure for demonstration private stringGenerateCIIXml(Invoice invoice) { return $@"<?xml version='1.0' encoding='UTF-8'?><rsm:CrossIndustryInvoice xmlns:rsm='urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100' xmlns:ram='urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'> <rsm:ExchangedDocument> <ram:ID>{invoice.InvoiceNumber}</ram:ID> <ram:TypeCode>380</ram:TypeCode> </rsm:ExchangedDocument></rsm:CrossIndustryInvoice>"; } private stringBuildInvoiceHtml(Invoice invoice) { return $"<html><body><h1>Invoice {invoice.InvoiceNumber}</h1></body></html>"; }}
using IronPdf;
using System;
// Enum representing supported European e-invoicing standards
public enum InvoiceStandard
{
None,
ZUGFeRD, // German standard - uses CII XML format
FacturX, // French standard - technically identical to ZUGFeRD 2.0
Peppol // Pan-European standard - uses UBL XML format
}
// Factory class that generates invoices compliant with different e-invoicing standards
// Allows switching between standards without changing core invoice generation logic
public class CompliantInvoiceGenerator
{
public PdfDocument GenerateCompliantInvoice(Invoice invoice, InvoiceStandard standard)
{
// Generate the base PDF from HTML
var renderer = new ChromePdfRenderer();
string html = BuildInvoiceHtml(invoice);
var pdf = renderer.RenderHtmlAsPdf(html);
// Attach the appropriate XML format based on target market/regulation
switch (standard)
{
case InvoiceStandard.ZUGFeRD:
case InvoiceStandard.FacturX:
// Both use Cross-Industry Invoice format, just different filenames
EmbedCIIXmlData(pdf, invoice, standard);
break;
case InvoiceStandard.Peppol:
// Peppol uses Universal Business Language format
EmbedUBLXmlData(pdf, invoice);
break;
}
return pdf;
}
// Creates and embeds CII-format XML (used by ZUGFeRD and Factur-X)
private void EmbedCIIXmlData(PdfDocument pdf, Invoice invoice, InvoiceStandard standard)
{
string xml = GenerateCIIXml(invoice);
// Filename convention differs between German and French standards
string filename = standard == InvoiceStandard.ZUGFeRD
? "zugferd-invoice.xml"
: "factur-x.xml";
System.IO.File.WriteAllText("temp-invoice.xml", xml);
byte[] xmlData = System.IO.File.ReadAllBytes("temp-invoice.xml");
pdf.Attachments.AddAttachment(filename, xmlData);
}
// Creates and embeds UBL-format XML for Peppol network compliance
private void EmbedUBLXmlData(PdfDocument pdf, Invoice invoice)
{
// UBL (Universal Business Language) is the Peppol standard format
string xml = $@"<?xml version='1.0' encoding='UTF-8'?>
<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2'>
<ID>{invoice.InvoiceNumber}</ID>
<IssueDate>{invoice.InvoiceDate:yyyy-MM-dd}</IssueDate>
<DocumentCurrencyCode>EUR</DocumentCurrencyCode>
<LegalMonetaryTotal>
<PayableAmount currencyID='EUR'>{invoice.Total}</PayableAmount>
</LegalMonetaryTotal>
</Invoice>";
System.IO.File.WriteAllText("peppol-invoice.xml", xml);
pdf.Attachments.AddFile("peppol-invoice.xml", "invoice.xml", "Peppol UBL Invoice");
}
// Generates minimal CII XML structure for demonstration
private string GenerateCIIXml(Invoice invoice)
{
return $@"<?xml version='1.0' encoding='UTF-8'?>
<rsm:CrossIndustryInvoice
xmlns:rsm='urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'
xmlns:ram='urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'>
<rsm:ExchangedDocument>
<ram:ID>{invoice.InvoiceNumber}</ram:ID>
<ram:TypeCode>380</ram:TypeCode>
</rsm:ExchangedDocument>
</rsm:CrossIndustryInvoice>";
}
private string BuildInvoiceHtml(Invoice invoice)
{
return $"<html><body><h1>Invoice {invoice.InvoiceNumber}</h1></body></html>";
}
}
C#
This architecture allows you to add new standards as they emerge without restructuring your core invoice generation logic. The enum-based approach makes it easy to let users or configuration determine which compliance mode to use.
My favorite library of this kind is IronPDF. It allows for fast and efficient manipulation of PDF files. It also has many valuable features, like exporting to PDF/A format and digitally signing PDF documents.
IronOCR means we can save $40,000 annually from manual processing, while enhancing productivity and freeing up resources for high-impact tasks. I would highly recommend it.
Generating invoices is only half the equation. Most businesses also receive invoices from vendors and need to extract data for processing. IronPDF provides powerful text extraction capabilities that form the foundation of invoice data capture.
How to Extract Text from a PDF Invoice
The most fundamental extraction operation retrieves all text content from a PDF. IronPDF's ExtractAllText method handles the complexity of PDF text encoding and positioning:
using IronPdf;using System;// Extracts raw text content from PDF invoices for further processingpublic class InvoiceTextExtractor{ // Extracts all text from a PDF in one operation // Best for single-page invoices or when you need the complete content public stringExtractInvoiceText(string pdfPath) { var pdf = PdfDocument.FromFile(pdfPath); // IronPDF handles the complexity of PDF text encoding and positioning string allText = pdf.ExtractAllText();Console.WriteLine("Full invoice text:");Console.WriteLine(allText); return allText; } // Extracts text page by page - useful for multi-page invoices // Allows you to process header info separately from line items public voidExtractTextByPage(string pdfPath) { var pdf = PdfDocument.FromFile(pdfPath); // Iterate through each page (0-indexed) for (int i = 0; i < pdf.PageCount; i++) { string pageText = pdf.ExtractTextFromPage(i);Console.WriteLine($"\n--- Page {i + 1} ---");Console.WriteLine(pageText); } }}
using IronPdf;
using System;
// Extracts raw text content from PDF invoices for further processing
public class InvoiceTextExtractor
{
// Extracts all text from a PDF in one operation
// Best for single-page invoices or when you need the complete content
public string ExtractInvoiceText(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
// IronPDF handles the complexity of PDF text encoding and positioning
string allText = pdf.ExtractAllText();
Console.WriteLine("Full invoice text:");
Console.WriteLine(allText);
return allText;
}
// Extracts text page by page - useful for multi-page invoices
// Allows you to process header info separately from line items
public void ExtractTextByPage(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
// Iterate through each page (0-indexed)
for (int i = 0; i < pdf.PageCount; i++)
{
string pageText = pdf.ExtractTextFromPage(i);
Console.WriteLine($"\n--- Page {i + 1} ---");
Console.WriteLine(pageText);
}
}
}
ImportsIronPdfImportsSystem' Extracts raw text content from PDF invoices for further processingPublic Class InvoiceTextExtractor ' Extracts all text from a PDF in one operation ' Best for single-page invoices or when you need the complete content Public Function ExtractInvoiceText(pdfPath AsString) AsString Dim pdf = PdfDocument.FromFile(pdfPath) ' IronPDF handles the complexity of PDF text encoding and positioning Dim allText AsString = pdf.ExtractAllText()Console.WriteLine("Full invoice text:")Console.WriteLine(allText) Return allText End Function ' Extracts text page by page - useful for multi-page invoices ' Allows you to process header info separately from line items Public Sub ExtractTextByPage(pdfPath AsString) Dim pdf = PdfDocument.FromFile(pdfPath) ' Iterate through each page (0-indexed) For i AsInteger = 0 To pdf.PageCount - 1 Dim pageText AsString = pdf.ExtractTextFromPage(i)Console.WriteLine(vbCrLf & "--- Page " & (i + 1).ToString() & " ---")Console.WriteLine(pageText) Next End SubEnd Class
Imports IronPdf
Imports System
' Extracts raw text content from PDF invoices for further processing
Public Class InvoiceTextExtractor
' Extracts all text from a PDF in one operation
' Best for single-page invoices or when you need the complete content
Public Function ExtractInvoiceText(pdfPath As String) As String
Dim pdf = PdfDocument.FromFile(pdfPath)
' IronPDF handles the complexity of PDF text encoding and positioning
Dim allText As String = pdf.ExtractAllText()
Console.WriteLine("Full invoice text:")
Console.WriteLine(allText)
Return allText
End Function
' Extracts text page by page - useful for multi-page invoices
' Allows you to process header info separately from line items
Public Sub ExtractTextByPage(pdfPath As String)
Dim pdf = PdfDocument.FromFile(pdfPath)
' Iterate through each page (0-indexed)
For i As Integer = 0 To pdf.PageCount - 1
Dim pageText As String = pdf.ExtractTextFromPage(i)
Console.WriteLine(vbCrLf & "--- Page " & (i + 1).ToString() & " ---")
Console.WriteLine(pageText)
Next
End Sub
End Class
Page-by-page extraction is particularly useful for multi-page invoices where you need to locate specific sections, such as finding line items that span multiple pages whereas header information appears only on the first page.
How to Extract Table Data for Line Items
Invoice line items typically appear in tabular format. PDFs lack a native table structure, but you can extract text and parse it to reconstruct table data:
using IronPdf;using System;using System.Collections.Generic;// Data model for a single invoice line itempublic class InvoiceLineItem{ public stringDescription { get; set; } public decimalQuantity { get; set; } public decimalUnitPrice { get; set; } public decimalTotal { get; set; }}// Extracts tabular line item data from PDF invoices// Note: PDFs don't have native table structure, so this uses text parsingpublic class InvoiceTableExtractor{ public List<InvoiceLineItem> ExtractLineItems(string pdfPath) { var pdf = PdfDocument.FromFile(pdfPath); string text = pdf.ExtractAllText(); var lineItems = new List<InvoiceLineItem>(); string[] lines = text.Split('\n'); foreach (string line in lines) { // Currency symbols indicate potential line items with amounts if (line.Contains("$") || line.Contains("€")) {Console.WriteLine($"Potential line item: {line.Trim()}"); // Split on whitespace to separate columns // Actual parsing logic depends on your invoice format string[] parts = line.Split(new[] { '\t', ' ' },StringSplitOptions.RemoveEmptyEntries); // Try to find numeric values that could be amounts foreach (string part in parts) { string cleaned = part.Replace("$", "").Replace("€", "").Replace(",", ""); if (decimal.TryParse(cleaned, out decimal amount)) {Console.WriteLine($" Found amount: {amount:C}"); } } } } return lineItems; }}
using IronPdf;
using System;
using System.Collections.Generic;
// Data model for a single invoice line item
public class InvoiceLineItem
{
public string Description { get; set; }
public decimal Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total { get; set; }
}
// Extracts tabular line item data from PDF invoices
// Note: PDFs don't have native table structure, so this uses text parsing
public class InvoiceTableExtractor
{
public List<InvoiceLineItem> ExtractLineItems(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
var lineItems = new List<InvoiceLineItem>();
string[] lines = text.Split('\n');
foreach (string line in lines)
{
// Currency symbols indicate potential line items with amounts
if (line.Contains("$") || line.Contains("€"))
{
Console.WriteLine($"Potential line item: {line.Trim()}");
// Split on whitespace to separate columns
// Actual parsing logic depends on your invoice format
string[] parts = line.Split(new[] { '\t', ' ' },
StringSplitOptions.RemoveEmptyEntries);
// Try to find numeric values that could be amounts
foreach (string part in parts)
{
string cleaned = part.Replace("$", "").Replace("€", "").Replace(",", "");
if (decimal.TryParse(cleaned, out decimal amount))
{
Console.WriteLine($" Found amount: {amount:C}");
}
}
}
}
return lineItems;
}
}
ImportsIronPdfImportsSystemImportsSystem.Collections.Generic' Data model for a single invoice line itemPublic Class InvoiceLineItem Public Property DescriptionAsString Public Property QuantityAsDecimal Public Property UnitPriceAsDecimal Public Property TotalAsDecimalEnd Class' Extracts tabular line item data from PDF invoices' Note: PDFs don't have native table structure, so this uses text parsingPublic Class InvoiceTableExtractor Public Function ExtractLineItems(pdfPath AsString) AsList(OfInvoiceLineItem) Dim pdf = PdfDocument.FromFile(pdfPath) Dim text AsString = pdf.ExtractAllText() Dim lineItems As New List(OfInvoiceLineItem)() Dim lines() AsString = text.Split(ControlChars.Lf) For Each line AsStringIn lines ' Currency symbols indicate potential line items with amounts If line.Contains("$") OrElse line.Contains("€") ThenConsole.WriteLine($"Potential line item: {line.Trim()}") ' Split on whitespace to separate columns ' Actual parsing logic depends on your invoice format Dim parts() AsString = line.Split(New Char() {ControlChars.Tab, " "c}, StringSplitOptions.RemoveEmptyEntries) ' Try to find numeric values that could be amounts For Each part AsStringIn parts Dim cleaned AsString = part.Replace("$", "").Replace("€", "").Replace(",", "") Dim amount AsDecimal IfDecimal.TryParse(cleaned, amount) ThenConsole.WriteLine($" Found amount: {amount:C}") End If Next End If Next Return lineItems End FunctionEnd Class
Imports IronPdf
Imports System
Imports System.Collections.Generic
' Data model for a single invoice line item
Public Class InvoiceLineItem
Public Property Description As String
Public Property Quantity As Decimal
Public Property UnitPrice As Decimal
Public Property Total As Decimal
End Class
' Extracts tabular line item data from PDF invoices
' Note: PDFs don't have native table structure, so this uses text parsing
Public Class InvoiceTableExtractor
Public Function ExtractLineItems(pdfPath As String) As List(Of InvoiceLineItem)
Dim pdf = PdfDocument.FromFile(pdfPath)
Dim text As String = pdf.ExtractAllText()
Dim lineItems As New List(Of InvoiceLineItem)()
Dim lines() As String = text.Split(ControlChars.Lf)
For Each line As String In lines
' Currency symbols indicate potential line items with amounts
If line.Contains("$") OrElse line.Contains("€") Then
Console.WriteLine($"Potential line item: {line.Trim()}")
' Split on whitespace to separate columns
' Actual parsing logic depends on your invoice format
Dim parts() As String = line.Split(New Char() {ControlChars.Tab, " "c}, StringSplitOptions.RemoveEmptyEntries)
' Try to find numeric values that could be amounts
For Each part As String In parts
Dim cleaned As String = part.Replace("$", "").Replace("€", "").Replace(",", "")
Dim amount As Decimal
If Decimal.TryParse(cleaned, amount) Then
Console.WriteLine($" Found amount: {amount:C}")
End If
Next
End If
Next
Return lineItems
End Function
End Class
The parsing logic will vary based on your invoice formats. For invoices with consistent layouts from known vendors, you can build format-specific parsers. For varied formats, consider the AI-powered extraction covered later in this article.
How to Use Pattern Matching for Invoice Numbers, Dates, and Totals
Regular expressions are invaluable for extracting specific data points from invoice text. Key fields like invoice numbers, dates, and totals often follow recognizable patterns:
using IronPdf;using System;using System.Text.RegularExpressions;// Data model for extracted invoice informationpublic class InvoiceData{ public stringInvoiceNumber { get; set; } public stringInvoiceDate { get; set; } public decimalTotalAmount { get; set; } public stringVendorName { get; set; }}// Extracts key invoice fields using regex pattern matching// Multiple patterns handle variations across different vendorspublic class InvoiceParser{ public InvoiceDataParseInvoice(string pdfPath) { var pdf = PdfDocument.FromFile(pdfPath); string text = pdf.ExtractAllText(); var invoiceData = new InvoiceData(); // Try multiple patterns to find invoice number // Handles: "Invoice #123", "INV-123", "Invoice Number: 123", German "Rechnungsnummer" string[] invoiceNumberPatterns = new[] { @"Invoice\s*#?\s*:?\s*([A-Z0-9-]+)", @"INV[-\s]?(\d+)", @"Invoice\s+Number\s*:?\s*([A-Z0-9-]+)", @"Rechnungsnummer\s*:?\s*([A-Z0-9-]+)" }; foreach (string pattern in invoiceNumberPatterns) { var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase); if (match.Success) { invoiceData.InvoiceNumber = match.Groups[1].Value;Console.WriteLine($"Found Invoice Number: {invoiceData.InvoiceNumber}"); break; } } // Date patterns for US, European, and written formats string[] datePatterns = new[] { @"Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", @"Invoice\s+Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", @"(\d{1,2}\.\d{1,2}\.\d{4})", // European: DD.MM.YYYY @"(\w+\s+\d{1,2},?\s+\d{4})" // Written: January 15, 2024 }; foreach (string pattern in datePatterns) { var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase); if (match.Success) { invoiceData.InvoiceDate = match.Groups[1].Value;Console.WriteLine($"Found Date: {invoiceData.InvoiceDate}"); break; } } // Look for total amount with various labels string[] totalPatterns = new[] { @"Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})", @"Amount\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})", @"Grand\s+Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})", @"Balance\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})" }; foreach (string pattern in totalPatterns) { var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase); if (match.Success) { // Remove commas before parsing string amountStr = match.Groups[1].Value.Replace(",", ""); if (decimal.TryParse(amountStr, out decimal amount)) { invoiceData.TotalAmount = amount;Console.WriteLine($"Found Total: ${invoiceData.TotalAmount:F2}"); break; } } } return invoiceData; }}
using IronPdf;
using System;
using System.Text.RegularExpressions;
// Data model for extracted invoice information
public class InvoiceData
{
public string InvoiceNumber { get; set; }
public string InvoiceDate { get; set; }
public decimal TotalAmount { get; set; }
public string VendorName { get; set; }
}
// Extracts key invoice fields using regex pattern matching
// Multiple patterns handle variations across different vendors
public class InvoiceParser
{
public InvoiceData ParseInvoice(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
var invoiceData = new InvoiceData();
// Try multiple patterns to find invoice number
// Handles: "Invoice #123", "INV-123", "Invoice Number: 123", German "Rechnungsnummer"
string[] invoiceNumberPatterns = new[]
{
@"Invoice\s*#?\s*:?\s*([A-Z0-9-]+)",
@"INV[-\s]?(\d+)",
@"Invoice\s+Number\s*:?\s*([A-Z0-9-]+)",
@"Rechnungsnummer\s*:?\s*([A-Z0-9-]+)"
};
foreach (string pattern in invoiceNumberPatterns)
{
var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
invoiceData.InvoiceNumber = match.Groups[1].Value;
Console.WriteLine($"Found Invoice Number: {invoiceData.InvoiceNumber}");
break;
}
}
// Date patterns for US, European, and written formats
string[] datePatterns = new[]
{
@"Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
@"Invoice\s+Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
@"(\d{1,2}\.\d{1,2}\.\d{4})", // European: DD.MM.YYYY
@"(\w+\s+\d{1,2},?\s+\d{4})" // Written: January 15, 2024
};
foreach (string pattern in datePatterns)
{
var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
invoiceData.InvoiceDate = match.Groups[1].Value;
Console.WriteLine($"Found Date: {invoiceData.InvoiceDate}");
break;
}
}
// Look for total amount with various labels
string[] totalPatterns = new[]
{
@"Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
@"Amount\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
@"Grand\s+Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
@"Balance\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})"
};
foreach (string pattern in totalPatterns)
{
var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
// Remove commas before parsing
string amountStr = match.Groups[1].Value.Replace(",", "");
if (decimal.TryParse(amountStr, out decimal amount))
{
invoiceData.TotalAmount = amount;
Console.WriteLine($"Found Total: ${invoiceData.TotalAmount:F2}");
break;
}
}
}
return invoiceData;
}
}
ImportsIronPdfImportsSystemImportsSystem.Text.RegularExpressions' Data model for extracted invoice informationPublic Class InvoiceData Public Property InvoiceNumberAsString Public Property InvoiceDateAsString Public Property TotalAmountAsDecimal Public Property VendorNameAsStringEnd Class' Extracts key invoice fields using regex pattern matching' Multiple patterns handle variations across different vendorsPublic Class InvoiceParser Public Function ParseInvoice(pdfPath AsString) AsInvoiceData Dim pdf = PdfDocument.FromFile(pdfPath) Dim text AsString = pdf.ExtractAllText() Dim invoiceData As New InvoiceData() ' Try multiple patterns to find invoice number ' Handles: "Invoice #123", "INV-123", "Invoice Number: 123", German "Rechnungsnummer" Dim invoiceNumberPatterns AsString() = { "Invoice\s*#?\s*:?\s*([A-Z0-9-]+)", "INV[-\s]?(\d+)", "Invoice\s+Number\s*:?\s*([A-Z0-9-]+)", "Rechnungsnummer\s*:?\s*([A-Z0-9-]+)" } For Each pattern AsStringIn invoiceNumberPatterns Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase) If match.SuccessThen invoiceData.InvoiceNumber = match.Groups(1).ValueConsole.WriteLine($"Found Invoice Number: {invoiceData.InvoiceNumber}") Exit For End If Next ' Date patterns for US, European, and written formats Dim datePatterns AsString() = { "Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", "Invoice\s+Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", "(\d{1,2}\.\d{1,2}\.\d{4})", ' European: DD.MM.YYYY "(\w+\s+\d{1,2},?\s+\d{4})" ' Written: January 15, 2024 } For Each pattern AsStringIn datePatterns Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase) If match.SuccessThen invoiceData.InvoiceDate = match.Groups(1).ValueConsole.WriteLine($"Found Date: {invoiceData.InvoiceDate}") Exit For End If Next ' Look for total amount with various labels Dim totalPatterns AsString() = { "Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})", "Amount\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})", "Grand\s+Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})", "Balance\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})" } For Each pattern AsStringIn totalPatterns Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase) If match.SuccessThen ' Remove commas before parsing Dim amountStr AsString = match.Groups(1).Value.Replace(",", "") Dim amount AsDecimal IfDecimal.TryParse(amountStr, amount) Then invoiceData.TotalAmount = amountConsole.WriteLine($"Found Total: ${invoiceData.TotalAmount:F2}") Exit For End If End If Next Return invoiceData End FunctionEnd Class
Imports IronPdf
Imports System
Imports System.Text.RegularExpressions
' Data model for extracted invoice information
Public Class InvoiceData
Public Property InvoiceNumber As String
Public Property InvoiceDate As String
Public Property TotalAmount As Decimal
Public Property VendorName As String
End Class
' Extracts key invoice fields using regex pattern matching
' Multiple patterns handle variations across different vendors
Public Class InvoiceParser
Public Function ParseInvoice(pdfPath As String) As InvoiceData
Dim pdf = PdfDocument.FromFile(pdfPath)
Dim text As String = pdf.ExtractAllText()
Dim invoiceData As New InvoiceData()
' Try multiple patterns to find invoice number
' Handles: "Invoice #123", "INV-123", "Invoice Number: 123", German "Rechnungsnummer"
Dim invoiceNumberPatterns As String() = {
"Invoice\s*#?\s*:?\s*([A-Z0-9-]+)",
"INV[-\s]?(\d+)",
"Invoice\s+Number\s*:?\s*([A-Z0-9-]+)",
"Rechnungsnummer\s*:?\s*([A-Z0-9-]+)"
}
For Each pattern As String In invoiceNumberPatterns
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success Then
invoiceData.InvoiceNumber = match.Groups(1).Value
Console.WriteLine($"Found Invoice Number: {invoiceData.InvoiceNumber}")
Exit For
End If
Next
' Date patterns for US, European, and written formats
Dim datePatterns As String() = {
"Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
"Invoice\s+Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
"(\d{1,2}\.\d{1,2}\.\d{4})", ' European: DD.MM.YYYY
"(\w+\s+\d{1,2},?\s+\d{4})" ' Written: January 15, 2024
}
For Each pattern As String In datePatterns
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success Then
invoiceData.InvoiceDate = match.Groups(1).Value
Console.WriteLine($"Found Date: {invoiceData.InvoiceDate}")
Exit For
End If
Next
' Look for total amount with various labels
Dim totalPatterns As String() = {
"Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
"Amount\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
"Grand\s+Total\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})",
"Balance\s+Due\s*:?\s*[\$€]?\s*([\d,]+\.\d{2})"
}
For Each pattern As String In totalPatterns
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success Then
' Remove commas before parsing
Dim amountStr As String = match.Groups(1).Value.Replace(",", "")
Dim amount As Decimal
If Decimal.TryParse(amountStr, amount) Then
invoiceData.TotalAmount = amount
Console.WriteLine($"Found Total: ${invoiceData.TotalAmount:F2}")
Exit For
End If
End If
Next
Return invoiceData
End Function
End Class
This pattern-based approach works well for invoices with predictable formats. The multiple pattern variations handle common formatting differences across vendors, such as "Invoice #" and "Invoice Number:"
What about Scanned or Image-Based Invoices?
The text extraction methods shown above work with PDFs that contain embedded text. However, scanned documents and image-based PDFs don't have extractable text. They're essentially pictures of invoices.
Please note: For processing scanned invoices, you'll need OCR (Optical Character Recognition) capabilities. IronOCR, part of the Iron Suite, integrates with IronPDF for these scenarios. Visit https://ironsoftware.com/csharp/ocr/ to learn more about extracting text from scanned documents and images.
How to Use AI to Process Invoices in .NET
Traditional pattern matching works well for standardized invoices, but real-world accounts payable departments receive documents in countless formats. This is where AI-powered extraction shines. Large language models can understand invoice semantics and extract structured data even from unfamiliar layouts.
How to Integrate AI for Invoice Parsing
The pattern for AI-powered invoice processing combines IronPDF's text extraction with LLM API calls. Here's a generic implementation that works with any OpenAI-compatible API:
using IronPdf;using System;using System.Net.Http;using System.Text;using System.Text.Json;using System.Threading.Tasks;// Data model for extracted invoice informationpublic class InvoiceData{ public stringInvoiceNumber { get; set; } public stringInvoiceDate { get; set; } public stringVendorName { get; set; } public decimalTotalAmount { get; set; }}// Leverages AI/LLM APIs to extract structured data from any invoice format// Works with OpenAI or any compatible API endpointpublic class AIInvoiceParser{ private readonly HttpClient _httpClient; private readonly string _apiKey; private readonly string _apiUrl; publicAIInvoiceParser(string apiKey, string apiUrl = "https://api.openai.com/v1/chat/completions") { _apiKey = apiKey; _apiUrl = apiUrl; _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}"); } public async Task<InvoiceData> ParseInvoiceWithAI(string pdfPath) { // First extract raw text from the PDF using IronPDF var pdf = PdfDocument.FromFile(pdfPath); string invoiceText = pdf.ExtractAllText(); // Construct a prompt that instructs the AI to return structured JSON // Being explicit about the format reduces parsing errors string prompt = $@"Extract the following information from this invoice text.Return ONLY valid JSON with no additional text or markdown formatting.Required fields:- InvoiceNumber: The invoice or document number- InvoiceDate: The invoice date in YYYY-MM-DD format- VendorName: The company or person who sent the invoice- TotalAmount: The total amount due as a number (no currency symbols)Invoice text:{invoiceText}JSON response:"; // Build the API request with a system prompt for context var requestBody = new { model = "gpt-4", messages = new[] { new { role = "system", content = "You are an invoice data extraction assistant. Extract structured data from invoices and return valid JSON only." }, new { role = "user", content = prompt } }, temperature = 0.1 // Low temperature ensures consistent, deterministic results }; var json = JsonSerializer.Serialize(requestBody); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(_apiUrl, content); var responseJson = await response.Content.ReadAsStringAsync(); // Navigate the API response structure to get the extracted content using var doc = JsonDocument.Parse(responseJson); var messageContent = doc.RootElement .GetProperty("choices")[0] .GetProperty("message") .GetProperty("content") .GetString();Console.WriteLine("AI Extracted Data:");Console.WriteLine(messageContent); // Deserialize the AI's JSON response into our data class var invoiceData = JsonSerializer.Deserialize<InvoiceData>(messageContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); return invoiceData; }}
using IronPdf;
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
// Data model for extracted invoice information
public class InvoiceData
{
public string InvoiceNumber { get; set; }
public string InvoiceDate { get; set; }
public string VendorName { get; set; }
public decimal TotalAmount { get; set; }
}
// Leverages AI/LLM APIs to extract structured data from any invoice format
// Works with OpenAI or any compatible API endpoint
public class AIInvoiceParser
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _apiUrl;
public AIInvoiceParser(string apiKey, string apiUrl = "https://api.openai.com/v1/chat/completions")
{
_apiKey = apiKey;
_apiUrl = apiUrl;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
}
public async Task<InvoiceData> ParseInvoiceWithAI(string pdfPath)
{
// First extract raw text from the PDF using IronPDF
var pdf = PdfDocument.FromFile(pdfPath);
string invoiceText = pdf.ExtractAllText();
// Construct a prompt that instructs the AI to return structured JSON
// Being explicit about the format reduces parsing errors
string prompt = $@"Extract the following information from this invoice text.
Return ONLY valid JSON with no additional text or markdown formatting.
Required fields:
- InvoiceNumber: The invoice or document number
- InvoiceDate: The invoice date in YYYY-MM-DD format
- VendorName: The company or person who sent the invoice
- TotalAmount: The total amount due as a number (no currency symbols)
Invoice text:
{invoiceText}
JSON response:";
// Build the API request with a system prompt for context
var requestBody = new
{
model = "gpt-4",
messages = new[]
{
new {
role = "system",
content = "You are an invoice data extraction assistant. Extract structured data from invoices and return valid JSON only."
},
new { role = "user", content = prompt }
},
temperature = 0.1 // Low temperature ensures consistent, deterministic results
};
var json = JsonSerializer.Serialize(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(_apiUrl, content);
var responseJson = await response.Content.ReadAsStringAsync();
// Navigate the API response structure to get the extracted content
using var doc = JsonDocument.Parse(responseJson);
var messageContent = doc.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString();
Console.WriteLine("AI Extracted Data:");
Console.WriteLine(messageContent);
// Deserialize the AI's JSON response into our data class
var invoiceData = JsonSerializer.Deserialize<InvoiceData>(messageContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
return invoiceData;
}
}
ImportsIronPdfImportsSystemImportsSystem.Net.HttpImportsSystem.TextImportsSystem.Text.JsonImportsSystem.Threading.Tasks' Data model for extracted invoice informationPublic Class InvoiceData Public Property InvoiceNumberAsString Public Property InvoiceDateAsString Public Property VendorNameAsString Public Property TotalAmountAsDecimalEnd Class' Leverages AI/LLM APIs to extract structured data from any invoice format' Works with OpenAI or any compatible API endpointPublic Class AIInvoiceParser PrivateReadOnly _httpClient AsHttpClient PrivateReadOnly _apiKey AsString PrivateReadOnly _apiUrl AsString Public Sub New(apiKey AsString, Optional apiUrl AsString = "https://api.openai.com/v1/chat/completions") _apiKey = apiKey _apiUrl = apiUrl _httpClient = New HttpClient() _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}") End Sub PublicAsync Function ParseInvoiceWithAI(pdfPath AsString) AsTask(OfInvoiceData) ' First extract raw text from the PDF using IronPDF Dim pdf = PdfDocument.FromFile(pdfPath) Dim invoiceText AsString = pdf.ExtractAllText() ' Construct a prompt that instructs the AI to return structured JSON ' Being explicit about the format reduces parsing errors Dim prompt AsString = $"Extract the following information from this invoice text.Return ONLY valid JSON with no additional text or markdown formatting.Required fields:- InvoiceNumber: The invoice or document number- InvoiceDate: The invoice date in YYYY-MM-DD format- VendorName: The company or person who sent the invoice- TotalAmount: The total amount due as a number (no currency symbols)Invoice text:{invoiceText}JSON response:" ' Build the API request with a system prompt for context Dim requestBody = New With { .model = "gpt-4", .messages = New Object() { New With { .role = "system", .content = "You are an invoice data extraction assistant. Extract structured data from invoices and return valid JSON only." }, New With { .role = "user", .content = prompt } }, .temperature = 0.1 ' Low temperature ensures consistent, deterministic results } Dim json AsString = JsonSerializer.Serialize(requestBody) Dim content As New StringContent(json, Encoding.UTF8, "application/json") Dim response = Await _httpClient.PostAsync(_apiUrl, content) Dim responseJson AsString = Awaitresponse.Content.ReadAsStringAsync() ' Navigate the API response structure to get the extracted contentUsing doc = JsonDocument.Parse(responseJson) Dim messageContent AsString = doc.RootElement _ .GetProperty("choices")(0) _ .GetProperty("message") _ .GetProperty("content") _ .GetString()Console.WriteLine("AI Extracted Data:")Console.WriteLine(messageContent) ' Deserialize the AI's JSON response into our data class Dim invoiceData AsInvoiceData = JsonSerializer.Deserialize(OfInvoiceData)(messageContent, New JsonSerializerOptionsWith {.PropertyNameCaseInsensitive = True}) Return invoiceDataEndUsing End FunctionEnd Class
Imports IronPdf
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading.Tasks
' Data model for extracted invoice information
Public Class InvoiceData
Public Property InvoiceNumber As String
Public Property InvoiceDate As String
Public Property VendorName As String
Public Property TotalAmount As Decimal
End Class
' Leverages AI/LLM APIs to extract structured data from any invoice format
' Works with OpenAI or any compatible API endpoint
Public Class AIInvoiceParser
Private ReadOnly _httpClient As HttpClient
Private ReadOnly _apiKey As String
Private ReadOnly _apiUrl As String
Public Sub New(apiKey As String, Optional apiUrl As String = "https://api.openai.com/v1/chat/completions")
_apiKey = apiKey
_apiUrl = apiUrl
_httpClient = New HttpClient()
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}")
End Sub
Public Async Function ParseInvoiceWithAI(pdfPath As String) As Task(Of InvoiceData)
' First extract raw text from the PDF using IronPDF
Dim pdf = PdfDocument.FromFile(pdfPath)
Dim invoiceText As String = pdf.ExtractAllText()
' Construct a prompt that instructs the AI to return structured JSON
' Being explicit about the format reduces parsing errors
Dim prompt As String = $"Extract the following information from this invoice text.
Return ONLY valid JSON with no additional text or markdown formatting.
Required fields:
- InvoiceNumber: The invoice or document number
- InvoiceDate: The invoice date in YYYY-MM-DD format
- VendorName: The company or person who sent the invoice
- TotalAmount: The total amount due as a number (no currency symbols)
Invoice text:
{invoiceText}
JSON response:"
' Build the API request with a system prompt for context
Dim requestBody = New With {
.model = "gpt-4",
.messages = New Object() {
New With {
.role = "system",
.content = "You are an invoice data extraction assistant. Extract structured data from invoices and return valid JSON only."
},
New With {
.role = "user",
.content = prompt
}
},
.temperature = 0.1 ' Low temperature ensures consistent, deterministic results
}
Dim json As String = JsonSerializer.Serialize(requestBody)
Dim content As New StringContent(json, Encoding.UTF8, "application/json")
Dim response = Await _httpClient.PostAsync(_apiUrl, content)
Dim responseJson As String = Await response.Content.ReadAsStringAsync()
' Navigate the API response structure to get the extracted content
Using doc = JsonDocument.Parse(responseJson)
Dim messageContent As String = doc.RootElement _
.GetProperty("choices")(0) _
.GetProperty("message") _
.GetProperty("content") _
.GetString()
Console.WriteLine("AI Extracted Data:")
Console.WriteLine(messageContent)
' Deserialize the AI's JSON response into our data class
Dim invoiceData As InvoiceData = JsonSerializer.Deserialize(Of InvoiceData)(messageContent, New JsonSerializerOptions With {.PropertyNameCaseInsensitive = True})
Return invoiceData
End Using
End Function
End Class
The low temperature setting (0.1) encourages deterministic outputs, which is important for data extraction tasks where you want consistent results for the same input.
How to Extract Structured JSON Data from Invoices
For more complex invoices with line items, vendor details, and customer information, you can request a richer JSON structure:
using IronPdf;using System;using System.Collections.Generic;using System.Text.Json;using System.Threading.Tasks;// Comprehensive invoice data model with all detailspublic class DetailedInvoiceData{ public stringInvoiceNumber { get; set; } public DateTimeInvoiceDate { get; set; } public DateTimeDueDate { get; set; } public VendorInfoVendor { get; set; } public CustomerInfoCustomer { get; set; } public List<LineItem> LineItems { get; set; } public decimalSubtotal { get; set; } public decimalTax { get; set; } public decimalTotal { get; set; }}public class VendorInfo{ public stringName { get; set; } public stringAddress { get; set; } public stringTaxId { get; set; }}public class CustomerInfo{ public stringName { get; set; } public stringAddress { get; set; }}public class LineItem{ public stringDescription { get; set; } public decimalQuantity { get; set; } public decimalUnitPrice { get; set; } public decimalTotal { get; set; }}// Extracts comprehensive invoice data including line items and party detailspublic class StructuredInvoiceExtractor{ private readonly AIInvoiceParser _aiParser; publicStructuredInvoiceExtractor(string apiKey) { _aiParser = new AIInvoiceParser(apiKey); } public async Task<DetailedInvoiceData> ExtractDetailedData(string pdfPath) { var pdf = PdfDocument.FromFile(pdfPath); string text = pdf.ExtractAllText(); // Define the exact JSON structure we want the AI to return // This schema guides the AI to extract all relevant fields string jsonSchema = @"{ ""InvoiceNumber"": ""string"", ""InvoiceDate"": ""YYYY-MM-DD"", ""DueDate"": ""YYYY-MM-DD"", ""Vendor"": { ""Name"": ""string"", ""Address"": ""string"", ""TaxId"": ""string or null"" }, ""Customer"": { ""Name"": ""string"", ""Address"": ""string"" }, ""LineItems"": [ { ""Description"": ""string"", ""Quantity"": 0.0, ""UnitPrice"": 0.00, ""Total"": 0.00 } ], ""Subtotal"": 0.00, ""Tax"": 0.00, ""Total"": 0.00}"; // Prompt includes both the schema and the extracted text string prompt = $@"Extract all invoice data and return it in this exact JSON structure:{jsonSchema}Invoice text:{text}Return only valid JSON, no markdown formatting or additional text."; // Call AI API and parse response (implementation as shown above) // Return deserialized DetailedInvoiceData return new DetailedInvoiceData(); // Placeholder }}
using IronPdf;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
// Comprehensive invoice data model with all details
public class DetailedInvoiceData
{
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public DateTime DueDate { get; set; }
public VendorInfo Vendor { get; set; }
public CustomerInfo Customer { get; set; }
public List<LineItem> LineItems { get; set; }
public decimal Subtotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
}
public class VendorInfo
{
public string Name { get; set; }
public string Address { get; set; }
public string TaxId { get; set; }
}
public class CustomerInfo
{
public string Name { get; set; }
public string Address { get; set; }
}
public class LineItem
{
public string Description { get; set; }
public decimal Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total { get; set; }
}
// Extracts comprehensive invoice data including line items and party details
public class StructuredInvoiceExtractor
{
private readonly AIInvoiceParser _aiParser;
public StructuredInvoiceExtractor(string apiKey)
{
_aiParser = new AIInvoiceParser(apiKey);
}
public async Task<DetailedInvoiceData> ExtractDetailedData(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
// Define the exact JSON structure we want the AI to return
// This schema guides the AI to extract all relevant fields
string jsonSchema = @"{
""InvoiceNumber"": ""string"",
""InvoiceDate"": ""YYYY-MM-DD"",
""DueDate"": ""YYYY-MM-DD"",
""Vendor"": {
""Name"": ""string"",
""Address"": ""string"",
""TaxId"": ""string or null""
},
""Customer"": {
""Name"": ""string"",
""Address"": ""string""
},
""LineItems"": [
{
""Description"": ""string"",
""Quantity"": 0.0,
""UnitPrice"": 0.00,
""Total"": 0.00
}
],
""Subtotal"": 0.00,
""Tax"": 0.00,
""Total"": 0.00
}";
// Prompt includes both the schema and the extracted text
string prompt = $@"Extract all invoice data and return it in this exact JSON structure:
{jsonSchema}
Invoice text:
{text}
Return only valid JSON, no markdown formatting or additional text.";
// Call AI API and parse response (implementation as shown above)
// Return deserialized DetailedInvoiceData
return new DetailedInvoiceData(); // Placeholder
}
}
ImportsIronPdfImportsSystemImportsSystem.Collections.GenericImportsSystem.Text.JsonImportsSystem.Threading.Tasks' Comprehensive invoice data model with all detailsPublic Class DetailedInvoiceData Public Property InvoiceNumberAsString Public Property InvoiceDateAsDateTime Public Property DueDateAsDateTime Public Property VendorAsVendorInfo Public Property CustomerAsCustomerInfo Public Property LineItemsAsList(OfLineItem) Public Property SubtotalAsDecimal Public Property TaxAsDecimal Public Property TotalAsDecimalEnd ClassPublic Class VendorInfo Public Property NameAsString Public Property AddressAsString Public Property TaxIdAsStringEnd ClassPublic Class CustomerInfo Public Property NameAsString Public Property AddressAsStringEnd ClassPublic Class LineItem Public Property DescriptionAsString Public Property QuantityAsDecimal Public Property UnitPriceAsDecimal Public Property TotalAsDecimalEnd Class' Extracts comprehensive invoice data including line items and party detailsPublic Class StructuredInvoiceExtractor PrivateReadOnly _aiParser AsAIInvoiceParser Public Sub New(apiKey AsString) _aiParser = New AIInvoiceParser(apiKey) End Sub PublicAsync Function ExtractDetailedData(pdfPath AsString) AsTask(OfDetailedInvoiceData) Dim pdf = PdfDocument.FromFile(pdfPath) Dim text AsString = pdf.ExtractAllText() ' Define the exact JSON structure we want the AI to return ' This schema guides the AI to extract all relevant fields Dim jsonSchema AsString = "{ ""InvoiceNumber"": ""string"", ""InvoiceDate"": ""YYYY-MM-DD"", ""DueDate"": ""YYYY-MM-DD"", ""Vendor"": { ""Name"": ""string"", ""Address"": ""string"", ""TaxId"": ""string or null"" }, ""Customer"": { ""Name"": ""string"", ""Address"": ""string"" }, ""LineItems"": [ { ""Description"": ""string"", ""Quantity"": 0.0, ""UnitPrice"": 0.00, ""Total"": 0.00 } ], ""Subtotal"": 0.00, ""Tax"": 0.00, ""Total"": 0.00}" ' Prompt includes both the schema and the extracted text Dim prompt AsString = $"Extract all invoice data and return it in this exact JSON structure:{jsonSchema}Invoice text:{text}Return only valid JSON, no markdown formatting or additional text." ' Call AI API and parse response (implementation as shown above) ' Return deserialized DetailedInvoiceData Return New DetailedInvoiceData() ' Placeholder End FunctionEnd Class
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Text.Json
Imports System.Threading.Tasks
' Comprehensive invoice data model with all details
Public Class DetailedInvoiceData
Public Property InvoiceNumber As String
Public Property InvoiceDate As DateTime
Public Property DueDate As DateTime
Public Property Vendor As VendorInfo
Public Property Customer As CustomerInfo
Public Property LineItems As List(Of LineItem)
Public Property Subtotal As Decimal
Public Property Tax As Decimal
Public Property Total As Decimal
End Class
Public Class VendorInfo
Public Property Name As String
Public Property Address As String
Public Property TaxId As String
End Class
Public Class CustomerInfo
Public Property Name As String
Public Property Address As String
End Class
Public Class LineItem
Public Property Description As String
Public Property Quantity As Decimal
Public Property UnitPrice As Decimal
Public Property Total As Decimal
End Class
' Extracts comprehensive invoice data including line items and party details
Public Class StructuredInvoiceExtractor
Private ReadOnly _aiParser As AIInvoiceParser
Public Sub New(apiKey As String)
_aiParser = New AIInvoiceParser(apiKey)
End Sub
Public Async Function ExtractDetailedData(pdfPath As String) As Task(Of DetailedInvoiceData)
Dim pdf = PdfDocument.FromFile(pdfPath)
Dim text As String = pdf.ExtractAllText()
' Define the exact JSON structure we want the AI to return
' This schema guides the AI to extract all relevant fields
Dim jsonSchema As String = "{
""InvoiceNumber"": ""string"",
""InvoiceDate"": ""YYYY-MM-DD"",
""DueDate"": ""YYYY-MM-DD"",
""Vendor"": {
""Name"": ""string"",
""Address"": ""string"",
""TaxId"": ""string or null""
},
""Customer"": {
""Name"": ""string"",
""Address"": ""string""
},
""LineItems"": [
{
""Description"": ""string"",
""Quantity"": 0.0,
""UnitPrice"": 0.00,
""Total"": 0.00
}
],
""Subtotal"": 0.00,
""Tax"": 0.00,
""Total"": 0.00
}"
' Prompt includes both the schema and the extracted text
Dim prompt As String = $"
Extract all invoice data and return it in this exact JSON structure:
{jsonSchema}
Invoice text:
{text}
Return only valid JSON, no markdown formatting or additional text."
' Call AI API and parse response (implementation as shown above)
' Return deserialized DetailedInvoiceData
Return New DetailedInvoiceData() ' Placeholder
End Function
End Class
How to Handle Inconsistent Invoice Formats
The real power of AI extraction emerges when processing invoices from multiple vendors, each with unique formats. A smart processor can attempt pattern-based extraction first (faster and free) and fall back to AI only when needed:
using IronPdf;using System.Threading.Tasks;// Hybrid processor that optimizes for cost and capability// Tries fast regex patterns first, uses AI only when patterns failpublic class SmartInvoiceProcessor{ private readonly AIInvoiceParser _aiParser; publicSmartInvoiceProcessor(string aiApiKey) { _aiParser = new AIInvoiceParser(aiApiKey); } public async Task<InvoiceData> ProcessAnyInvoice(string pdfPath) { var pdf = PdfDocument.FromFile(pdfPath); string text = pdf.ExtractAllText(); // First attempt: regex patterns (fast and free) var patternParser = new InvoiceParser(); var standardResult = patternParser.ParseInvoiceFromText(text); // If pattern matching found all required fields, use that result if (IsComplete(standardResult)) {Console.WriteLine("Pattern extraction successful"); return standardResult; } // Fallback: use AI for complex or unusual invoice formats // This costs money but handles any layoutConsole.WriteLine("Using AI extraction for complex invoice format"); var aiResult = await _aiParser.ParseInvoiceWithAI(pdfPath); return aiResult; } // Validates that we have the minimum required fields private boolIsComplete(InvoiceData data) { return !string.IsNullOrEmpty(data.InvoiceNumber) && !string.IsNullOrEmpty(data.InvoiceDate) && data.TotalAmount > 0; }}
using IronPdf;
using System.Threading.Tasks;
// Hybrid processor that optimizes for cost and capability
// Tries fast regex patterns first, uses AI only when patterns fail
public class SmartInvoiceProcessor
{
private readonly AIInvoiceParser _aiParser;
public SmartInvoiceProcessor(string aiApiKey)
{
_aiParser = new AIInvoiceParser(aiApiKey);
}
public async Task<InvoiceData> ProcessAnyInvoice(string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
string text = pdf.ExtractAllText();
// First attempt: regex patterns (fast and free)
var patternParser = new InvoiceParser();
var standardResult = patternParser.ParseInvoiceFromText(text);
// If pattern matching found all required fields, use that result
if (IsComplete(standardResult))
{
Console.WriteLine("Pattern extraction successful");
return standardResult;
}
// Fallback: use AI for complex or unusual invoice formats
// This costs money but handles any layout
Console.WriteLine("Using AI extraction for complex invoice format");
var aiResult = await _aiParser.ParseInvoiceWithAI(pdfPath);
return aiResult;
}
// Validates that we have the minimum required fields
private bool IsComplete(InvoiceData data)
{
return !string.IsNullOrEmpty(data.InvoiceNumber) &&
!string.IsNullOrEmpty(data.InvoiceDate) &&
data.TotalAmount > 0;
}
}
ImportsIronPdfImportsSystem.Threading.Tasks' Hybrid processor that optimizes for cost and capability' Tries fast regex patterns first, uses AI only when patterns failPublic Class SmartInvoiceProcessor PrivateReadOnly _aiParser AsAIInvoiceParser Public Sub New(aiApiKey AsString) _aiParser = New AIInvoiceParser(aiApiKey) End Sub PublicAsync Function ProcessAnyInvoice(pdfPath AsString) AsTask(OfInvoiceData) Dim pdf = PdfDocument.FromFile(pdfPath) Dim text AsString = pdf.ExtractAllText() ' First attempt: regex patterns (fast and free) Dim patternParser = New InvoiceParser() Dim standardResult = patternParser.ParseInvoiceFromText(text) ' If pattern matching found all required fields, use that result IfIsComplete(standardResult) ThenConsole.WriteLine("Pattern extraction successful") Return standardResult End If ' Fallback: use AI for complex or unusual invoice formats ' This costs money but handles any layoutConsole.WriteLine("Using AI extraction for complex invoice format") Dim aiResult = Await _aiParser.ParseInvoiceWithAI(pdfPath) Return aiResult End Function ' Validates that we have the minimum required fields Private Function IsComplete(data AsInvoiceData) AsBoolean ReturnNotString.IsNullOrEmpty(data.InvoiceNumber) AndAlsoNotString.IsNullOrEmpty(data.InvoiceDate) AndAlso data.TotalAmount > 0 End FunctionEnd Class
Imports IronPdf
Imports System.Threading.Tasks
' Hybrid processor that optimizes for cost and capability
' Tries fast regex patterns first, uses AI only when patterns fail
Public Class SmartInvoiceProcessor
Private ReadOnly _aiParser As AIInvoiceParser
Public Sub New(aiApiKey As String)
_aiParser = New AIInvoiceParser(aiApiKey)
End Sub
Public Async Function ProcessAnyInvoice(pdfPath As String) As Task(Of InvoiceData)
Dim pdf = PdfDocument.FromFile(pdfPath)
Dim text As String = pdf.ExtractAllText()
' First attempt: regex patterns (fast and free)
Dim patternParser = New InvoiceParser()
Dim standardResult = patternParser.ParseInvoiceFromText(text)
' If pattern matching found all required fields, use that result
If IsComplete(standardResult) Then
Console.WriteLine("Pattern extraction successful")
Return standardResult
End If
' Fallback: use AI for complex or unusual invoice formats
' This costs money but handles any layout
Console.WriteLine("Using AI extraction for complex invoice format")
Dim aiResult = Await _aiParser.ParseInvoiceWithAI(pdfPath)
Return aiResult
End Function
' Validates that we have the minimum required fields
Private Function IsComplete(data As InvoiceData) As Boolean
Return Not String.IsNullOrEmpty(data.InvoiceNumber) AndAlso
Not String.IsNullOrEmpty(data.InvoiceDate) AndAlso
data.TotalAmount > 0
End Function
End Class
How to Build an Accounts Payable Automation Pipeline
Bringing all these pieces together, here's a complete automation pipeline that processes incoming invoices, extracts data, validates it, and prepares it for your accounting system:
using IronPdf;using System;using System.IO;using System.Threading.Tasks;using System.Collections.Generic;using System.Linq;// Tracks the outcome of processing each invoicepublic class ProcessingResult{ public stringFileName { get; set; } public boolSuccess { get; set; } public stringInvoiceNumber { get; set; } public stringErrorMessage { get; set; }}// Complete automation pipeline for accounts payable// Watches a folder, extracts data, validates, and routes to accounting systempublic class InvoiceAutomationPipeline{ private readonly SmartInvoiceProcessor _processor; private readonly string _inputFolder; private readonly string _processedFolder; private readonly string _errorFolder; publicInvoiceAutomationPipeline(string apiKey, string inputFolder) { _processor = new SmartInvoiceProcessor(apiKey); _inputFolder = inputFolder; _processedFolder = Path.Combine(inputFolder, "processed"); _errorFolder = Path.Combine(inputFolder, "errors"); // Create output directories if they don't existDirectory.CreateDirectory(_processedFolder);Directory.CreateDirectory(_errorFolder); } // Main entry point - processes all PDFs in the input folder public async Task<List<ProcessingResult>> ProcessInvoiceBatch() { string[] invoiceFiles = Directory.GetFiles(_inputFolder, "*.pdf");Console.WriteLine($"Found {invoiceFiles.Length} invoices to process"); var results = new List<ProcessingResult>(); foreach (string invoicePath in invoiceFiles) { string fileName = Path.GetFileName(invoicePath); try {Console.WriteLine($"Processing: {fileName}"); // Extract data using smart processor (patterns first, then AI) var invoiceData = await _processor.ProcessAnyInvoice(invoicePath); // Ensure we have minimum required fields before proceeding if (ValidateInvoiceData(invoiceData)) { // Send to accounting system (QuickBooks, Xero, etc.) awaitSaveToAccountingSystem(invoiceData); // Archive successful invoices string destPath = Path.Combine(_processedFolder, fileName);File.Move(invoicePath, destPath, overwrite: true); results.Add(new ProcessingResult {FileName = fileName,Success = true,InvoiceNumber = invoiceData.InvoiceNumber });Console.WriteLine($"✓ Processed: {invoiceData.InvoiceNumber}"); } else { throw new Exception("Validation failed - missing required fields"); } } catch (Exception ex) {Console.WriteLine($"✗ Failed: {fileName} - {ex.Message}"); // Quarantine failed invoices for manual review string destPath = Path.Combine(_errorFolder, fileName);File.Move(invoicePath, destPath, overwrite: true); results.Add(new ProcessingResult {FileName = fileName,Success = false,ErrorMessage = ex.Message }); } }GenerateReport(results); return results; } // Checks for minimum required fields private boolValidateInvoiceData(InvoiceData data) { return !string.IsNullOrEmpty(data.InvoiceNumber) && !string.IsNullOrEmpty(data.VendorName) && data.TotalAmount > 0; } // Placeholder for accounting system integration private async TaskSaveToAccountingSystem(InvoiceData data) { // Integrate with your accounting system here // Examples: QuickBooks API, Xero API, SAP, or database storageConsole.WriteLine($" Saved invoice {data.InvoiceNumber} to accounting system"); awaitTask.CompletedTask; } // Outputs a summary of the batch processing results private voidGenerateReport(List<ProcessingResult> results) { int successful = results.Count(r => r.Success); int failed = results.Count(r => !r.Success);Console.WriteLine($"\n========== Processing Complete ==========");Console.WriteLine($"Total Processed: {results.Count}");Console.WriteLine($"Successful: {successful}");Console.WriteLine($"Failed: {failed}"); if (failed > 0) {Console.WriteLine("\nFailed invoices requiring review:"); foreach (var failure in results.Where(r => !r.Success)) {Console.WriteLine($" • {failure.FileName}: {failure.ErrorMessage}"); } } }}
using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
// Tracks the outcome of processing each invoice
public class ProcessingResult
{
public string FileName { get; set; }
public bool Success { get; set; }
public string InvoiceNumber { get; set; }
public string ErrorMessage { get; set; }
}
// Complete automation pipeline for accounts payable
// Watches a folder, extracts data, validates, and routes to accounting system
public class InvoiceAutomationPipeline
{
private readonly SmartInvoiceProcessor _processor;
private readonly string _inputFolder;
private readonly string _processedFolder;
private readonly string _errorFolder;
public InvoiceAutomationPipeline(string apiKey, string inputFolder)
{
_processor = new SmartInvoiceProcessor(apiKey);
_inputFolder = inputFolder;
_processedFolder = Path.Combine(inputFolder, "processed");
_errorFolder = Path.Combine(inputFolder, "errors");
// Create output directories if they don't exist
Directory.CreateDirectory(_processedFolder);
Directory.CreateDirectory(_errorFolder);
}
// Main entry point - processes all PDFs in the input folder
public async Task<List<ProcessingResult>> ProcessInvoiceBatch()
{
string[] invoiceFiles = Directory.GetFiles(_inputFolder, "*.pdf");
Console.WriteLine($"Found {invoiceFiles.Length} invoices to process");
var results = new List<ProcessingResult>();
foreach (string invoicePath in invoiceFiles)
{
string fileName = Path.GetFileName(invoicePath);
try
{
Console.WriteLine($"Processing: {fileName}");
// Extract data using smart processor (patterns first, then AI)
var invoiceData = await _processor.ProcessAnyInvoice(invoicePath);
// Ensure we have minimum required fields before proceeding
if (ValidateInvoiceData(invoiceData))
{
// Send to accounting system (QuickBooks, Xero, etc.)
await SaveToAccountingSystem(invoiceData);
// Archive successful invoices
string destPath = Path.Combine(_processedFolder, fileName);
File.Move(invoicePath, destPath, overwrite: true);
results.Add(new ProcessingResult
{
FileName = fileName,
Success = true,
InvoiceNumber = invoiceData.InvoiceNumber
});
Console.WriteLine($"✓ Processed: {invoiceData.InvoiceNumber}");
}
else
{
throw new Exception("Validation failed - missing required fields");
}
}
catch (Exception ex)
{
Console.WriteLine($"✗ Failed: {fileName} - {ex.Message}");
// Quarantine failed invoices for manual review
string destPath = Path.Combine(_errorFolder, fileName);
File.Move(invoicePath, destPath, overwrite: true);
results.Add(new ProcessingResult
{
FileName = fileName,
Success = false,
ErrorMessage = ex.Message
});
}
}
GenerateReport(results);
return results;
}
// Checks for minimum required fields
private bool ValidateInvoiceData(InvoiceData data)
{
return !string.IsNullOrEmpty(data.InvoiceNumber) &&
!string.IsNullOrEmpty(data.VendorName) &&
data.TotalAmount > 0;
}
// Placeholder for accounting system integration
private async Task SaveToAccountingSystem(InvoiceData data)
{
// Integrate with your accounting system here
// Examples: QuickBooks API, Xero API, SAP, or database storage
Console.WriteLine($" Saved invoice {data.InvoiceNumber} to accounting system");
await Task.CompletedTask;
}
// Outputs a summary of the batch processing results
private void GenerateReport(List<ProcessingResult> results)
{
int successful = results.Count(r => r.Success);
int failed = results.Count(r => !r.Success);
Console.WriteLine($"\n========== Processing Complete ==========");
Console.WriteLine($"Total Processed: {results.Count}");
Console.WriteLine($"Successful: {successful}");
Console.WriteLine($"Failed: {failed}");
if (failed > 0)
{
Console.WriteLine("\nFailed invoices requiring review:");
foreach (var failure in results.Where(r => !r.Success))
{
Console.WriteLine($" • {failure.FileName}: {failure.ErrorMessage}");
}
}
}
}
ImportsIronPdfImportsSystemImportsSystem.IOImportsSystem.Threading.TasksImportsSystem.Collections.GenericImportsSystem.Linq' Tracks the outcome of processing each invoicePublic Class ProcessingResult Public Property FileNameAsString Public Property SuccessAsBoolean Public Property InvoiceNumberAsString Public Property ErrorMessageAsStringEnd Class' Complete automation pipeline for accounts payable' Watches a folder, extracts data, validates, and routes to accounting systemPublic Class InvoiceAutomationPipeline PrivateReadOnly _processor AsSmartInvoiceProcessor PrivateReadOnly _inputFolder AsString PrivateReadOnly _processedFolder AsString PrivateReadOnly _errorFolder AsString Public Sub New(apiKey AsString, inputFolder AsString) _processor = New SmartInvoiceProcessor(apiKey) _inputFolder = inputFolder _processedFolder = Path.Combine(inputFolder, "processed") _errorFolder = Path.Combine(inputFolder, "errors") ' Create output directories if they don't existDirectory.CreateDirectory(_processedFolder)Directory.CreateDirectory(_errorFolder) End Sub ' Main entry point - processes all PDFs in the input folder PublicAsync Function ProcessInvoiceBatch() AsTask(OfList(OfProcessingResult)) Dim invoiceFiles AsString() = Directory.GetFiles(_inputFolder, "*.pdf")Console.WriteLine($"Found {invoiceFiles.Length} invoices to process") Dim results As New List(OfProcessingResult)() For Each invoicePath AsStringIn invoiceFiles Dim fileName AsString = Path.GetFileName(invoicePath)TryConsole.WriteLine($"Processing: {fileName}") ' Extract data using smart processor (patterns first, then AI) Dim invoiceData = Await _processor.ProcessAnyInvoice(invoicePath) ' Ensure we have minimum required fields before proceeding IfValidateInvoiceData(invoiceData) Then ' Send to accounting system (QuickBooks, Xero, etc.)AwaitSaveToAccountingSystem(invoiceData) ' Archive successful invoices Dim destPath AsString = Path.Combine(_processedFolder, fileName)File.Move(invoicePath, destPath, overwrite:=True) results.Add(New ProcessingResultWith { .FileName = fileName, .Success = True, .InvoiceNumber = invoiceData.InvoiceNumber })Console.WriteLine($"✓ Processed: {invoiceData.InvoiceNumber}") ElseThrow New Exception("Validation failed - missing required fields") End IfCatch ex AsExceptionConsole.WriteLine($"✗ Failed: {fileName} - {ex.Message}") ' Quarantine failed invoices for manual review Dim destPath AsString = Path.Combine(_errorFolder, fileName)File.Move(invoicePath, destPath, overwrite:=True) results.Add(New ProcessingResultWith { .FileName = fileName, .Success = False, .ErrorMessage = ex.Message })EndTry NextGenerateReport(results) Return results End Function ' Checks for minimum required fields Private Function ValidateInvoiceData(data AsInvoiceData) AsBoolean ReturnNotString.IsNullOrEmpty(data.InvoiceNumber) AndAlsoNotString.IsNullOrEmpty(data.VendorName) AndAlso data.TotalAmount > 0 End Function ' Placeholder for accounting system integration PrivateAsync Function SaveToAccountingSystem(data AsInvoiceData) AsTask ' Integrate with your accounting system here ' Examples: QuickBooks API, Xero API, SAP, or database storageConsole.WriteLine($" Saved invoice {data.InvoiceNumber} to accounting system")AwaitTask.CompletedTask End Function ' Outputs a summary of the batch processing results Private Sub GenerateReport(results AsList(OfProcessingResult)) Dim successful AsInteger = results.Count(Function(r) r.Success) Dim failed AsInteger = results.Count(Function(r) Not r.Success)Console.WriteLine(vbCrLf & "========== Processing Complete ==========")Console.WriteLine($"Total Processed: {results.Count}")Console.WriteLine($"Successful: {successful}")Console.WriteLine($"Failed: {failed}") If failed > 0 ThenConsole.WriteLine(vbCrLf & "Failed invoices requiring review:") For Each failure In results.Where(Function(r) Not r.Success)Console.WriteLine($" • {failure.FileName}: {failure.ErrorMessage}") Next End If End SubEnd Class
Imports IronPdf
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports System.Linq
' Tracks the outcome of processing each invoice
Public Class ProcessingResult
Public Property FileName As String
Public Property Success As Boolean
Public Property InvoiceNumber As String
Public Property ErrorMessage As String
End Class
' Complete automation pipeline for accounts payable
' Watches a folder, extracts data, validates, and routes to accounting system
Public Class InvoiceAutomationPipeline
Private ReadOnly _processor As SmartInvoiceProcessor
Private ReadOnly _inputFolder As String
Private ReadOnly _processedFolder As String
Private ReadOnly _errorFolder As String
Public Sub New(apiKey As String, inputFolder As String)
_processor = New SmartInvoiceProcessor(apiKey)
_inputFolder = inputFolder
_processedFolder = Path.Combine(inputFolder, "processed")
_errorFolder = Path.Combine(inputFolder, "errors")
' Create output directories if they don't exist
Directory.CreateDirectory(_processedFolder)
Directory.CreateDirectory(_errorFolder)
End Sub
' Main entry point - processes all PDFs in the input folder
Public Async Function ProcessInvoiceBatch() As Task(Of List(Of ProcessingResult))
Dim invoiceFiles As String() = Directory.GetFiles(_inputFolder, "*.pdf")
Console.WriteLine($"Found {invoiceFiles.Length} invoices to process")
Dim results As New List(Of ProcessingResult)()
For Each invoicePath As String In invoiceFiles
Dim fileName As String = Path.GetFileName(invoicePath)
Try
Console.WriteLine($"Processing: {fileName}")
' Extract data using smart processor (patterns first, then AI)
Dim invoiceData = Await _processor.ProcessAnyInvoice(invoicePath)
' Ensure we have minimum required fields before proceeding
If ValidateInvoiceData(invoiceData) Then
' Send to accounting system (QuickBooks, Xero, etc.)
Await SaveToAccountingSystem(invoiceData)
' Archive successful invoices
Dim destPath As String = Path.Combine(_processedFolder, fileName)
File.Move(invoicePath, destPath, overwrite:=True)
results.Add(New ProcessingResult With {
.FileName = fileName,
.Success = True,
.InvoiceNumber = invoiceData.InvoiceNumber
})
Console.WriteLine($"✓ Processed: {invoiceData.InvoiceNumber}")
Else
Throw New Exception("Validation failed - missing required fields")
End If
Catch ex As Exception
Console.WriteLine($"✗ Failed: {fileName} - {ex.Message}")
' Quarantine failed invoices for manual review
Dim destPath As String = Path.Combine(_errorFolder, fileName)
File.Move(invoicePath, destPath, overwrite:=True)
results.Add(New ProcessingResult With {
.FileName = fileName,
.Success = False,
.ErrorMessage = ex.Message
})
End Try
Next
GenerateReport(results)
Return results
End Function
' Checks for minimum required fields
Private Function ValidateInvoiceData(data As InvoiceData) As Boolean
Return Not String.IsNullOrEmpty(data.InvoiceNumber) AndAlso
Not String.IsNullOrEmpty(data.VendorName) AndAlso
data.TotalAmount > 0
End Function
' Placeholder for accounting system integration
Private Async Function SaveToAccountingSystem(data As InvoiceData) As Task
' Integrate with your accounting system here
' Examples: QuickBooks API, Xero API, SAP, or database storage
Console.WriteLine($" Saved invoice {data.InvoiceNumber} to accounting system")
Await Task.CompletedTask
End Function
' Outputs a summary of the batch processing results
Private Sub GenerateReport(results As List(Of ProcessingResult))
Dim successful As Integer = results.Count(Function(r) r.Success)
Dim failed As Integer = results.Count(Function(r) Not r.Success)
Console.WriteLine(vbCrLf & "========== Processing Complete ==========")
Console.WriteLine($"Total Processed: {results.Count}")
Console.WriteLine($"Successful: {successful}")
Console.WriteLine($"Failed: {failed}")
If failed > 0 Then
Console.WriteLine(vbCrLf & "Failed invoices requiring review:")
For Each failure In results.Where(Function(r) Not r.Success)
Console.WriteLine($" • {failure.FileName}: {failure.ErrorMessage}")
Next
End If
End Sub
End Class
This pipeline implements a complete workflow: it scans a folder for incoming PDFs, processes each one, validates the extracted data, routes successful extractions to your accounting system, and quarantines failures for manual review. The summary report gives visibility into processing outcomes.
How to Integrate C# Invoice Processing with Accounting Systems
The extracted invoice data ultimately needs to flow into accounting systems for payment and record-keeping. The specifics vary by platform, but the integration patterns are consistent.
What are Common Integration Patterns for QuickBooks, Xero, and SAP?
Most accounting platforms offer REST APIs for creating bills or invoices programmatically. Here's a generalized pattern that you can adapt for your specific platform:
using System;using System.Net.Http;using System.Text;using System.Text.Json;using System.Threading.Tasks;// Generic integration layer for pushing invoice data to accounting systems// Adapt the API calls based on your specific platformpublic class AccountingSystemIntegration{ private readonly HttpClient _httpClient; private readonly string _apiKey; private readonly string _baseUrl; publicAccountingSystemIntegration(string apiKey, string baseUrl) { _apiKey = apiKey; _baseUrl = baseUrl; _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}"); } // Creates a Bill in QuickBooks (vendor invoices are called "Bills") public async TaskSendToQuickBooks(InvoiceData invoice) { // QuickBooks Bill structure - see their API docs for full schema var bill = new {VendorRef = new { name = invoice.VendorName },TxnDate = invoice.InvoiceDate,DocNumber = invoice.InvoiceNumber,TotalAmt = invoice.TotalAmount,Line = new[] { new {Amount = invoice.TotalAmount,DetailType = "AccountBasedExpenseLineDetail",AccountBasedExpenseLineDetail = new {AccountRef = new { name = "Accounts Payable" } } } } }; awaitPostToApi("/v3/company/{companyId}/bill", bill); } // Creates an accounts payable invoice in Xero public async TaskSendToXero(InvoiceData invoice) { // ACCPAY type indicates this is a bill to pay (not a sales invoice) var bill = new {Type = "ACCPAY",Contact = new { Name = invoice.VendorName },Date = invoice.InvoiceDate,InvoiceNumber = invoice.InvoiceNumber,Total = invoice.TotalAmount }; awaitPostToApi("/api.xro/2.0/Invoices", bill); } // Generic POST helper with error handling private async TaskPostToApi(string endpoint, object payload) { string json = JsonSerializer.Serialize(payload); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync($"{_baseUrl}{endpoint}", content); if (!response.IsSuccessStatusCode) { string error = await response.Content.ReadAsStringAsync(); throw new Exception($"API Error: {response.StatusCode} - {error}"); }Console.WriteLine($"Successfully posted to {endpoint}"); }}
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
// Generic integration layer for pushing invoice data to accounting systems
// Adapt the API calls based on your specific platform
public class AccountingSystemIntegration
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _baseUrl;
public AccountingSystemIntegration(string apiKey, string baseUrl)
{
_apiKey = apiKey;
_baseUrl = baseUrl;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
}
// Creates a Bill in QuickBooks (vendor invoices are called "Bills")
public async Task SendToQuickBooks(InvoiceData invoice)
{
// QuickBooks Bill structure - see their API docs for full schema
var bill = new
{
VendorRef = new { name = invoice.VendorName },
TxnDate = invoice.InvoiceDate,
DocNumber = invoice.InvoiceNumber,
TotalAmt = invoice.TotalAmount,
Line = new[]
{
new
{
Amount = invoice.TotalAmount,
DetailType = "AccountBasedExpenseLineDetail",
AccountBasedExpenseLineDetail = new
{
AccountRef = new { name = "Accounts Payable" }
}
}
}
};
await PostToApi("/v3/company/{companyId}/bill", bill);
}
// Creates an accounts payable invoice in Xero
public async Task SendToXero(InvoiceData invoice)
{
// ACCPAY type indicates this is a bill to pay (not a sales invoice)
var bill = new
{
Type = "ACCPAY",
Contact = new { Name = invoice.VendorName },
Date = invoice.InvoiceDate,
InvoiceNumber = invoice.InvoiceNumber,
Total = invoice.TotalAmount
};
await PostToApi("/api.xro/2.0/Invoices", bill);
}
// Generic POST helper with error handling
private async Task PostToApi(string endpoint, object payload)
{
string json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{_baseUrl}{endpoint}", content);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
throw new Exception($"API Error: {response.StatusCode} - {error}");
}
Console.WriteLine($"Successfully posted to {endpoint}");
}
}
ImportsSystemImportsSystem.Net.HttpImportsSystem.TextImportsSystem.Text.JsonImportsSystem.Threading.Tasks' Generic integration layer for pushing invoice data to accounting systems' Adapt the API calls based on your specific platformPublic Class AccountingSystemIntegration PrivateReadOnly _httpClient AsHttpClient PrivateReadOnly _apiKey AsString PrivateReadOnly _baseUrl AsString Public Sub New(apiKey AsString, baseUrl AsString) _apiKey = apiKey _baseUrl = baseUrl _httpClient = New HttpClient() _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}") End Sub ' Creates a Bill in QuickBooks (vendor invoices are called "Bills") PublicAsync Function SendToQuickBooks(invoice AsInvoiceData) AsTask ' QuickBooks Bill structure - see their API docs for full schema Dim bill = New With { .VendorRef = New With {.name = invoice.VendorName}, .TxnDate = invoice.InvoiceDate, .DocNumber = invoice.InvoiceNumber, .TotalAmt = invoice.TotalAmount, .Line = New Object() { New With { .Amount = invoice.TotalAmount, .DetailType = "AccountBasedExpenseLineDetail", .AccountBasedExpenseLineDetail = New With { .AccountRef = New With {.name = "Accounts Payable"} } } } }AwaitPostToApi("/v3/company/{companyId}/bill", bill) End Function ' Creates an accounts payable invoice in Xero PublicAsync Function SendToXero(invoice AsInvoiceData) AsTask ' ACCPAY type indicates this is a bill to pay (not a sales invoice) Dim bill = New With { .Type = "ACCPAY", .Contact = New With {.Name = invoice.VendorName}, .Date = invoice.InvoiceDate, .InvoiceNumber = invoice.InvoiceNumber, .Total = invoice.TotalAmount }AwaitPostToApi("/api.xro/2.0/Invoices", bill) End Function ' Generic POST helper with error handling PrivateAsync Function PostToApi(endpoint AsString, payload AsObject) AsTask Dim json AsString = JsonSerializer.Serialize(payload) Dim content = New StringContent(json, Encoding.UTF8, "application/json") Dim response = Await _httpClient.PostAsync($"{_baseUrl}{endpoint}", content) IfNotresponse.IsSuccessStatusCodeThen Dim error AsString = Awaitresponse.Content.ReadAsStringAsync()Throw New Exception($"API Error: {response.StatusCode} - {error}") End IfConsole.WriteLine($"Successfully posted to {endpoint}") End FunctionEnd Class
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading.Tasks
' Generic integration layer for pushing invoice data to accounting systems
' Adapt the API calls based on your specific platform
Public Class AccountingSystemIntegration
Private ReadOnly _httpClient As HttpClient
Private ReadOnly _apiKey As String
Private ReadOnly _baseUrl As String
Public Sub New(apiKey As String, baseUrl As String)
_apiKey = apiKey
_baseUrl = baseUrl
_httpClient = New HttpClient()
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}")
End Sub
' Creates a Bill in QuickBooks (vendor invoices are called "Bills")
Public Async Function SendToQuickBooks(invoice As InvoiceData) As Task
' QuickBooks Bill structure - see their API docs for full schema
Dim bill = New With {
.VendorRef = New With {.name = invoice.VendorName},
.TxnDate = invoice.InvoiceDate,
.DocNumber = invoice.InvoiceNumber,
.TotalAmt = invoice.TotalAmount,
.Line = New Object() {
New With {
.Amount = invoice.TotalAmount,
.DetailType = "AccountBasedExpenseLineDetail",
.AccountBasedExpenseLineDetail = New With {
.AccountRef = New With {.name = "Accounts Payable"}
}
}
}
}
Await PostToApi("/v3/company/{companyId}/bill", bill)
End Function
' Creates an accounts payable invoice in Xero
Public Async Function SendToXero(invoice As InvoiceData) As Task
' ACCPAY type indicates this is a bill to pay (not a sales invoice)
Dim bill = New With {
.Type = "ACCPAY",
.Contact = New With {.Name = invoice.VendorName},
.Date = invoice.InvoiceDate,
.InvoiceNumber = invoice.InvoiceNumber,
.Total = invoice.TotalAmount
}
Await PostToApi("/api.xro/2.0/Invoices", bill)
End Function
' Generic POST helper with error handling
Private Async Function PostToApi(endpoint As String, payload As Object) As Task
Dim json As String = JsonSerializer.Serialize(payload)
Dim content = New StringContent(json, Encoding.UTF8, "application/json")
Dim response = Await _httpClient.PostAsync($"{_baseUrl}{endpoint}", content)
If Not response.IsSuccessStatusCode Then
Dim error As String = Await response.Content.ReadAsStringAsync()
Throw New Exception($"API Error: {response.StatusCode} - {error}")
End If
Console.WriteLine($"Successfully posted to {endpoint}")
End Function
End Class
Each platform has its own authentication mechanism (OAuth for QuickBooks and Xero, various methods for SAP), required fields, and API conventions. Consult your target platform's documentation for specifics, but the pattern of transforming extracted invoice data into API payloads remains consistent.
How to Batch Process Hundreds of Invoices
High-volume invoice processing requires careful attention to concurrency and resource management. Here's a pattern using parallel processing with controlled concurrency:
using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.Linq;using System.Threading;using System.Threading.Tasks;// Tracks the result of processing a single invoice in a batchpublic class BatchResult{ public stringFilePath { get; set; } public boolSuccess { get; set; } public stringInvoiceNumber { get; set; } public stringError { get; set; }}// High-volume invoice processor with controlled parallelism// Prevents overwhelming APIs while maximizing throughputpublic class BatchInvoiceProcessor{ private readonly SmartInvoiceProcessor _invoiceProcessor; private readonly AccountingSystemIntegration _accountingIntegration; private readonly int _maxConcurrency; publicBatchInvoiceProcessor(string aiApiKey, string accountingApiKey, string accountingUrl, int maxConcurrency = 5) { _invoiceProcessor = new SmartInvoiceProcessor(aiApiKey); _accountingIntegration = new AccountingSystemIntegration(accountingApiKey, accountingUrl); _maxConcurrency = maxConcurrency; // Adjust based on API rate limits } // Processes multiple invoices in parallel with controlled concurrency public async Task<List<BatchResult>> ProcessInvoiceBatch(List<string> invoicePaths) { // Thread-safe collection for gathering results from parallel tasks var results = new ConcurrentBag<BatchResult>(); // Semaphore limits how many invoices process simultaneously var semaphore = new SemaphoreSlim(_maxConcurrency); // Create a task for each invoice var tasks = invoicePaths.Select(async path => { // Wait for a slot to become available await semaphore.WaitAsync(); try { var result = awaitProcessSingleInvoice(path); results.Add(result); } finally { // Release slot for next invoice semaphore.Release(); } }); // Wait for all invoices to complete awaitTask.WhenAll(tasks); // Output summary statistics var resultList = results.ToList(); int successful = resultList.Count(r => r.Success); int failed = resultList.Count(r => !r.Success);Console.WriteLine($"\nBatch Processing Complete:");Console.WriteLine($" Total: {resultList.Count}");Console.WriteLine($" Successful: {successful}");Console.WriteLine($" Failed: {failed}"); return resultList; } // Processes one invoice: extract data and send to accounting system private async Task<BatchResult> ProcessSingleInvoice(string pdfPath) { try {Console.WriteLine($"Processing: {pdfPath}"); var invoiceData = await _invoiceProcessor.ProcessAnyInvoice(pdfPath); await _accountingIntegration.SendToQuickBooks(invoiceData);Console.WriteLine($"✓ Completed: {invoiceData.InvoiceNumber}"); return new BatchResult {FilePath = pdfPath,Success = true,InvoiceNumber = invoiceData.InvoiceNumber }; } catch (Exception ex) {Console.WriteLine($"✗ Failed: {pdfPath}"); return new BatchResult {FilePath = pdfPath,Success = false,Error = ex.Message }; } }}
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
// Tracks the result of processing a single invoice in a batch
public class BatchResult
{
public string FilePath { get; set; }
public bool Success { get; set; }
public string InvoiceNumber { get; set; }
public string Error { get; set; }
}
// High-volume invoice processor with controlled parallelism
// Prevents overwhelming APIs while maximizing throughput
public class BatchInvoiceProcessor
{
private readonly SmartInvoiceProcessor _invoiceProcessor;
private readonly AccountingSystemIntegration _accountingIntegration;
private readonly int _maxConcurrency;
public BatchInvoiceProcessor(string aiApiKey, string accountingApiKey,
string accountingUrl, int maxConcurrency = 5)
{
_invoiceProcessor = new SmartInvoiceProcessor(aiApiKey);
_accountingIntegration = new AccountingSystemIntegration(accountingApiKey, accountingUrl);
_maxConcurrency = maxConcurrency; // Adjust based on API rate limits
}
// Processes multiple invoices in parallel with controlled concurrency
public async Task<List<BatchResult>> ProcessInvoiceBatch(List<string> invoicePaths)
{
// Thread-safe collection for gathering results from parallel tasks
var results = new ConcurrentBag<BatchResult>();
// Semaphore limits how many invoices process simultaneously
var semaphore = new SemaphoreSlim(_maxConcurrency);
// Create a task for each invoice
var tasks = invoicePaths.Select(async path =>
{
// Wait for a slot to become available
await semaphore.WaitAsync();
try
{
var result = await ProcessSingleInvoice(path);
results.Add(result);
}
finally
{
// Release slot for next invoice
semaphore.Release();
}
});
// Wait for all invoices to complete
await Task.WhenAll(tasks);
// Output summary statistics
var resultList = results.ToList();
int successful = resultList.Count(r => r.Success);
int failed = resultList.Count(r => !r.Success);
Console.WriteLine($"\nBatch Processing Complete:");
Console.WriteLine($" Total: {resultList.Count}");
Console.WriteLine($" Successful: {successful}");
Console.WriteLine($" Failed: {failed}");
return resultList;
}
// Processes one invoice: extract data and send to accounting system
private async Task<BatchResult> ProcessSingleInvoice(string pdfPath)
{
try
{
Console.WriteLine($"Processing: {pdfPath}");
var invoiceData = await _invoiceProcessor.ProcessAnyInvoice(pdfPath);
await _accountingIntegration.SendToQuickBooks(invoiceData);
Console.WriteLine($"✓ Completed: {invoiceData.InvoiceNumber}");
return new BatchResult
{
FilePath = pdfPath,
Success = true,
InvoiceNumber = invoiceData.InvoiceNumber
};
}
catch (Exception ex)
{
Console.WriteLine($"✗ Failed: {pdfPath}");
return new BatchResult
{
FilePath = pdfPath,
Success = false,
Error = ex.Message
};
}
}
}
ImportsSystemImportsSystem.Collections.ConcurrentImportsSystem.Collections.GenericImportsSystem.LinqImportsSystem.ThreadingImportsSystem.Threading.Tasks' Tracks the result of processing a single invoice in a batchPublic Class BatchResult Public Property FilePathAsString Public Property SuccessAsBoolean Public Property InvoiceNumberAsString Public Property ErrorAsStringEnd Class' High-volume invoice processor with controlled parallelism' Prevents overwhelming APIs while maximizing throughputPublic Class BatchInvoiceProcessor PrivateReadOnly _invoiceProcessor AsSmartInvoiceProcessor PrivateReadOnly _accountingIntegration AsAccountingSystemIntegration PrivateReadOnly _maxConcurrency AsInteger Public Sub New(aiApiKey AsString, accountingApiKey AsString, accountingUrl AsString, Optional maxConcurrency AsInteger = 5) _invoiceProcessor = New SmartInvoiceProcessor(aiApiKey) _accountingIntegration = New AccountingSystemIntegration(accountingApiKey, accountingUrl) _maxConcurrency = maxConcurrency ' Adjust based on API rate limits End Sub ' Processes multiple invoices in parallel with controlled concurrency PublicAsync Function ProcessInvoiceBatch(invoicePaths AsList(OfString)) AsTask(OfList(OfBatchResult)) ' Thread-safe collection for gathering results from parallel tasks Dim results = New ConcurrentBag(OfBatchResult)() ' Semaphore limits how many invoices process simultaneously Dim semaphore = New SemaphoreSlim(_maxConcurrency) ' Create a task for each invoice Dim tasks = invoicePaths.Select(Async Function(path) ' Wait for a slot to become availableAwait semaphore.WaitAsync()Try Dim result = AwaitProcessSingleInvoice(path) results.Add(result)Finally ' Release slot for next invoice semaphore.Release()EndTry End Function) ' Wait for all invoices to completeAwaitTask.WhenAll(tasks) ' Output summary statistics Dim resultList = results.ToList() Dim successful = resultList.Count(Function(r) r.Success) Dim failed = resultList.Count(Function(r) Not r.Success)Console.WriteLine(vbCrLf & "Batch Processing Complete:")Console.WriteLine($" Total: {resultList.Count}")Console.WriteLine($" Successful: {successful}")Console.WriteLine($" Failed: {failed}") Return resultList End Function ' Processes one invoice: extract data and send to accounting system PrivateAsync Function ProcessSingleInvoice(pdfPath AsString) AsTask(OfBatchResult)TryConsole.WriteLine($"Processing: {pdfPath}") Dim invoiceData = Await _invoiceProcessor.ProcessAnyInvoice(pdfPath)Await _accountingIntegration.SendToQuickBooks(invoiceData)Console.WriteLine($"✓ Completed: {invoiceData.InvoiceNumber}") Return New BatchResultWith { .FilePath = pdfPath, .Success = True, .InvoiceNumber = invoiceData.InvoiceNumber }Catch ex AsExceptionConsole.WriteLine($"✗ Failed: {pdfPath}") Return New BatchResultWith { .FilePath = pdfPath, .Success = False, .Error = ex.Message }EndTry End FunctionEnd Class
Imports System
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
' Tracks the result of processing a single invoice in a batch
Public Class BatchResult
Public Property FilePath As String
Public Property Success As Boolean
Public Property InvoiceNumber As String
Public Property Error As String
End Class
' High-volume invoice processor with controlled parallelism
' Prevents overwhelming APIs while maximizing throughput
Public Class BatchInvoiceProcessor
Private ReadOnly _invoiceProcessor As SmartInvoiceProcessor
Private ReadOnly _accountingIntegration As AccountingSystemIntegration
Private ReadOnly _maxConcurrency As Integer
Public Sub New(aiApiKey As String, accountingApiKey As String, accountingUrl As String, Optional maxConcurrency As Integer = 5)
_invoiceProcessor = New SmartInvoiceProcessor(aiApiKey)
_accountingIntegration = New AccountingSystemIntegration(accountingApiKey, accountingUrl)
_maxConcurrency = maxConcurrency ' Adjust based on API rate limits
End Sub
' Processes multiple invoices in parallel with controlled concurrency
Public Async Function ProcessInvoiceBatch(invoicePaths As List(Of String)) As Task(Of List(Of BatchResult))
' Thread-safe collection for gathering results from parallel tasks
Dim results = New ConcurrentBag(Of BatchResult)()
' Semaphore limits how many invoices process simultaneously
Dim semaphore = New SemaphoreSlim(_maxConcurrency)
' Create a task for each invoice
Dim tasks = invoicePaths.Select(Async Function(path)
' Wait for a slot to become available
Await semaphore.WaitAsync()
Try
Dim result = Await ProcessSingleInvoice(path)
results.Add(result)
Finally
' Release slot for next invoice
semaphore.Release()
End Try
End Function)
' Wait for all invoices to complete
Await Task.WhenAll(tasks)
' Output summary statistics
Dim resultList = results.ToList()
Dim successful = resultList.Count(Function(r) r.Success)
Dim failed = resultList.Count(Function(r) Not r.Success)
Console.WriteLine(vbCrLf & "Batch Processing Complete:")
Console.WriteLine($" Total: {resultList.Count}")
Console.WriteLine($" Successful: {successful}")
Console.WriteLine($" Failed: {failed}")
Return resultList
End Function
' Processes one invoice: extract data and send to accounting system
Private Async Function ProcessSingleInvoice(pdfPath As String) As Task(Of BatchResult)
Try
Console.WriteLine($"Processing: {pdfPath}")
Dim invoiceData = Await _invoiceProcessor.ProcessAnyInvoice(pdfPath)
Await _accountingIntegration.SendToQuickBooks(invoiceData)
Console.WriteLine($"✓ Completed: {invoiceData.InvoiceNumber}")
Return New BatchResult With {
.FilePath = pdfPath,
.Success = True,
.InvoiceNumber = invoiceData.InvoiceNumber
}
Catch ex As Exception
Console.WriteLine($"✗ Failed: {pdfPath}")
Return New BatchResult With {
.FilePath = pdfPath,
.Success = False,
.Error = ex.Message
}
End Try
End Function
End Class
The SemaphoreSlim ensures you don't overwhelm external APIs or exhaust system resources. Adjust _maxConcurrency based on your API rate limits and server capacity. The ConcurrentBag safely collects results from parallel operations.
Next Steps
Invoice automation represents a significant opportunity to reduce manual work, minimize errors, and accelerate business processes. This guide has walked you through the complete lifecycle: generating professional invoices from HTML templates, complying with ZUGFeRD and Factur-X e-invoicing standards, extracting data from received invoices using both pattern matching and AI-powered processing, and building scalable automation pipelines.
IronPDF serves as the foundation for these capabilities, providing reliable HTML-to-PDF rendering, reliable text extraction, and the attachment features needed for PDF/A-3 e-invoicing compliance. Its Chrome-based rendering engine ensures your invoices look exactly as designed, while its extraction methods handle the complexity of PDF text encoding automatically.
The patterns shown here are starting points. Real implementations will need adaptation for your specific invoice formats, accounting systems, and business rules. For high-volume scenarios, the batch processing tutorial covers parallel execution with controlled concurrency and error recovery.
Ready to start building? Download IronPDF and try it with a free trial. The library includes a free development license, so you can fully evaluate invoice generation, data extraction, and PDF report capabilities before committing to a production license. If you have questions about invoice automation or accounting system integration, reach out to our engineering support team.
Frequently Asked Questions
What is invoice processing in C# .NET with IronPDF?
Invoice processing in C# .NET with IronPDF involves generating professional PDF invoices from HTML templates, ensuring compliance with ZUGFeRD and Factur-X e-invoicing standards, extracting structured data using AI-powered processing, and creating automation pipelines that integrate with accounting systems like QuickBooks.
How does IronPDF help in generating PDF invoices?
IronPDF helps in generating PDF invoices by converting HTML templates into high-quality PDF documents. This allows for the use of standard web technologies like HTML and CSS to design invoices, which IronPDF then renders with pixel-perfect accuracy.
Can IronPDF embedded XML data in PDF invoices for e-invoicing compliance?
Yes, IronPDF can embed XML data in PDF invoices to comply with e-invoicing standards like ZUGFeRD and Factur-X. This involves attaching structured XML data within the PDF/A-3 format, enabling compliance with European e-invoicing mandates.
How can I extract text from a PDF invoice using IronPDF?
You can extract text from a PDF invoice using IronPDF's `ExtractAllText` method, which handles the complexities of PDF text extraction and provides the text data required for processing invoices.
Does IronPDF support AI-powered invoice data extraction?
Yes, IronPDF supports AI-powered invoice data extraction by interfacing with AI and LLM APIs. This approach is used to extract structured data from diverse invoice formats, using IronPDF for initial text extraction and AI for data parsing.
What are some integration patterns for accounting systems with IronPDF?
Common integration patterns for accounting systems with IronPDF include using REST APIs to programmatically create bills or invoices in platforms like QuickBooks, Xero, and SAP, transforming extracted invoice data into JSON payloads for these platforms.
Can IronPDF handle batch processing of invoices?
Yes, IronPDF can handle batch processing of invoices effectively. This involves using a parallel processing pattern with controlled concurrency to manage resources while converting multiple invoices in bulk.
What are the advantages of using PDF format for invoices?
The PDF format preserves invoice formatting across devices, prevents unauthorized changes, supports digital signatures and encryption, and is widely recognized by business systems, making it ideal for professional invoices.
How does IronPDF assist with e-invoicing compliance in Europe?
IronPDF assists with e-invoicing compliance in Europe by enabling the embedding of XML data for standards like ZUGFeRD and Factur-X within PDFs, necessary for meeting European Union e-invoicing mandates.
What is a recommended technology stack for invoice processing in .NET?
A recommended technology stack for invoice processing in .NET includes IronPDF for PDF manipulation, IronQR for embedding QR codes, and integration with AI models for advanced data parsing.
Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.