Rechnungsverarbeitung in C#;: Generieren, Extrahieren und Automatisieren von PDF-Rechnungen mit .NET

This article was translated from English: Does it need improvement?
Translated
View the article in English

Rechnungsverarbeitung in C# .NET mit IronPDF deckt den gesamten Lebenszyklus von Dokumenten ab: Generierung professioneller PDF-Rechnungen aus HTML-Vorlagen, Einhaltung der ZUGFeRD- und Factur-X-Standards für die elektronische Rechnungsstellung, Extraktion strukturierter Daten aus empfangenen Rechnungen mithilfe von Text-Parsing und KI-gestützter Verarbeitung sowie Aufbau von Batch-Automatisierungspipelines, die sich in Buchhaltungssysteme wie QuickBooks, Xero und SAP integrieren lassen.

TL;DR: Quickstart Guide

Dieses Tutorial behandelt das Generieren, Extrahieren und Automatisieren von PDF-Rechnungen in C# .NET, einschließlich der Einhaltung von E-Invoicing-Vorgaben, KI-gestütztem Parsing und der Integration von Buchhaltungssystemen.

  • Für wen ist das?: .NET-Entwickler, die Module für die Rechnungsstellung, die Automatisierung der Kreditorenbuchhaltung oder die Einhaltung von Vorschriften für die elektronische Rechnungsstellung entwickeln.
  • Was Sie erstellen werden: 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.
  • Wo es läuft: .NET 10, .NET 8 LTS, .NET Framework 4.6.2+, und .NET Standard 2.0. Keine externen Service-Abhängigkeiten.
  • Wann sollten Sie diesen Ansatz verwenden: Wenn Sie Rechnungs-PDFs generieren, die EU-Vorschriften zur elektronischen Rechnungsstellung erfüllen oder Daten aus Lieferantenrechnungen für die Kreditorenbuchhaltung extrahieren müssen.
  • Warum es technisch wichtig ist: IronPDF rendert HTML in PDF mit pixelgenauer Genauigkeit, unterstützt PDF/A-3 für eingebettetes XML und bietet APIs zur Textextraktion, die mit Regex oder KI kombiniert werden können, um unstrukturierte Rechnungen in strukturierte Daten umzuwandeln.

Generieren Sie Ihre erste PDF-Rechnung mit nur ein paar Zeilen Code:

Nuget IconLegen Sie jetzt mit NuGet los, um PDFs zu erstellen:

  1. Installieren Sie IronPDF mit dem NuGet-Paketmanager.

    PM > Install-Package IronPdf

  2. Kopieren Sie diesen Codeausschnitt und führen Sie ihn aus.

    var renderer = new IronPdf.ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice #1001</h1><p>Total: $500.00</p>");
    pdf.SaveAs("invoice.pdf");
  3. Bereitstellen zum Testen in Ihrer Live-Umgebung

    Beginnen Sie noch heute mit der Nutzung von IronPDF in Ihrem Projekt – mit einer kostenlosen Testversion.
    arrow pointer

Nachdem Sie IronPDF gekauft oder sich für eine 30-tägige Testversion angemeldet haben, fügen Sie Ihren Lizenzschlüssel am Anfang Ihrer Anwendung hinzu.

IronPdf.License.LicenseKey = "KEY";
IronPdf.License.LicenseKey = "KEY";
Imports IronPdf

IronPdf.License.LicenseKey = "KEY"
$vbLabelText   $csharpLabel

Nutzen Sie IronPDF heute kostenlos in Ihrem Projekt.

Erster Schritt:
green arrow pointer
NuGet Mit NuGet installieren

PM >  Install-Package IronPdf

Schauen Sie sich IronPDF auf NuGet für eine schnelle Installation an. Mit über 10 Millionen Downloads transformiert es die PDF-Entwicklung mit C#. Sie können auch das DLL oder den Windows Installer herunterladen.

Inhaltsverzeichnis

NuGet Mit NuGet installieren

PM >  Install-Package IronPdf

Schauen Sie sich IronPDF auf NuGet für eine schnelle Installation an. Mit über 10 Millionen Downloads transformiert es die PDF-Entwicklung mit C#. Sie können auch das DLL oder den Windows Installer herunterladen.

Was ist der Lebenszyklus von Rechnungen und warum bleibt PDF der Standard?

Bevor man in den Code eintaucht, ist es hilfreich, den gesamten Weg einer Rechnung durch ein modernes Geschäftssystem zu verstehen. Der Lebenszyklus einer Rechnung besteht aus fünf verschiedenen Phasen: Erstellung, Verteilung, Empfang, Datenextraktion und Integration in die Buchhaltung.

Der Rechnungsprozess beginnt mit der Erstellung. Ein Unternehmen erstellt eine Rechnung, die Einzelposten, Preise, Steuerberechnungen, Zahlungsbedingungen und Branding enthält. Die Rechnung muss professionell aussehen und alle rechtlichen Anforderungen erfüllen. Als Nächstes kommt die Verteilung, bei der die Rechnung per E-Mail, über ein Kundenportal oder auf dem traditionellen Postweg an den Kunden gesendet wird. Sobald der Kunde das Dokument erhält, wird es von der Kreditorenbuchhaltung erfasst und für die Bearbeitung vorbereitet. Bei der Datenextraktion werden wichtige Informationen aus der Rechnung extrahiert, wie z. B. Angaben zum Lieferanten, Einzelposten, Summen und Fälligkeitsdaten, damit sie überprüft und mit Bestellungen abgeglichen werden können. Bei der Buchhaltungsintegration schließlich werden diese Daten in Finanzsysteme wie QuickBooks, Xero oder SAP übertragen, um Zahlungen und Aufzeichnungen zu ermöglichen.

Warum ist PDF nach so vielen Jahren immer noch das am meisten verwendete Format? Es geht um eine einzigartige Mischung von Vorteilen. Mit PDFs bleibt die Formatierung Ihrer Rechnungen konsistent, egal welches Gerät oder Betriebssystem Sie verwenden. Egal, ob jemand Ihre Rechnung unter Windows, Mac oder auf seinem Handy öffnet, sie sieht genauso aus, wie Sie sie gestaltet haben. PDFs sind außerdem schwer zu verändern und schützen die Integrität Ihrer Dokumente besser als Formate wie Word oder Excel. Sie können digitale Signaturen für die Authentizität hinzufügen und Verschlüsselung für die Sicherheit verwenden. Am wichtigsten ist, dass PDFs zu einem universellen Standard geworden sind, der von jedem Geschäftssystem erkannt und unterstützt wird.

Das ist natürlich eine Herausforderung. PDFs sind so gestaltet, dass sie von Menschen gelesen werden können, nicht von Computern verarbeitet werden müssen. Anstatt Informationen in strukturierten Daten zu speichern, speichert eine PDF-Datei Text, Linien, Formen und Bilder an der Stelle, an der sie auf der Seite erscheinen. Deshalb sind Tools wie IronPDF so hilfreich, denn sie ermöglichen es, menschenfreundliche Dokumente in Daten zu verwandeln, mit denen Software arbeiten kann.


Professionelle PDF-Rechnungen in C# generieren

Die programmatische Erstellung von Rechnungen erfordert die Umwandlung strukturierter Daten, wie z. B. Kundeninformationen, Einzelposten und Berechnungen, in ein ansprechendes PDF-Dokument. IronPDF macht dies bemerkenswert einfach, indem es HTML und CSS nutzt, Technologien, die die meisten Entwickler bereits gut kennen.

In diesem Tutorium gehen wir mögliche Szenarien durch, denen Sie in der Praxis begegnen werden. Sie können das unten abgebildete Projekt auch hier herunterladen.

Wie man eine HTML-Vorlage für Rechnungen erstellt

Die Grundlage der Rechnungserstellung mit IronPDF ist HTML. Anstatt sich mit Low-Level-PDF-Zeichenbefehlen herumzuschlagen, gestalten Sie Ihre Rechnung mit Standard-HTML und CSS und lassen sie dann von der Chrome-basierten Rendering-Engine von IronPDF in eine pixelgenaue PDF-Datei umwandeln.

Hier ist eine einfache Rechnungsvorlage, die den Ansatz veranschaulicht:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-invoice-processing/basic-invoice-template.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");
Imports IronPdf

' Define the HTML template for a basic invoice
' Uses inline CSS for styling headers, tables, and totals
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-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
Dim renderer As New ChromePdfRenderer()

' Convert the HTML string to a PDF document
Dim pdf = renderer.RenderHtmlAsPdf(invoiceHtml)

' Save the generated PDF to disk
pdf.SaveAs("basic-invoice.pdf")
$vbLabelText   $csharpLabel

Musterausgabe

Dieser Ansatz bietet eine enorme Flexibilität. Jedes CSS, das in Chrome funktioniert, funktioniert auch in Ihrer PDF-Datei, einschließlich moderner Funktionen wie Flexbox, Grid-Layouts und benutzerdefinierter Schriftarten. Sie können sogar externe Stylesheets und Bilder verwenden, indem Sie auf URLs oder lokale Dateipfade verweisen.

Hinzufügen von dynamischen Positionen und Berechnen von Summen

Echte Rechnungen haben selten statischen Inhalt. Sie müssen Einzelposten aus einer Datenbank einfügen, Zwischensummen berechnen, Steuersätze anwenden und Währungswerte formatieren. Das folgende Beispiel demonstriert ein produktionsreifes Muster für die dynamische Rechnungserstellung:

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);
    }
}
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);
    }
}
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
$vbLabelText   $csharpLabel

Musterausgabe

Die Klasse Invoice kapselt alle Rechnungsdaten mit berechneten Eigenschaften für Zwischensumme, Steuer und Gesamtbetrag. Der Generator wandelt diese Daten mithilfe von String-Interpolation in HTML um und rendert sie dann in PDF. Durch diese Trennung von Belangen wird der Code wartbar und testbar.

Wie man Rechnungen mit Firmenlogos und Wasserzeichen versieht

Professionelle Rechnungen benötigen Branding-Elemente wie Logos und in manchen Fällen Wasserzeichen, um den Zahlungsstatus anzuzeigen. IronPDF unterstützt sowohl eingebettete Bilder in HTML als auch programmatische Wasserzeichen nach dem Rendering.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-invoice-processing/branding-watermarks.cs
using IronPdf;
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");

using IronPdf;
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

' Invoice HTML template with company logo embedded via URL
' Logo can also be Base64-encoded or a local file path
Dim htmlWithLogo As String = "
<!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
Dim 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")
$vbLabelText   $csharpLabel

Musterausgabe

Die Methode ApplyWatermark akzeptiert HTML-Inhalte und gibt Ihnen die vollständige Kontrolle über das Aussehen des Wasserzeichens. Sie können Deckkraft, Drehung und Positionierung anpassen, um genau das gewünschte Aussehen zu erzielen. Dies ist besonders nützlich für die Kennzeichnung von Rechnungen als "PAID", "DRAFT" oder "CANCELLED", ohne dass das gesamte Dokument neu erstellt werden muss.

Moderne Rechnungen enthalten oft QR-Codes, die Kunden scannen können, um schnell zu bezahlen. IronPDF konzentriert sich zwar auf die PDF-Erzeugung, arbeitet aber nahtlos mit IronQR für die Erstellung von Barcodes zusammen:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-invoice-processing/qr-code-payment.cs
using IronPdf;
using IronQr;
using IronSoftware.Drawing;

// Generates PDF invoices with embedded QR codes for quick mobile payment
public class InvoiceWithQRGenerator
{
    public void GenerateInvoiceWithQR(string invoiceNumber, decimal amount)
    {
        // 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");
    }
}
Imports IronPdf
Imports IronQr
Imports IronSoftware.Drawing

' Generates PDF invoices with embedded QR codes for quick mobile payment
Public Class InvoiceWithQRGenerator
    Public Sub GenerateInvoiceWithQR(invoiceNumber As String, amount As Decimal)
        ' Create a payment URL with invoice details as query parameters
        Dim paymentUrl As String = $"https://yourcompany.com/pay?invoice={invoiceNumber}&amount={amount}"

        ' Generate QR code from the payment URL using IronQR
        Dim qrCode As QrCode = QrWriter.Write(paymentUrl)
        Dim qrImage As AnyBitmap = 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
        Dim invoiceHtml As String = $"
<!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
        Dim renderer = New ChromePdfRenderer()
        Dim pdf = renderer.RenderHtmlAsPdf(invoiceHtml)
        pdf.SaveAs($"invoice-{invoiceNumber}.pdf")
    End Sub
End Class
$vbLabelText   $csharpLabel

Musterausgabe

Der QR-Code verlinkt direkt zu einer Zahlungsseite, was die Reibungsverluste für die Kunden verringert und Ihren Cashflow beschleunigt. Dieses Muster funktioniert mit jedem Zahlungsanbieter, der eine URL-basierte Zahlungsauslösung unterstützt.


Wie man die ZUGFeRD- und Factur-X-Standards für die elektronische Rechnungsstellung in C# einhält

Die elektronische Rechnungsstellung wird in ganz Europa immer mehr zur Pflicht. Deutschland hat mit ZUGFeRD den Anfang gemacht, Frankreich folgte mit Factur-X. Diese Standards betten maschinenlesbare XML-Daten in PDF-Rechnungen ein und ermöglichen so eine automatisierte Verarbeitung unter Beibehaltung von menschenlesbaren Dokumenten. Das Verständnis und die Umsetzung dieser Standards ist für Unternehmen, die auf europäischen Märkten tätig sind, zunehmend wichtig.

Was ist ZUGFeRD und wie funktioniert es?

ZUGFeRD (Zentraler User Guide des Forums elektronische Rechnung Deutschland) ist ein deutscher E-Invoicing-Standard, der Rechnungsdaten als XML-Dateianhang in ein PDF/A-3-konformes Dokument einbettet. Das eingebettete XML ermöglicht eine automatische Datenextraktion ohne OCR oder Parsing.

Der Standard definiert drei Konformitätsstufen, die jeweils zunehmend besser strukturierte Daten bieten:

  • Basic: Enthält die wichtigsten Rechnungsdaten, die für eine einfache automatische Verarbeitung geeignet sind
  • Komfort: Fügt detaillierte Informationen hinzu, die eine vollautomatische Rechnungsbearbeitung ermöglichen
  • Erweitert: Enthält umfassende Daten für komplexe Geschäftsszenarien in verschiedenen Branchen

Das XML folgt dem UN/CEFACT Cross-Industry Invoice (CII) Schema, das zur Grundlage der europäischen E-Invoicing-Standardisierung geworden ist.

Was ist Factur-X und wie unterscheidet es sich von ZUGFeRD?

Factur-X ist die französische Implementierung desselben zugrunde liegenden Standards. ZUGFeRD 2.0 und Factur-X sind technisch identisch. Sie verwenden das gleiche XML-Schema und Konformitätsprofile, die auf der europäischen Norm EN 16931 basieren. Der Unterschied besteht lediglich in der regionalen Benennung: Eine nach den ZUGFeRD-Spezifikationen erstellte Rechnung ist auch unter Factur-X gültig und umgekehrt.

Wie man XML-Daten in PDF/A-3-Rechnungen einbettet

IronPDF bietet die für die Erstellung konformer elektronischer Rechnungen erforderlichen Anhangsfunktionen. Der Prozess umfasst die Generierung Ihrer Rechnungs-PDF-Datei, die Erstellung der XML-Daten nach dem CII-Schema und die Einbettung der XML-Datei als Anhang mit den richtigen Namenskonventionen:

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
        pdf.Attachments.AddFile(xmlPath, "zugferd-invoice.xml", "ZUGFeRD Invoice Data");

        // 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>";
    }
}
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
        pdf.Attachments.AddFile(xmlPath, "zugferd-invoice.xml", "ZUGFeRD Invoice Data");

        // 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>";
    }
}
Imports System
Imports 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 Sub GenerateZUGFeRDInvoice(invoice As Invoice)
        ' First, create the visual PDF that humans will read
        Dim renderer = New ChromePdfRenderer()
        Dim invoiceHtml As String = BuildInvoiceHtml(invoice)
        Dim pdf = renderer.RenderHtmlAsPdf(invoiceHtml)

        ' Define the UN/CEFACT namespaces required by the ZUGFeRD standard
        ' These are mandatory for compliance with European e-invoicing regulations
        Dim rsm As XNamespace = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"
        Dim ram As XNamespace = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100"
        Dim udt As XNamespace = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100"

        ' Build the ZUGFeRD XML structure following the Cross-Industry Invoice schema
        Dim zugferdXml = New XDocument(
            New XDeclaration("1.0", "UTF-8", Nothing),
            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
        Dim xmlPath As String = $"zugferd-{invoice.InvoiceNumber}.xml"
        zugferdXml.Save(xmlPath)

        ' Attach the XML to the PDF - filename must follow ZUGFeRD conventions
        pdf.Attachments.AddFile(xmlPath, "zugferd-invoice.xml", "ZUGFeRD Invoice Data")

        ' Final PDF contains both visual invoice and machine-readable XML
        pdf.SaveAs($"invoice-{invoice.InvoiceNumber}-zugferd.pdf")
    End Sub

    ' Generates simple HTML for the visual portion of the invoice
    Private Function BuildInvoiceHtml(invoice As Invoice) As String
        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>"
    End Function
End Class
$vbLabelText   $csharpLabel

Musterausgabe

Die wichtigsten Aspekte der Konformität sind die Verwendung der richtigen XML-Namensräume, die Einhaltung der CII-Schemastruktur und die Einbettung der XML-Datei mit einem geeigneten Dateinamen. Der TypeCode "380" weist das Dokument ausdrücklich als Handelsrechnung im Rahmen des UN/CEFACT-Standards aus.

Wie man Rechnungen für EU-Mandate zukunftssicher macht

Die Europäische Union schreibt nach und nach die elektronische Rechnungsstellung in allen Mitgliedsstaaten vor. Italien verlangt dies bereits für B2B-Transaktionen, Frankreich führt die Anforderungen schrittweise bis 2026 ein, und Deutschland hat die elektronische Rechnungsstellung im B2B-Bereich ab 2025 verbindlich angekündigt. Wenn Sie jetzt ZUGFeRD/Factur-X unterstützen, ist Ihr System auf diese gesetzlichen Anforderungen vorbereitet.

Hier ist ein Muster für einen konformitätsbewussten Rechnungsgenerator, der auf verschiedene Standards ausgerichtet sein kann:

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);
        pdf.Attachments.AddFile("temp-invoice.xml", filename, $"{standard} Invoice Data");
    }

    // 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>";
    }
}
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);
        pdf.Attachments.AddFile("temp-invoice.xml", filename, $"{standard} Invoice Data");
    }

    // 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>";
    }
}
Imports IronPdf
Imports 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
End Enum

' 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 Function GenerateCompliantInvoice(invoice As Invoice, standard As InvoiceStandard) As PdfDocument
        ' Generate the base PDF from HTML
        Dim renderer As New ChromePdfRenderer()
        Dim html As String = BuildInvoiceHtml(invoice)
        Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

        ' Attach the appropriate XML format based on target market/regulation
        Select Case standard
            Case InvoiceStandard.ZUGFeRD, InvoiceStandard.FacturX
                ' Both use Cross-Industry Invoice format, just different filenames
                EmbedCIIXmlData(pdf, invoice, standard)
            Case InvoiceStandard.Peppol
                ' Peppol uses Universal Business Language format
                EmbedUBLXmlData(pdf, invoice)
        End Select

        Return pdf
    End Function

    ' Creates and embeds CII-format XML (used by ZUGFeRD and Factur-X)
    Private Sub EmbedCIIXmlData(pdf As PdfDocument, invoice As Invoice, standard As InvoiceStandard)
        Dim xml As String = GenerateCIIXml(invoice)

        ' Filename convention differs between German and French standards
        Dim filename As String = If(standard = InvoiceStandard.ZUGFeRD, "zugferd-invoice.xml", "factur_x.xml")

        System.IO.File.WriteAllText("temp-invoice.xml", xml)
        pdf.Attachments.AddFile("temp-invoice.xml", filename, $"{standard} Invoice Data")
    End Sub

    ' Creates and embeds UBL-format XML for Peppol network compliance
    Private Sub EmbedUBLXmlData(pdf As PdfDocument, invoice As Invoice)
        ' UBL (Universal Business Language) is the Peppol standard format
        Dim xml As String = $"<?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")
    End Sub

    ' Generates minimal CII XML structure for demonstration
    Private Function GenerateCIIXml(invoice As Invoice) As String
        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>"
    End Function

    Private Function BuildInvoiceHtml(invoice As Invoice) As String
        Return $"<html><body><h1>Invoice {invoice.InvoiceNumber}</h1></body></html>"
    End Function
End Class
$vbLabelText   $csharpLabel

Diese Architektur ermöglicht es Ihnen, neue Standards hinzuzufügen, sobald diese auftauchen, ohne Ihre Kernlogik zur Rechnungserstellung umzustrukturieren. Der enumbasierte Ansatz macht es einfach, die Benutzer oder die Konfiguration bestimmen zu lassen, welcher Konformitätsmodus verwendet werden soll.


Wie man Daten aus PDF-Rechnungen in C# extrahiert

Die Erstellung von Rechnungen ist nur die Hälfte der Gleichung. Die meisten Unternehmen erhalten auch Rechnungen von Lieferanten und müssen Daten zur Verarbeitung extrahieren. IronPDF bietet leistungsstarke Textextraktionsfunktionen, die die Grundlage für die Erfassung von Rechnungsdaten bilden.

Wie man Text aus einer PDF-Rechnung extrahiert

Der grundlegendste Extraktionsvorgang ruft den gesamten Textinhalt aus einer PDF-Datei ab. Die Methode ExtractAllText von IronPDF bewältigt die Komplexität der PDF-Textkodierung und -positionierung:

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);
        }
    }
}
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);
        }
    }
}
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
$vbLabelText   $csharpLabel

Die seitenweise Extraktion ist besonders nützlich für mehrseitige Rechnungen, bei denen Sie bestimmte Abschnitte finden müssen, z. B. bei der Suche nach Positionen, die sich über mehrere Seiten erstrecken, während die Kopfdaten nur auf der ersten Seite erscheinen.

Wie man Tabellendaten für Positionen extrahiert

Die Rechnungsposten erscheinen in der Regel in Tabellenform. PDFs haben keine native Tabellenstruktur, aber Sie können Text extrahieren und analysieren, um Tabellendaten zu rekonstruieren:

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;
    }
}
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;
    }
}
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
$vbLabelText   $csharpLabel

Die Parsing-Logik wird je nach Ihren Rechnungsformaten variieren. Für Rechnungen mit einheitlichen Layouts von bekannten Anbietern können Sie formatspezifische Parser erstellen. Für unterschiedliche Formate bietet sich die KI-gestützte Extraktion an, die weiter unten in diesem Artikel beschrieben wird.

Wie man Pattern Matching für Rechnungsnummern, Daten und Summen verwendet

Reguläre Ausdrücke sind von unschätzbarem Wert, wenn es darum geht, bestimmte Datenpunkte aus Rechnungstext zu extrahieren. Schlüsselfelder wie Rechnungsnummern, Daten und Summen folgen oft erkennbaren Mustern:

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;
    }
}
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;
    }
}
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
$vbLabelText   $csharpLabel

Dieser musterbasierte Ansatz eignet sich gut für Rechnungen mit vorhersehbaren Formaten. Die zahlreichen Mustervariationen berücksichtigen gängige Formatierungsunterschiede zwischen verschiedenen Anbietern, wie z. B. "Invoice #" und "Invoice Number:"

Was ist mit gescannten oder bildbasierten Rechnungen?

Die oben gezeigten Textextraktionsmethoden funktionieren mit PDFs, die eingebetteten Text enthalten. Gescannte Dokumente und bildbasierte PDFs haben jedoch keinen extrahierbaren Text. Es handelt sich im Wesentlichen um Bilder von Rechnungen.

Hinweis:Für die Verarbeitung gescannter Rechnungen benötigen Sie OCR-Fähigkeiten (Optical Character Recognition). IronOCR, Teil der Iron Suite, lässt sich für diese Szenarien nahtlos in IronPDF integrieren. Besuchen Sie https://ironsoftware.com/csharp/ocr/, um mehr über die Extraktion von Text aus gescannten Dokumenten und Bildern zu erfahren.


Wie man KI zur Verarbeitung von Rechnungen in .NET verwendet

Der herkömmliche Musterabgleich funktioniert gut für standardisierte Rechnungen, aber in der Praxis erhalten die Kreditorenbuchhaltungen Dokumente in unzähligen Formaten. Hier kommt die KI-gestützte Extraktion zum Tragen. Große Sprachmodelle können die Rechnungssemantik verstehen und strukturierte Daten auch aus unbekannten Layouts extrahieren.

Integration von KI für das Parsen von Rechnungen

Das Muster für die KI-gestützte Rechnungsverarbeitung kombiniert die Textextraktion von IronPDF mit LLM-API-Aufrufen. Hier ist eine generische Implementierung, die mit jeder OpenAI-kompatiblen API funktioniert:

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;
    }
}
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;
    }
}
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
$vbLabelText   $csharpLabel

Die niedrige Temperatureinstellung (0,1) fördert deterministische Ausgaben, was für Datenextraktionsaufgaben wichtig ist, bei denen Sie konsistente Ergebnisse für dieselbe Eingabe wünschen.

Wie man strukturierte JSON-Daten aus Rechnungen extrahiert

Für komplexere Rechnungen mit Einzelposten, Lieferantendetails und Kundeninformationen können Sie eine umfangreichere JSON-Struktur anfordern:

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
    }
}
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
    }
}
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
$vbLabelText   $csharpLabel

Wie man mit inkonsistenten Rechnungsformaten umgeht

Die wahre Stärke der KI-Extraktion zeigt sich bei der Verarbeitung von Rechnungen mehrerer Anbieter, die jeweils eigene Formate haben. Ein intelligenter Prozessor kann zunächst eine musterbasierte Extraktion versuchen (schneller und kostenlos) und nur bei Bedarf auf KI zurückgreifen:

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;
    }
}
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;
    }
}
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
$vbLabelText   $csharpLabel

Wie man eine Pipeline zur Automatisierung der Kreditorenbuchhaltung aufbaut

Wenn Sie all diese Teile zusammenbringen, erhalten Sie eine vollständige Automatisierungspipeline, die eingehende Rechnungen verarbeitet, Daten extrahiert, validiert und für Ihr Buchhaltungssystem aufbereitet:

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}");
            }
        }
    }
}
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}");
            }
        }
    }
}
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
$vbLabelText   $csharpLabel

Diese Pipeline implementiert einen vollständigen Arbeitsablauf: Sie durchsucht einen Ordner nach eingehenden PDFs, verarbeitet jede einzelne, validiert die extrahierten Daten, leitet erfolgreiche Extraktionen an Ihr Buchhaltungssystem weiter und stellt fehlgeschlagene Extraktionen zur manuellen Überprüfung in Quarantäne. Der zusammenfassende Bericht gibt einen Überblick über die Verarbeitungsergebnisse.


Integration von C# Rechnungsverarbeitung mit Buchhaltungssystemen

Die extrahierten Rechnungsdaten müssen schließlich in die Buchhaltungssysteme für die Zahlung und Buchführung einfließen. Die Spezifika variieren je nach Plattform, aber die Integrationsmuster sind einheitlich.

Was sind gemeinsame Integrationsmuster für QuickBooks, Xero und SAP?

Die meisten Buchhaltungsplattformen bieten REST-APIs zur programmgesteuerten Erstellung von Rechnungen an. Hier ist ein allgemeines Muster, das Sie für Ihre spezifische Plattform anpassen können:

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}");
    }
}
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}");
    }
}
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
$vbLabelText   $csharpLabel

Jede Plattform hat ihren eigenen Authentifizierungsmechanismus (OAuth für QuickBooks und Xero, verschiedene Methoden für SAP), erforderliche Felder und API-Konventionen. Konsultieren Sie die Dokumentation Ihrer Zielplattform, um Einzelheiten zu erfahren, aber das Muster der Umwandlung extrahierter Rechnungsdaten in API-Payloads bleibt gleich.

Wie man Hunderte von Rechnungen im Stapel verarbeitet

Die Verarbeitung großer Rechnungsmengen erfordert eine sorgfältige Beachtung von Gleichzeitigkeit und Ressourcenmanagement. Hier ist ein Muster, das Parallelverarbeitung mit kontrollierter Gleichzeitigkeit verwendet:

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
            };
        }
    }
}
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
            };
        }
    }
}
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
$vbLabelText   $csharpLabel

Der SemaphoreSlim sorgt dafür, dass Sie externe APIs nicht überfordern oder Systemressourcen erschöpfen. Passen Sie _maxConcurrency an die Grenzen Ihrer API-Rate und Serverkapazität an. Die ConcurrentBag sammelt sicher die Ergebnisse von parallelen Operationen.


Nächste Schritte

Die Automatisierung von Rechnungen stellt eine große Chance dar, manuelle Arbeit zu reduzieren, Fehler zu minimieren und Geschäftsprozesse zu beschleunigen. Dieser Leitfaden führt Sie durch den gesamten Lebenszyklus: erstellung professioneller Rechnungen aus HTML-Vorlagen unter Einhaltung der ZUGFeRD und Factur-X Standards für die elektronische Rechnungsstellung, Extrahieren von Daten aus empfangenen Rechnungen unter Verwendung von Mustervergleichen und AI-powered processing sowie der Aufbau skalierbarer Automatisierungspipelines.

IronPDF dient als Grundlage für diese Fähigkeiten, indem es ein robustes HTML-zu-PDF-Rendering, eine zuverlässige Textextraktion und die für die PDF/A-3 e-invoicing compliance erforderlichen Anhangsfunktionen bietet. Die Chrome-basierte Rendering-Engine sorgt dafür, dass Ihre Rechnungen genau so aussehen, wie sie entworfen wurden, während die Extraktionsmethoden die Komplexität der PDF-Textkodierung automatisch bewältigen.

Die hier gezeigten Muster sind Ausgangspunkte. Reale Implementierungen müssen für Ihre spezifischen Rechnungsformate, Buchhaltungssysteme und Geschäftsregeln angepasst werden. Das Tutorial zur Stapelverarbeitung behandelt die parallele Ausführung mit kontrollierter Gleichzeitigkeit und Fehlerbehebung für Szenarien mit hohem Datenaufkommen.

Bereit, loszulegen? Laden Sie IronPDF herunter und probieren Sie es mit einer kostenlosen Testversion aus. Die Bibliothek enthält eine kostenlose Entwicklungslizenz, so dass Sie die Rechnungserstellung, die Datenextraktion und die PDF-Berichtsfunktionen umfassend testen können, bevor Sie sich für eine Produktionslizenz entscheiden. Wenn Sie Fragen zur Rechnungsautomatisierung oder zur Integration von Buchhaltungssystemen haben, wenden Sie sich an unser technisches Support-Team.

Häufig gestellte Fragen

Wofür wird IronPDF in der C#-Rechnungsverarbeitung verwendet?

IronPDF wird in der C#-Rechnungsverarbeitung eingesetzt, um professionelle PDF-Rechnungen zu generieren, strukturierte Daten zu extrahieren und Rechnungs-Workflows zu automatisieren und dabei die Einhaltung von Standards wie ZUGFeRD und Factur-X zu gewährleisten.

Wie kann ich eine PDF-Rechnung mit IronPDF in C# erstellen?

Sie können eine PDF-Rechnung mit IronPDF in C# generieren, indem Sie die API nutzen, um PDF-Dokumente programmatisch zu erstellen und anzupassen. Dazu gehört das Hinzufügen von Elementen wie Text, Tabellen und Bildern, die eine Rechnung ausmachen.

Was sind ZUGFeRD und Factur-X, und wie unterstützt IronPDF sie?

ZUGFeRD und Factur-X sind Standards für die elektronische Rechnungsstellung, die sicherstellen, dass Rechnungen sowohl menschenlesbar als auch maschinenlesbar sind. IronPDF unterstützt diese Standards, indem es Ihnen ermöglicht, PDF-Rechnungen zu erstellen, die diesen Spezifikationen entsprechen.

Wie kann IronPDF bei der Automatisierung von Kreditorenprozessen helfen?

IronPDF kann Kreditorenbuchhaltungsprozesse automatisieren, indem es strukturierte Daten aus Rechnungen extrahiert und in Automatisierungspipelines integriert, wodurch die manuelle Dateneingabe reduziert und die Effizienz verbessert wird.

Kann IronPDF Daten aus bestehenden PDF-Rechnungen extrahieren?

Ja, IronPDF kann strukturierte Daten aus bestehenden PDF-Rechnungen extrahieren und erleichtert so die automatische Verarbeitung und Analyse von Rechnungsinformationen.

Welche Vorteile bietet die Verwendung von IronPDF für die Rechnungsverarbeitung in C#?

Zu den Vorteilen des Einsatzes von IronPDF für die Rechnungsverarbeitung in C# gehören eine optimierte Rechnungserstellung, die Einhaltung internationaler Rechnungsstellungsstandards, eine effiziente Datenextraktion und verbesserte Automatisierungsfunktionen.

Ist es möglich, das Erscheinungsbild einer PDF-Rechnung mit IronPDF individuell zu gestalten?

Ja, IronPDF ermöglicht es Ihnen, das Erscheinungsbild einer PDF-Rechnung anzupassen, indem Sie verschiedene Designelemente wie Logos, Textformatierungen und Layoutanpassungen hinzufügen, um die Anforderungen an das Branding zu erfüllen.

Was sind die typischen Schritte zur Automatisierung der Rechnungsverarbeitung mit IronPDF?

Um die Rechnungsverarbeitung mit IronPDF zu automatisieren, generieren Sie in der Regel die Rechnung, extrahieren die erforderlichen Daten und integrieren sie in andere Systeme oder Automatisierungswerkzeuge, um die Arbeitsabläufe zu optimieren.

Wie geht IronPDF mit verschiedenen Rechnungsformaten um?

IronPDF kann mit verschiedenen Rechnungsformaten umgehen, indem es Werkzeuge zum Erzeugen, Bearbeiten und Lesen von PDF-Dokumenten bereitstellt und so die Kompatibilität mit gängigen E-Invoicing-Standards gewährleistet.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen
Bereit anzufangen?
Nuget Downloads 17,386,124 | Version: 2026.2 gerade veröffentlicht