發票 OCR API 開發者教學
發票 OCR API 利用機器學習自動化發票資料擷取,消除手動輸入錯誤,同時精確擷取供應商資訊、發票號碼及價格,無論是數位或掃描文件皆適用。本教學將示範如何使用 IronOCR 建立發票 OCR 解決方案。
透過機器學習與電腦視覺,發票 OCR 技術可將發票資料轉換為可自動處理的格式。您將學會如何解決常見挑戰,如手動資料輸入延遲、成本與錯誤,同時精確擷取任何格式發票中的供應商資訊、發票號碼及價格。
本文使用 IronOCR,這是 .NET 開發人員首選的發票 OCR API。
如何建立發票 OCR API
- 下載並安裝發票 OCR API
- 在 Visual Studio 建立新的 C# 專案,或開啟現有專案。
- 使用
方法載入現有影像檔案OcrInput - 使用
Ocr.Read方法從影像中擷取文字。 - 使用
Console.在主控台列印擷取的文字WriteLine
什麼是 IronOCR?
IronOCR 由 Iron Software 開發,為開發人員提供完整的 OCR 工具。它運用機器學習與電腦視覺,從掃描文件、影像及 PDF 中擷取文字,實現自動化處理。其 API 能無縫整合至多種語言與平台,減少手動資料輸入錯誤並提升效率。擷取的資料可直接流入現有系統進行分析與決策。像是影像預處理、條碼辨識及彈性檔案解析等功能,進一步提升其多元應用性。IronOCR 讓開發人員能將強大的文字辨識功能整合至應用程式中。
該函式庫支援125 種國際語言,透過專用語言包,非常適合全球發票處理。進階功能包括自動以電腦視覺尋找文字,對於版面多變的發票特別實用。此外,IronOCR 也提供多執行緒處理能力,能有效處理大量發票。
為什麼我應該使用 IronOCR 進行發票處理?
IronOCR 為發票處理應用程式提供了極具吸引力的優勢。首先,它透過專為 .NET 應用程式優化的 Tesseract 5 引擎 ,提供卓越的準確度。該函式庫能處理各種發票格式,從掃描文件、PDF 檔案,甚至是低品質掃描件。
內建的影像優化濾鏡會在處理前自動提升影像品質,從而獲得更準確的文字擷取效果。對於有特殊需求的發票,IronOCR 支援自訂語言訓練,可針對您常見的發票字型或格式進行最佳化。
IronOCR 與其他 OCR 函式庫有何不同?
IronOCR 以簡單的一行 OCR 功能脫穎而出,同時保有企業級功能。與原生 Tesseract 實作不同,IronOCR 提供受控的 .NET API,能無縫處理複雜操作。該函式庫提供專業的文件讀取方法,適用於各種文件類型,並特別支援讀取文件中的表格,這對發票明細項目至關重要。
Filter Wizard 會自動判斷最適合您發票影像的預處理設定,省去優化時的猜測。IronOCR 也提供完整的除錯功能,讓開發人員能視覺化 OCR 引擎所見,有效排查擷取問題。
我需要哪些先決條件?
在使用 IronOCR 前,請確保具備以下先決條件:
- 已安裝如 Visual Studio 等 IDE 的合適開發環境
- 具備 C# 程式設計的基本知識,以便有效理解與修改程式範例
- 透過 NuGet 套件管理器或命令列,已將 IronOCR 函式庫安裝至您的專案中
滿足這些先決條件後,您就能順利開始使用 IronOCR。
IronOCR 提供Windows、Linux 和 macOS 的完整安裝指南。該函式庫支援雲端部署,並針對 AWS Lambda 和 Azure Functions 提供專屬教學。
我應該使用哪個版本的 Visual Studio?
IronOCR 支援從 2017 年到最新版本的 Visual Studio。為了獲得最佳相容性及存取最新 C# 功能,建議使用 Visual Studio 2019 或 2022。此函式庫完全相容於.NET Framework、.NET Core 及 .NET 5+,確保您的開發環境具備彈性。
若需跨平台開發,可搭配 C# 擴充套件使用 Visual Studio Code。行動開發者可參考 IronOCR 提供的Android及iOS實作指引,非常適合用於.NET MAUI 應用程式。
我需要什麼程度的 C# 知識?
具備中階 C# 知識即可完成基本發票 OCR 實作。您應該熟悉:
- 物件導向程式設計概念
- 操作串流與檔案 I/O
- 基本的async/await 模式
- 使用正則表達式進行模式比對
- 例外處理以強化錯誤管理
IronOCR 直覺化的 API 設計,讓您無需深入影像處理或機器學習專業知識。函式庫會自動處理複雜運算,讓您專注於商業邏輯。初學者可從簡單的 OCR 範例開始。
如何建立新的 Visual Studio 專案?
要開始使用 IronOCR,請先建立一個新的 Visual Studio 專案。
開啟 Visual Studio,點選「檔案」,將滑鼠移至「新增」,然後點選「專案」。
新增專案
在新視窗中,選擇「主控台應用程式」並點選「下一步」。
主控台應用程式
會出現新視窗。輸入您的專案名稱與位置,然後點選「下一步」。
專案設定
最後,選擇目標框架並點選「建立」。
目標框架
您的新 Visual Studio 專案已準備就緒。接下來讓我們安裝 IronOCR。
哪種專案類型最適合 OCR 應用程式?
雖然本教學為簡單起見採用主控台應用程式,IronOCR 支援多種專案類型:
- 主控台應用程式: 適合批次處理或命令列工具
- 網頁應用程式: 非常適合建立 API 或網頁服務
- Windows Forms/WPF: 適用於具有 GUI 的桌面應用程式
- .NET MAUI 應用程式: 用於跨平台解決方案
若需大量處理,建議在 Windows 服務或微服務架構中實作 IronOCR。該函式庫的進度追蹤功能讓監控長時間執行的作業變得容易。
我應該選擇哪個 .NET Framework 版本?
IronOCR 提供廣泛的 .NET 版本相容性。新專案建議以 .NET 6.0 或更高版本為目標,以獲得最佳效能與最新功能。該函式庫同時維持極佳的向下相容性:
- .NET Framework 4.6.2+: 適用於舊有企業應用程式
- .NET Core 3.1: 穩定部署的長期支援版本
- .NET 5.0+: 具備效能提升的現代化框架
- .NET Standard 2.0: 跨平台最大相容性
部署至 Docker 容器時,.NET 6.0 或更新版本可提供更小的映像檔與更佳效能。針對 Azure Functions,.NET 6.0 與 .NET Framework 均受支援。
如何安裝 IronOCR?
有兩種簡單方法可下載並安裝 IronOCR:
- 使用 Visual Studio NuGet 套件管理員
- 使用 Visual Studio 命令列
什麼時候該用 NuGet 套件管理員,什麼時候該用命令列?
可依您的工作流程選擇 NuGet 套件管理員 GUI 或命令列:
NuGet 套件管理員 GUI 最適合以下情境:
- 您是 NuGet 套件新手
- 您想瀏覽 IronOCR 語言包
- 您偏好視覺化確認
- 您需管理多個套件
命令列(套件管理員主控台) 適合以下情境:
- 您熟悉命令介面
- 您採用腳本化部署
- 您需快速取得特定版本
- 您使用進階安裝選項
兩種方法效果完全相同——請依您的習慣與需求選擇。
我可能需要哪些額外語言包?
IronOCR 透過專用語言包支援125 種國際語言。針對發票處理,建議考慮:
語言包會與主 IronOCR 套件一同安裝,對於非英文文字能大幅提升辨識準確度。
使用 Visual Studio NuGet 套件管理員
使用 Visual Studio NuGet 套件管理員將 IronOCR 加入您的 C# 專案。
前往 工具 > NuGet 套件管理員 > 管理方案的 NuGet 套件
NuGet 套件管理員
搜尋 IronOCR 並在您的專案中安裝此套件。
在 NuGet 套件管理員 UI 中選擇 IronOCR 套件
可用相同方式安裝其他語言包。
使用 Visual Studio 命令列
-
在 Visual Studio 中,前往 工具 > NuGet 套件管理員 > 套件管理員主控台
-
在套件管理員主控台輸入以下指令:
套件管理員主控台
套件將下載並安裝至您目前的專案,隨時可用。
如何使用 IronOCR 從發票中擷取資料?
只需幾行程式碼,即可利用 IronOCR 輕鬆擷取發票資料。這取代了手動輸入資料,讓您的工作流程更有效率。
以下是一份用於文字擷取的發票範例:
發票範例
讓我們從這張發票中擷取所有資料:
using IronOcr;
using System;
// Initialize a new instance of the IronTesseract class
// This is the main OCR engine that will process our invoice
var ocr = new IronTesseract();
// Configure OCR settings for better invoice processing
ocr.Configuration.BlackListCharacters = "~`$#^*_}{]";Imports IronOcr
Imports System
' Initialize a new instance of the IronTesseract class
' This is the main OCR engine that will process our invoice
Dim ocr = New IronTesseract()
' Configure OCR settings for better invoice processing
ocr.Configuration.BlackListCharacters = "~`$#^*_}{]"Imports IronOcr
Imports System
' Initialize a new instance of the IronTesseract class
' This is the main OCR engine that will process our invoice
Dim ocr = New IronTesseract()
' Configure OCR settings for better invoice processing
ocr.Configuration.BlackListCharacters = "~`$#^*_}{]"此範例呼叫 Read 方法,來自 IronTesseract 類別。主要強化功能包括:

發票解析器
我如何處理不同的發票格式?
發票格式因供應商而異,但 IronOCR 提供靈活的解決方案:
對於複雜的版面,建議實作文件版面分析流程,利用機器學習自動識別結構。
發票資料常見的擷取模式有哪些?
發票資料通常有可辨識的模式,可結合正則表達式與 OCR 結果進行擷取:
using IronOCR;
using System;
using System.Text.`RegularExpressions`;
using System.Collections.Generic;
public class `InvoiceDataExtractor`
{
private readonly `IronTesseract` ocr;
public `InvoiceDataExtractor`()
{
ocr = new `IronTesseract`();
// Configure for optimal invoice reading
`ocr.Configuration`.`ReadBarcodes` = true; // Many invoices include barcodes
`ocr.Configuration`.`TesseractVersion` = `TesseractVersion`.Tesseract5;
}
public `InvoiceData` `ExtractInvoiceData`(string imagePath)
{
var invoiceData = new `InvoiceData`();
using (var input = new `OcrInput`(imagePath/))
{
// Apply filters for better accuracy
input.`EnhanceResolution`(300/);
`input.Sharpen`();
var result = `ocr.Read`(input/);
var text = `result.Text`;
// Extract invoice number
invoiceData.`InvoiceNumber` = `ExtractPattern`(text,
@"INV[/-]?\d{4}[/-]?\d{5}|Invoice\s*#?\s*:?\s*(\d+)");
// Extract dates
invoiceData.`InvoiceDate` = `ExtractDate`(text,
@"Invoice\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
invoiceData.`DueDate` = `ExtractDate`(text,
@"Due\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
// Extract amounts
`invoiceData.Total` = `ExtractAmount`(text,
@"Total\s*:?\s*\$?\s*([\d,]+\.?\d*)");
`invoiceData.Tax` = `ExtractAmount`(text,
@"Tax\s*:?\s*\$?\s*([\d,]+\.?\d*)");
// Extract vendor information
invoiceData.`VendorName` = `ExtractVendorName`(text/);
// Extract line items using table detection
invoiceData.`LineItems` = `ExtractLineItems`(result/);
// Extract any barcodes found
if (`result.Barcodes`.Length > 0)
{
invoiceData.`BarcodeValues` = new List<string>();
foreach (var barcode in `result.Barcodes`)
{
invoiceData.`BarcodeValues`.Add(`barcode.Value`);
}
}
}
return invoiceData;
}
private string `ExtractPattern`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
return `match.Success` ? `match.Value` : `string.Empty`;
}
private `DateTime`? `ExtractDate`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
if (`DateTime`.`TryParse`(`match.Groups`[1].Value, out `DateTime` date))
return date;
}
return null;
}
private decimal `ExtractAmount`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
var amountStr = `match.Groups`[1].Value.Replace(",", "");
if (decimal.`TryParse`(amountStr, out decimal amount))
return amount;
}
return 0;
}
private string `ExtractVendorName`(string text)
{
// Usually the vendor name appears in the first few lines
var lines = `text.Split`('\n'/);
if (`lines.Length` > 0)
{
// Simple heuristic: first non-empty line that's not a common header
foreach (var line in lines)
{
var trimmed = `line.Trim`();
if (!string.`IsNullOrEmpty`(trimmed/) &&
!trimmed.`ToLower`().Contains("invoice") &&
`trimmed.Length` > 3)
{
return trimmed;
}
}
}
return `string.Empty`;
}
private List<`LineItem`> `ExtractLineItems`(`OcrResult` result)
{
var lineItems = new List<`LineItem`>();
// Use IronOCR's table detection capabilities
if (`result.Tables` != null && `result.Tables`.Count > 0)
{
foreach (var table in `result.Tables`)
{
// Process each row as a potential line item
for (int i = 1; i < table.`RowCount`; i++) // Skip header row
{
var item = new `LineItem`
{
Description = table[i, 0]?.Text ?? "",
Quantity = `ParseQuantity`(table[i, 1]?.Text),
`UnitPrice` = `ParseAmount`(table[i, 2]?.Text),
Total = `ParseAmount`(table[i, 3]?.Text)
};
if (!string.`IsNullOrEmpty`(`item.Description`/))
`lineItems.Add`(item/);
}
}
}
return lineItems;
}
private int `ParseQuantity`(string text)
{
if (string.`IsNullOrEmpty`(text/)) return 0;
var cleaned = Regex.Replace(text, @"[^\d]", "");
return int.`TryParse`(cleaned, out int qty) ? qty : 0;
}
private decimal `ParseAmount`(string text)
{
if (string.`IsNullOrEmpty`(text/)) return 0;
var cleaned = Regex.Replace(text, @"[^\d.]", "");
return decimal.`TryParse`(cleaned, out decimal amt) ? amt : 0;
}
}
// Data classes for structured invoice information
public class `InvoiceData`
{
public string `InvoiceNumber` { get; set; }
public `DateTime`? `InvoiceDate` { get; set; }
public `DateTime`? `DueDate` { get; set; }
public string `VendorName` { get; set; }
public decimal Total { get; set; }
public decimal Tax { get; set; }
public List<`LineItem`> `LineItems` { get; set; }
public List<string> `BarcodeValues` { get; set; }
}
public class `LineItem`
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal `UnitPrice` { get; set; }
public decimal Total { get; set; }
}using IronOCR;
using System;
using System.Text.`RegularExpressions`;
using System.Collections.Generic;
public class `InvoiceDataExtractor`
{
private readonly `IronTesseract` ocr;
public `InvoiceDataExtractor`()
{
ocr = new `IronTesseract`();
// Configure for optimal invoice reading
`ocr.Configuration`.`ReadBarcodes` = true; // Many invoices include barcodes
`ocr.Configuration`.`TesseractVersion` = `TesseractVersion`.Tesseract5;
}
public `InvoiceData` `ExtractInvoiceData`(string imagePath)
{
var invoiceData = new `InvoiceData`();
using (var input = new `OcrInput`(imagePath/))
{
// Apply filters for better accuracy
input.`EnhanceResolution`(300/);
`input.Sharpen`();
var result = `ocr.Read`(input/);
var text = `result.Text`;
// Extract invoice number
invoiceData.`InvoiceNumber` = `ExtractPattern`(text,
@"INV[/-]?\d{4}[/-]?\d{5}|Invoice\s*#?\s*:?\s*(\d+)");
// Extract dates
invoiceData.`InvoiceDate` = `ExtractDate`(text,
@"Invoice\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
invoiceData.`DueDate` = `ExtractDate`(text,
@"Due\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
// Extract amounts
`invoiceData.Total` = `ExtractAmount`(text,
@"Total\s*:?\s*\$?\s*([\d,]+\.?\d*)");
`invoiceData.Tax` = `ExtractAmount`(text,
@"Tax\s*:?\s*\$?\s*([\d,]+\.?\d*)");
// Extract vendor information
invoiceData.`VendorName` = `ExtractVendorName`(text/);
// Extract line items using table detection
invoiceData.`LineItems` = `ExtractLineItems`(result/);
// Extract any barcodes found
if (`result.Barcodes`.Length > 0)
{
invoiceData.`BarcodeValues` = new List<string>();
foreach (var barcode in `result.Barcodes`)
{
invoiceData.`BarcodeValues`.Add(`barcode.Value`);
}
}
}
return invoiceData;
}
private string `ExtractPattern`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
return `match.Success` ? `match.Value` : `string.Empty`;
}
private `DateTime`? `ExtractDate`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
if (`DateTime`.`TryParse`(`match.Groups`[1].Value, out `DateTime` date))
return date;
}
return null;
}
private decimal `ExtractAmount`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
var amountStr = `match.Groups`[1].Value.Replace(",", "");
if (decimal.`TryParse`(amountStr, out decimal amount))
return amount;
}
return 0;
}
private string `ExtractVendorName`(string text)
{
// Usually the vendor name appears in the first few lines
var lines = `text.Split`('\n'/);
if (`lines.Length` > 0)
{
// Simple heuristic: first non-empty line that's not a common header
foreach (var line in lines)
{
var trimmed = `line.Trim`();
if (!string.`IsNullOrEmpty`(trimmed/) &&
!trimmed.`ToLower`().Contains("invoice") &&
`trimmed.Length` > 3)
{
return trimmed;
}
}
}
return `string.Empty`;
}
private List<`LineItem`> `ExtractLineItems`(`OcrResult` result)
{
var lineItems = new List<`LineItem`>();
// Use IronOCR's table detection capabilities
if (`result.Tables` != null && `result.Tables`.Count > 0)
{
foreach (var table in `result.Tables`)
{
// Process each row as a potential line item
for (int i = 1; i < table.`RowCount`; i++) // Skip header row
{
var item = new `LineItem`
{
Description = table[i, 0]?.Text ?? "",
Quantity = `ParseQuantity`(table[i, 1]?.Text),
`UnitPrice` = `ParseAmount`(table[i, 2]?.Text),
Total = `ParseAmount`(table[i, 3]?.Text)
};
if (!string.`IsNullOrEmpty`(`item.Description`/))
`lineItems.Add`(item/);
}
}
}
return lineItems;
}
private int `ParseQuantity`(string text)
{
if (string.`IsNullOrEmpty`(text/)) return 0;
var cleaned = Regex.Replace(text, @"[^\d]", "");
return int.`TryParse`(cleaned, out int qty) ? qty : 0;
}
private decimal `ParseAmount`(string text)
{
if (string.`IsNullOrEmpty`(text/)) return 0;
var cleaned = Regex.Replace(text, @"[^\d.]", "");
return decimal.`TryParse`(cleaned, out decimal amt) ? amt : 0;
}
}
// Data classes for structured invoice information
public class `InvoiceData`
{
public string `InvoiceNumber` { get; set; }
public `DateTime`? `InvoiceDate` { get; set; }
public `DateTime`? `DueDate` { get; set; }
public string `VendorName` { get; set; }
public decimal Total { get; set; }
public decimal Tax { get; set; }
public List<`LineItem`> `LineItems` { get; set; }
public List<string> `BarcodeValues` { get; set; }
}
public class `LineItem`
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal `UnitPrice` { get; set; }
public decimal Total { get; set; }
}Imports IronOcr
Imports System
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Public Class InvoiceDataExtractor
Private ReadOnly ocr As IronTesseract
Public Sub New()
ocr = New IronTesseract()
' Configure for optimal invoice reading
ocr.Configuration.ReadBarcodes = True ' Many invoices include barcodes
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
End Sub
Public Function ExtractInvoiceData(imagePath As String) As InvoiceData
Dim invoiceData As New InvoiceData()
Using input = New OcrInput(imagePath)
' Apply filters for better accuracy
input.EnhanceResolution(300)
input.Sharpen()
Dim result = ocr.Read(input)
Dim text = result.Text
' Extract invoice number
invoiceData.InvoiceNumber = ExtractPattern(text,
"INV[/-]?\d{4}[/-]?\d{5}|Invoice\s*#?\s*:?\s*(\d+)")
' Extract dates
invoiceData.InvoiceDate = ExtractDate(text,
"Invoice\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})")
invoiceData.DueDate = ExtractDate(text,
"Due\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})")
' Extract amounts
invoiceData.Total = ExtractAmount(text,
"Total\s*:?\s*\$?\s*([\d,]+\.?\d*)")
invoiceData.Tax = ExtractAmount(text,
"Tax\s*:?\s*\$?\s*([\d,]+\.?\d*)")
' Extract vendor information
invoiceData.VendorName = ExtractVendorName(text)
' Extract line items using table detection
invoiceData.LineItems = ExtractLineItems(result)
' Extract any barcodes found
If result.Barcodes.Length > 0 Then
invoiceData.BarcodeValues = New List(Of String)()
For Each barcode In result.Barcodes
invoiceData.BarcodeValues.Add(barcode.Value)
Next
End If
End Using
Return invoiceData
End Function
Private Function ExtractPattern(text As String, pattern As String) As String
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
Return If(match.Success, match.Value, String.Empty)
End Function
Private Function ExtractDate(text As String, pattern As String) As DateTime?
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success AndAlso match.Groups.Count > 1 Then
Dim dateResult As DateTime
If DateTime.TryParse(match.Groups(1).Value, dateResult) Then
Return dateResult
End If
End If
Return Nothing
End Function
Private Function ExtractAmount(text As String, pattern As String) As Decimal
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success AndAlso match.Groups.Count > 1 Then
Dim amountStr = match.Groups(1).Value.Replace(",", "")
Dim amount As Decimal
If Decimal.TryParse(amountStr, amount) Then
Return amount
End If
End If
Return 0
End Function
Private Function ExtractVendorName(text As String) As String
' Usually the vendor name appears in the first few lines
Dim lines = text.Split(ControlChars.Lf)
If lines.Length > 0 Then
' Simple heuristic: first non-empty line that's not a common header
For Each line In lines
Dim trimmed = line.Trim()
If Not String.IsNullOrEmpty(trimmed) AndAlso
Not trimmed.ToLower().Contains("invoice") AndAlso
trimmed.Length > 3 Then
Return trimmed
End If
Next
End If
Return String.Empty
End Function
Private Function ExtractLineItems(result As OcrResult) As List(Of LineItem)
Dim lineItems As New List(Of LineItem)()
' Use IronOCR's table detection capabilities
If result.Tables IsNot Nothing AndAlso result.Tables.Count > 0 Then
For Each table In result.Tables
' Process each row as a potential line item
For i As Integer = 1 To table.RowCount - 1 ' Skip header row
Dim item As New LineItem With {
.Description = If(table(i, 0)?.Text, ""),
.Quantity = ParseQuantity(table(i, 1)?.Text),
.UnitPrice = ParseAmount(table(i, 2)?.Text),
.Total = ParseAmount(table(i, 3)?.Text)
}
If Not String.IsNullOrEmpty(item.Description) Then
lineItems.Add(item)
End If
Next
Next
End If
Return lineItems
End Function
Private Function ParseQuantity(text As String) As Integer
If String.IsNullOrEmpty(text) Then Return 0
Dim cleaned = Regex.Replace(text, "[^\d]", "")
Dim qty As Integer
Return If(Integer.TryParse(cleaned, qty), qty, 0)
End Function
Private Function ParseAmount(text As String) As Decimal
If String.IsNullOrEmpty(text) Then Return 0
Dim cleaned = Regex.Replace(text, "[^\d.]", "")
Dim amt As Decimal
Return If(Decimal.TryParse(cleaned, amt), amt, 0)
End Function
End Class
' Data classes for structured invoice information
Public Class InvoiceData
Public Property InvoiceNumber As String
Public Property InvoiceDate As DateTime?
Public Property DueDate As DateTime?
Public Property VendorName As String
Public Property Total As Decimal
Public Property Tax As Decimal
Public Property LineItems As List(Of LineItem)
Public Property BarcodeValues As List(Of String)
End Class
Public Class LineItem
Public Property Description As String
Public Property Quantity As Integer
Public Property UnitPrice As Decimal
Public Property Total As Decimal
End ClassImports IronOcr
Imports System
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Public Class InvoiceDataExtractor
Private ReadOnly ocr As IronTesseract
Public Sub New()
ocr = New IronTesseract()
' Configure for optimal invoice reading
ocr.Configuration.ReadBarcodes = True ' Many invoices include barcodes
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
End Sub
Public Function ExtractInvoiceData(imagePath As String) As InvoiceData
Dim invoiceData As New InvoiceData()
Using input = New OcrInput(imagePath)
' Apply filters for better accuracy
input.EnhanceResolution(300)
input.Sharpen()
Dim result = ocr.Read(input)
Dim text = result.Text
' Extract invoice number
invoiceData.InvoiceNumber = ExtractPattern(text,
"INV[/-]?\d{4}[/-]?\d{5}|Invoice\s*#?\s*:?\s*(\d+)")
' Extract dates
invoiceData.InvoiceDate = ExtractDate(text,
"Invoice\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})")
invoiceData.DueDate = ExtractDate(text,
"Due\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})")
' Extract amounts
invoiceData.Total = ExtractAmount(text,
"Total\s*:?\s*\$?\s*([\d,]+\.?\d*)")
invoiceData.Tax = ExtractAmount(text,
"Tax\s*:?\s*\$?\s*([\d,]+\.?\d*)")
' Extract vendor information
invoiceData.VendorName = ExtractVendorName(text)
' Extract line items using table detection
invoiceData.LineItems = ExtractLineItems(result)
' Extract any barcodes found
If result.Barcodes.Length > 0 Then
invoiceData.BarcodeValues = New List(Of String)()
For Each barcode In result.Barcodes
invoiceData.BarcodeValues.Add(barcode.Value)
Next
End If
End Using
Return invoiceData
End Function
Private Function ExtractPattern(text As String, pattern As String) As String
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
Return If(match.Success, match.Value, String.Empty)
End Function
Private Function ExtractDate(text As String, pattern As String) As DateTime?
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success AndAlso match.Groups.Count > 1 Then
Dim dateResult As DateTime
If DateTime.TryParse(match.Groups(1).Value, dateResult) Then
Return dateResult
End If
End If
Return Nothing
End Function
Private Function ExtractAmount(text As String, pattern As String) As Decimal
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success AndAlso match.Groups.Count > 1 Then
Dim amountStr = match.Groups(1).Value.Replace(",", "")
Dim amount As Decimal
If Decimal.TryParse(amountStr, amount) Then
Return amount
End If
End If
Return 0
End Function
Private Function ExtractVendorName(text As String) As String
' Usually the vendor name appears in the first few lines
Dim lines = text.Split(ControlChars.Lf)
If lines.Length > 0 Then
' Simple heuristic: first non-empty line that's not a common header
For Each line In lines
Dim trimmed = line.Trim()
If Not String.IsNullOrEmpty(trimmed) AndAlso
Not trimmed.ToLower().Contains("invoice") AndAlso
trimmed.Length > 3 Then
Return trimmed
End If
Next
End If
Return String.Empty
End Function
Private Function ExtractLineItems(result As OcrResult) As List(Of LineItem)
Dim lineItems As New List(Of LineItem)()
' Use IronOCR's table detection capabilities
If result.Tables IsNot Nothing AndAlso result.Tables.Count > 0 Then
For Each table In result.Tables
' Process each row as a potential line item
For i As Integer = 1 To table.RowCount - 1 ' Skip header row
Dim item As New LineItem With {
.Description = If(table(i, 0)?.Text, ""),
.Quantity = ParseQuantity(table(i, 1)?.Text),
.UnitPrice = ParseAmount(table(i, 2)?.Text),
.Total = ParseAmount(table(i, 3)?.Text)
}
If Not String.IsNullOrEmpty(item.Description) Then
lineItems.Add(item)
End If
Next
Next
End If
Return lineItems
End Function
Private Function ParseQuantity(text As String) As Integer
If String.IsNullOrEmpty(text) Then Return 0
Dim cleaned = Regex.Replace(text, "[^\d]", "")
Dim qty As Integer
Return If(Integer.TryParse(cleaned, qty), qty, 0)
End Function
Private Function ParseAmount(text As String) As Decimal
If String.IsNullOrEmpty(text) Then Return 0
Dim cleaned = Regex.Replace(text, "[^\d.]", "")
Dim amt As Decimal
Return If(Decimal.TryParse(cleaned, amt), amt, 0)
End Function
End Class
' Data classes for structured invoice information
Public Class InvoiceData
Public Property InvoiceNumber As String
Public Property InvoiceDate As DateTime?
Public Property DueDate As DateTime?
Public Property VendorName As String
Public Property Total As Decimal
Public Property Tax As Decimal
Public Property LineItems As List(Of LineItem)
Public Property BarcodeValues As List(Of String)
End Class
Public Class LineItem
Public Property Description As String
Public Property Quantity As Integer
Public Property UnitPrice As Decimal
Public Property Total As Decimal
End Class發票處理以擷取發票中的特定資料
使用以下程式碼擷取如客戶發票號碼等特定發票資料:
using IronOCR;
using System;
using System.Text.`RegularExpressions`;
// Initialize a new instance of the `IronTesseract` class
var ocr = new `IronTesseract`();
// Use the `OcrInput` object to load the image file
using (var input = new `OcrInput`(@"`r2.png`"/))
{
// Perform OCR on the image
var result = `ocr.Read`(input/);
// Define a regular expression pattern for the invoice number
var linePattern = @"INV\/\d{4}\/\d{5}";
// Match the pattern in the extracted text
var lineMatch = Regex.Match(`result.Text`, linePattern);
// Check if the pattern matches any part of the text
if (`lineMatch.Success`)
{
// If a match is found, print the invoice number
var lineValue = `lineMatch.Value`;
Console.`WriteLine`("Customer Invoice number: " + lineValue);
}
}using IronOCR;
using System;
using System.Text.`RegularExpressions`;
// Initialize a new instance of the `IronTesseract` class
var ocr = new `IronTesseract`();
// Use the `OcrInput` object to load the image file
using (var input = new `OcrInput`(@"`r2.png`"/))
{
// Perform OCR on the image
var result = `ocr.Read`(input/);
// Define a regular expression pattern for the invoice number
var linePattern = @"INV\/\d{4}\/\d{5}";
// Match the pattern in the extracted text
var lineMatch = Regex.Match(`result.Text`, linePattern);
// Check if the pattern matches any part of the text
if (`lineMatch.Success`)
{
// If a match is found, print the invoice number
var lineValue = `lineMatch.Value`;
Console.`WriteLine`("Customer Invoice number: " + lineValue);
}
}Imports IronOcr
Imports System
Imports System.Text.RegularExpressions
' Initialize a new instance of the `IronTesseract` class
Dim ocr = New IronTesseract()
' Use the `OcrInput` object to load the image file
Using input = New OcrInput("r2.png")
' Perform OCR on the image
Dim result = ocr.Read(input)
' Define a regular expression pattern for the invoice number
Dim linePattern = "INV/\d{4}/\d{5}"
' Match the pattern in the extracted text
Dim lineMatch = Regex.Match(result.Text, linePattern)
' Check if the pattern matches any part of the text
If lineMatch.Success Then
' If a match is found, print the invoice number
Dim lineValue = lineMatch.Value
Console.WriteLine("Customer Invoice number: " & lineValue)
End If
End UsingImports IronOcr
Imports System
Imports System.Text.RegularExpressions
' Initialize a new instance of the `IronTesseract` class
Dim ocr = New IronTesseract()
' Use the `OcrInput` object to load the image file
Using input = New OcrInput("r2.png")
' Perform OCR on the image
Dim result = ocr.Read(input)
' Define a regular expression pattern for the invoice number
Dim linePattern = "INV/\d{4}/\d{5}"
' Match the pattern in the extracted text
Dim lineMatch = Regex.Match(result.Text, linePattern)
' Check if the pattern matches any part of the text
If lineMatch.Success Then
' If a match is found, print the invoice number
Dim lineValue = lineMatch.Value
Console.WriteLine("Customer Invoice number: " & lineValue)
End If
End Using
發票掃描
針對複雜的擷取情境,可使用專用 OCR 設定來最佳化您的發票類型。OcrResult 類別提供每個辨識元素的詳細資訊,包括座標與信心分數,方便驗證。
發票 OCR API 的主要優勢是什麼?
IronOCR 的發票 OCR API 透過機器學習與電腦視覺革新發票處理。此技術將發票文字轉換為機器可讀格式,簡化資料擷取以利分析、整合與流程優化。它為發票處理帶來強大的自動化,提升準確度並優化如應付帳款等工作流程。
IronOCR 利用最佳化的 Tesseract 結果,無需額外設定即可提供卓越的準確率。它支援多頁框架 TIFF、PDF 檔案及所有主流影像格式。從影像讀取條碼更增添一層擷取維度。
發票處理的主要優勢:
此函式庫的部署彈性可輕鬆整合至現有系統——無論是地端、雲端或混合環境。支援Docker、Azure及AWS,IronOCR 能隨您的需求擴展。
生產環境受益於 IronOCR 的授權選項,包括專屬支援和定期更新。該函式庫的疑難排解指南和工程支援可確保順利實施。
請造訪首頁以取得更多有關 IronOCR 的資訊。如需更多發票 OCR 教學,請參閱這份詳細的發票 OCR 指南。若想了解如何使用電腦視覺辨識發票欄位,請參考這份電腦視覺教學。
相關文章
