IRONSOFTWAREHOME
USING IRONOCR

收據掃描 API:使用 C# 和 IronOCR 從收據中提取資料

Kannaopat Udonpant
Kannapat Udonpant
Updated: 2026年5月8日

收據掃描API使用OCR技術自動從收據中提取資料,顯著減少手動輸入錯誤並加速處理。 本指南展示如何使用C#中的IronOCR準確提取收據圖像中的供應商名稱、日期、項目、價格及總額,並內建圖片預處理及支持多種格式。

為何選擇IronOCR來進行收據掃描?

IronOCR是一個靈活的OCR程式庫,提供可靠的從掃描文件、圖片和PDF提取文字的功能。 憑藉先進的算法、計算機視覺和機器學習模型,IronOCR即使在複雜的情況下也能確保高準確率。 該程式庫支持多種語言和字體樣式,非常適合全球應用。 通過將IronOCR整合到您的應用程式中,您可以自動化資料輸入和文字分析,提升生產力。

IronOCR如何從收據圖像中提取文字?

IronOCR從文件、照片、截圖和即時攝像頭看到的內容中檢索文字,然後作為JSON響應返回。 使用先進的算法和機器學習,IronOCR分析圖像資料、識別字元,並將其轉換為機器可讀的文字。 該程式庫使用增強了專有改進的Tesseract 5技術,具有卓越的精確度。

為何IronOCR在處理收據上表現優越?

IronOCR擅長處理低品質掃描、多樣的收據格式和不同的方向。 內建的圖像預處理過濾器能在處理前自動改善圖像質量,確保即使是揉皺或褪色的收據也能得到最佳效果。

使用IronOCR需要做哪些準備?

在使用IronOCR之前,請確保這些先決條件已到位:

支持哪些開發環境?

  1. 開發環境:安裝如Visual Studio的合適IDE。 IronOCR supports Windows, Linux, macOS, Azure, and AWS.

需要哪些程式設計技能?

  1. C#知識:基本的C#了解可以幫助您修改程式碼範例。 IronOCR提供簡單的範例API文件

需要哪些軟體依賴?

  1. IronOCR安裝:通過NuGet包管理器安裝。 可能需要平台特定的依賴項。

是否需要授權金鑰?

  1. 授權金鑰(可選):提供免費試用; 生產環境使用需要授權

如何為收據掃描建立新的Visual Studio專案?

如何在Visual Studio中開始新專案?

打開Visual Studio並進入文件,然後懸停在新建上,點擊專案。

Visual Studio IDE的文件選單展開,顯示突出選中的'新建 > 專案'選項,並顯示載入Excel工作簿的C#程式碼 新專案圖像

我應該選擇哪個專案模板?

選擇控制台應用程式,然後點擊下一步。 此模板非常適合在實施到Web應用之前學習IronOCR。

Visual Studio的'建立新專案'對話框顯示選中的控制台應用程式模板及Windows, Linux和macOS的平臺選擇 控制台應用

我應該如何命名我的收據掃描器專案?

寫下您的專案名稱和位置,然後點擊下一步。 選擇一個描述性的名稱,如'ReceiptScannerAPI'。

Visual Studio新專案配置畫面,用於建立名為'IronOCR'的控制台應用程式,選擇了C#並顯示了解決方案設置 專案配置

我應選擇哪個版本的.NET Framework?

選擇.NET 5.0或更高版本以達到最佳相容性,然後單擊建立。

Visual Studio的'其他資訊'對話框顯示控制台應用程式配置,選擇.NET 5.0作為目標框架,並顯示Linux、macOS、Windows和控制台的平臺選擇 目標框架

如何在我的專案中安裝IronOCR?

提供兩種簡單的安裝方法:

如何使用NuGet包管理器方法?

前往工具 > NuGet包管理器 > 管理解決方案的NuGet包

Visual Studio NuGet包管理器設置對話框,帶有包源配置,以及解決方案資源管理器中的C#專案結構 NuGet套件管理器

搜索IronOCR並安裝該包。 對於非英文收據,安裝語言特定的包

Visual Studio中的NuGet包管理器顯示已安裝的IronOCR包,包括主要程式庫和阿拉伯語、希伯來語及西班牙語的OCR語言包 IronOCR

如何使用命令行安裝?

  1. 前往工具 > NuGet包管理器 > 包管理器控制台

  2. 輸入此命令:

    PM > Install-Package IronOcr

    Visual Studio包管理器控制台窗口顯示執行的NuGet命令'PM> Install-Package IronOcr',專案名稱為'Create PDF' 包管理器控制台

如何快速提取IronOCR的收據資料?

使用幾行程式碼提取收據資料:

  1. 1Install IronOCR with NuGet Package Manager

    PM > Install-Package IronOcr

  2. 2複製並運行這段程式碼片段。

    using IronOcr;
    using System;
    
    var ocr = new IronTesseract();
    
    // Configure for receipt scanning
    ocr.Configuration.ReadBarCodes = true;
    ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% ";
    
    using (var input = new OcrInput(@"receipt.jpg"))
    {
        // Apply automatic image enhancement
        input.DeNoise();
        input.Deskew();
        input.EnhanceResolution(225);
        
        // Extract text from receipt
        var result = ocr.Read(input);
        
        // Display extracted text and confidence
        Console.WriteLine($"Extracted Text:\n{result.Text}");
        Console.WriteLine($"\nConfidence: {result.Confidence}%");
    }
    C#
  3. 3部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronOCR,透過免費試用
    arrow pointer

如何從收據圖像中提取結構化資料?

IronOCR從各種文件型別中提取劃銷項目、定價、稅金和總額。該程式庫支持PDF多頁TIFF和不同的圖像格式

using IronOcr;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class ReceiptScanner
{
    static void Main()
    {
        var ocr = new IronTesseract();
        
        // Configure OCR for optimal receipt reading
        ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% ";
        ocr.Configuration.BlackListCharacters = "~`@#*_}{][|\\";
        ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
        
        // Load the image of the receipt
        using (var input = new OcrInput(@"r2.png"))
        {
            // Apply image enhancement filters
            input.Deskew(); // Fix image rotation
            input.EnhanceResolution(225); // Optimal DPI for receipts
            input.DeNoise(); // Remove background noise
            input.Sharpen(); // Improve text clarity
            
            // Perform OCR on the input image
            var result = ocr.Read(input);

            // Regular expression patterns to extract relevant details from the OCR result
            var descriptionPattern = @"\w+\s+(.*?)\s+(\d+\.\d+)\s+Units\s+(\d+\.\d+)\s+Tax15%\s+\$(\d+\.\d+)";
            var pricePattern = @"\$\d+(\.\d{2})?";
            var datePattern = @"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}";
            
            // Variables to store extracted data
            var descriptions = new List<string>();
            var unitPrices = new List<decimal>();
            var taxes = new List<decimal>();
            var amounts = new List<decimal>();
            
            var lines = result.Text.Split('\n');
            foreach (var line in lines)
            {
                // Match each line against the description pattern
                var descriptionMatch = Regex.Match(line, descriptionPattern);
                if (descriptionMatch.Success)
                {
                    descriptions.Add(descriptionMatch.Groups[1].Value.Trim());
                    unitPrices.Add(decimal.Parse(descriptionMatch.Groups[2].Value));
                    
                    // Calculate tax and total amount for each item
                    var tax = unitPrices[unitPrices.Count - 1] * 0.15m;
                    taxes.Add(tax);
                    amounts.Add(unitPrices[unitPrices.Count - 1] + tax);
                }
                
                // Extract date if found
                var dateMatch = Regex.Match(line, datePattern);
                if (dateMatch.Success)
                {
                    Console.WriteLine($"Receipt Date: {dateMatch.Value}");
                }
            }
            
            // Output the extracted data
            for (int i = 0; i < descriptions.Count; i++)
            {
                Console.WriteLine($"Description: {descriptions[i]}");
                Console.WriteLine($"Quantity: 1.00 Units");
                Console.WriteLine($"Unit Price: ${unitPrices[i]:0.00}");
                Console.WriteLine($"Taxes: ${taxes[i]:0.00}");
                Console.WriteLine($"Amount: ${amounts[i]:0.00}");
                Console.WriteLine("-----------------------");
            }
            
            // Calculate and display totals
            var subtotal = unitPrices.Sum();
            var totalTax = taxes.Sum();
            var grandTotal = amounts.Sum();
            
            Console.WriteLine($"\nSubtotal: ${subtotal:0.00}");
            Console.WriteLine($"Total Tax: ${totalTax:0.00}");
            Console.WriteLine($"Grand Total: ${grandTotal:0.00}");
        }
    }
}

有哪些技術可提高收據掃描的準確率?

提高收據掃描準確率的關鍵技術:

Visual Studio除錯控制台顯示從PDF提取的發票資料,顯示帶有描述、數量、價格、稅率和總數的項目 輸出

如何提取完整的收據內容?

提取保持格式化的完整收據內容:

using IronOcr;
using System;
using System.Linq;

class WholeReceiptExtractor
{
    static void Main()
    {
        var ocr = new IronTesseract();
        
        // Configure for receipt scanning
        ocr.Configuration.ReadBarCodes = true; // Enable barcode detection
        ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5; // Use latest engine
        ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm; // Best accuracy
        
        using (var input = new OcrInput(@"r3.png"))
        {
            // Apply automatic image correction
            input.WithTitle("Receipt Scan");
            
            // Use computer vision to find text regions
            var textRegions = input.FindTextRegions();
            Console.WriteLine($"Found {textRegions.Count()} text regions");
            
            // Apply optimal filters for receipt processing
            input.ApplyOcrInputFilters();
            
            // Perform OCR on the entire receipt
            var result = ocr.Read(input);
            
            // Display extracted text
            Console.WriteLine("=== EXTRACTED RECEIPT TEXT ===");
            Console.WriteLine(result.Text);
            
            // Get detailed results
            Console.WriteLine($"\n=== OCR STATISTICS ===");
            Console.WriteLine($"OCR Confidence: {result.Confidence:F2}%");
            Console.WriteLine($"Pages Processed: {result.Pages.Length}");
            Console.WriteLine($"Paragraphs Found: {result.Paragraphs.Length}");
            Console.WriteLine($"Lines Detected: {result.Lines.Length}");
            Console.WriteLine($"Words Recognized: {result.Words.Length}");
            
            // Extract any barcodes found
            if (result.Barcodes.Any())
            {
                Console.WriteLine("\n=== BARCODES DETECTED ===");
                foreach(var barcode in result.Barcodes)
                {
                    Console.WriteLine($"Type: {barcode.Type}");
                    Console.WriteLine($"Value: {barcode.Value}");
                    Console.WriteLine($"Location: X={barcode.X}, Y={barcode.Y}");
                }
            }
            
            // Save as searchable PDF
            result.SaveAsSearchablePdf("receipt_searchable.pdf");
            Console.WriteLine("\nSearchable PDF saved as: receipt_searchable.pdf");
            
            // Export as hOCR for preservation
            result.SaveAsHocrFile("receipt_hocr.html");
            Console.WriteLine("hOCR file saved as: receipt_hocr.html");
        }
    }
}

Visual Studio除錯控制台顯示從PDF提取的發票資料,顯示帶有描述、數量、價格、稅率和總數的項目 掃描收據API輸出

有哪些先進的功能可以提升收據掃描?

IronOCR提供了一些顯著提高收據掃描準確率的先進功能:

IronOCR支持哪些語言?

  1. 多語言支持:處理125+種語言的收據或在一個文件中使用多種語言

IronOCR能讀取收據上的條碼嗎?

  1. 條碼讀取:自動檢測並讀取條碼和QR碼

計算機視覺如何幫助收據處理?

  1. 計算機視覺:使用先進文字檢測在OCR之前定位文字區域。

我可以為獨特的收據格式訓練自定義模型嗎?

  1. 自定義訓練訓練自定義字體以獲取專業化的收據格式。

如何提高批量處理的性能?

  1. 性能優化:實現多執行緒異步處理以進行批量操作。
// Example: Async receipt processing for high-volume scenarios
using IronOcr;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;

class BulkReceiptProcessor
{
    static async Task Main()
    {
        var ocr = new IronTesseract();
        
        // Configure for optimal performance
        ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
        ocr.Configuration.UseMultiThreading = true;
        ocr.Configuration.ProcessorCount = Environment.ProcessorCount;
        
        // Process multiple receipts asynchronously
        var receiptFiles = Directory.GetFiles(@"C:\Receipts\", "*.jpg");
        var tasks = new List<Task<OcrResult>>();
        
        foreach (var file in receiptFiles)
        {
            tasks.Add(ProcessReceiptAsync(ocr, file));
        }
        
        // Wait for all receipts to be processed
        var results = await Task.WhenAll(tasks);
        
        // Aggregate results
        decimal totalAmount = 0;
        foreach (var result in results)
        {
            // Extract total from each receipt
            var match = System.Text.RegularExpressions.Regex.Match(
                result.Text, @"Total:?\s*\$?(\d+\.\d{2})");
            
            if (match.Success && decimal.TryParse(match.Groups[1].Value, out var amount))
            {
                totalAmount += amount;
            }
        }
        
        Console.WriteLine($"Processed {results.Length} receipts");
        Console.WriteLine($"Combined total: ${totalAmount:F2}");
    }
    
    static async Task<OcrResult> ProcessReceiptAsync(IronTesseract ocr, string filePath)
    {
        using (var input = new OcrInput(filePath))
        {
            // Apply preprocessing
            input.DeNoise();
            input.Deskew();
            input.EnhanceResolution(200);
            
            // Process asynchronously
            return await ocr.ReadAsync(input);
        }
    }
}

如何應對常見的收據掃描挑戰?

收據掃描帶來了IronOCR可以幫助解決的獨特挑戰:

我該如何應對質量差的收據圖像?

  • 質量差的圖像:使用篩選嚮導自動找到最佳的預處理設置。

怎麼處理傾斜或旋轉的收據?

如何處理褪色或低對比度的收據?

IronOCR能處理揉皺或損壞的收據嗎?

  • 揉皺或損壞的收據先進預處理從複雜的圖像中恢復文字。

如何管理不同的收據格式和佈局?

收據格式在零售商之間差異很大。 IronOCR提供了靈活的方法:

using IronOcr;
using System;
using System.Collections.Generic;
using System.Linq;

class ReceiptLayoutHandler
{
    static void Main()
    {
        var ocr = new IronTesseract();
        
        // Configure for different receipt layouts
        ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;
        ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm;
        
        using (var input = new OcrInput(@"complex_receipt.jpg"))
        {
            // Apply region-specific processing
            var cropRegion = new CropRectangle(x: 0, y: 100, width: 400, height: 800);
            input.AddImage(@"complex_receipt.jpg", cropRegion);
            
            // Process with confidence tracking
            var result = ocr.Read(input);
            
            // Parse using confidence scores
            var highConfidenceLines = result.Lines
                .Where(line => line.Confidence > 85)
                .Select(line => line.Text)
                .ToList();
            
            // Extract data with fallback strategies
            var total = ExtractTotal(highConfidenceLines) 
                        ?? ExtractTotalAlternative(result.Text);
            
            Console.WriteLine($"Receipt Total: {total}");
        }
    }
    
    static decimal? ExtractTotal(List<string> lines)
    {
        // Primary extraction method
        foreach (var line in lines)
        {
            if (line.Contains("TOTAL") && 
                System.Text.RegularExpressions.Regex.IsMatch(line, @"\d+\.\d{2}"))
            {
                var match = System.Text.RegularExpressions.Regex.Match(line, @"(\d+\.\d{2})");
                if (decimal.TryParse(match.Value, out var total))
                    return total;
            }
        }
        return null;
    }
    
    static decimal? ExtractTotalAlternative(string fullText)
    {
        // Fallback extraction method
        var pattern = @"(?:Total|TOTAL|Grand Total|Amount Due).*?(\d+\.\d{2})";
        var match = System.Text.RegularExpressions.Regex.Match(fullText, pattern);
        
        if (match.Success && decimal.TryParse(match.Groups[1].Value, out var total))
            return total;
            
        return null;
    }
}

關於收據掃描API我應該記住哪些重要要點?

收據掃描API如IronOCR為自動提取收據資料提供可靠的解決方案。使用先進的OCR技術,企業可以自動提取供應商名稱、採購日期、分項列表、價格、稅金和總額。 支持多種語言、貨幣和條碼支持,企業可以簡化收據管理、節省時間並做出資料驅動的決策。

IronOCR提供開發者所需的工具,為準確有效的文字提取,實現任務自動化並提高效率。 該程式庫的完整功能集包括對各種文件型別的支持及98%的記憶體減少等近期改進。

通過滿足先決條件並整合IronOCR,您可以揭示自動收據處理的優勢。 該程式庫的文件範例疑難排解指南確保平滑的實施。

欲了解更多資訊,請存取授權頁面或探索C# Tesseract OCR教程

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
獲取您的無義務諮詢
填寫以下表格或發送電子郵件至sales@ironsoftware.com
您的詳細資訊將始終保密。
被全球數百萬工程師信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立