フッターコンテンツにスキップ
IRONOCRの使い方

請求書OCR API(開発者チュートリアル)

請求書 OCR API は、機械学習を使用して請求書データの抽出を自動化し、手動入力エラーを排除しながら、デジタル文書とスキャンされた文書の両方からベンダーの詳細、請求書番号、価格を正確に取得します。 このチュートリアルでは、IronOCR を使用して請求書 OCR ソリューションを構築する方法を説明します。

請求書 OCR テクノロジーは、機械学習とコンピューター ビジョンを活用して、請求書データを自動処理に適した形式に変換します。 あらゆる請求書形式からベンダー情報、請求書番号、価格を正確に抽出しながら、手動によるデータ入力の遅延、コスト、エラーなどの一般的な課題に対処する方法を学習します。

この記事では、.NET 開発者向けの主要な請求書 OCR API であるIronOCRを使用します。

IronOCRとは何ですか?

Iron Software が開発した IronOCR は、開発者向けに包括的な OCR ツールを提供します。 機械学習とコンピューター ビジョンを使用して、スキャンされたドキュメント、画像、PDF からテキストを抽出し、自動処理を可能にします。 API はさまざまな言語やプラットフォームとシームレスに統合され、手動によるデータ入力エラーを削減し、効率を向上させます。 抽出されたデータは既存のシステムに直接送られ、分析と意思決定に使用されます。 画像の事前処理バーコード認識、柔軟なファイル解析などの機能により、汎用性が向上します。 IronOCR を使用すると、開発者は強力なテキスト認識をアプリケーションに組み込むことができます。

ライブラリは、特殊な言語パックを通じて125 の国際言語をサポートしており、グローバルな請求書処理に最適です。 高度な機能には、テキストを自動的に見つけるコンピューター ビジョンが含まれており、さまざまなレイアウトの請求書に特に役立ちます。 さらに、IronOCR は、大量の請求書処理を効率的に処理するためのマルチスレッド処理機能を提供します。

請求書処理に IronOCR を使用する必要があるのはなぜですか?

IronOCR は、請求書処理アプリケーションに大きな利点をもたらします。 まず、.NET アプリケーション向けに特別に強化された最適化されたTesseract 5 エンジンにより、優れた精度を実現します。 ライブラリは、スキャンされた文書からPDF ファイル、さらには低品質のスキャンまで、さまざまな請求書形式を処理します。

組み込みの画像最適化フィルターにより、処理前に画像の品質が自動的に向上し、より正確なテキスト抽出が可能になります。 特定の要件がある請求書の場合、IronOCR はカスタム言語トレーニングをサポートし、請求書の種類によく見られる固有のフォントや形式を最適化できます。

IronOCR が他の OCR ライブラリと異なる点は何ですか?

IronOCR は、エンタープライズ レベルの機能を維持しながら、シンプルな 1 行 OCR 機能によって他と差別化されています。 生の Tesseract 実装とは異なり、IronOCR は複雑な操作をシームレスに処理するマネージ .NET API を提供します。 ライブラリは、請求書の明細項目に不可欠なドキュメント内の表の読み取り専用のサポートを含む、さまざまなドキュメント タイプに特化したドキュメント読み取りメソッドを提供します。

フィルター ウィザードは、特定の請求書画像に最適な前処理設定を自動的に決定し、最適化における推測作業を排除します。 IronOCR は包括的なデバッグ機能も提供しており、開発者は OCR エンジンが認識した内容を視覚化し、抽出の問題を効果的にトラブルシューティングできます。

どのような前提条件が必要ですか?

IronOCR を使用する前に、次の前提条件が満たされていることを確認してください。

  1. Visual StudioなどのIDEがインストールされた適切な開発環境
  2. コード例を効果的に理解し、修正するためのC#プログラミングの基礎知識
  3. NuGet パッケージ マネージャーまたはコマンド ライン経由でプロジェクトにインストールされた IronOCR ライブラリ

これらの前提条件を満たすことで、IronOCR をうまく使いこなす準備が整います。

IronOCR は、 WindowsLinuxmacOS向けの包括的なセットアップ ガイドを提供します。 このライブラリは、 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 が適しています。 モバイル開発者は、 AndroidおよびiOS実装用の IronOCR のガイダンスを活用できるため、 .NET MAUI アプリケーションに適合させることができます。

どの程度の C# 知識レベルが必要ですか?

基本的な請求書 OCR の実装には中級レベルの C# の知識があれば十分です。 以下の点について理解している必要があります:

IronOCR の直感的な API 設計により、画像処理や機械学習に関する深い専門知識は必要ありません。 ライブラリは複雑な操作を内部で処理するため、ビジネス ロジックに集中できます。 初心者は簡単な OCR の例から始めることができます。

新しい Visual Studio プロジェクトを作成するにはどうすればよいですか?

IronOCR を使い始めるには、まず新しい Visual Studio プロジェクトを作成します。

Visual Studio を開き、[ファイル] に移動して [新規] にカーソルを合わせ、[プロジェクト] をクリックします。

! Visual Studio IDE でファイル メニューが開き、"新規"と"プロジェクト"オプションが強調表示され、新しい請求書 OCR API プロジェクトを作成する最初の手順が示されています。 新しいプロジェクト

新しいウィンドウで、"コンソール アプリケーション"を選択し、"次へ"をクリックします。

Visual Studio の [新しいプロジェクトの作成] ダイアログには、さまざまなプロジェクト テンプレートが表示され、請求書の OCR 処理に適した .NET Core コマンドライン アプリケーションを作成するための [コンソール アプリケーション] オプションが強調表示されています。 コンソールアプリケーション

新しいウィンドウが表示されます。 プロジェクト名と場所を入力し、"次へ"をクリックします。

! Visual Studio の新しいプロジェクト構成ウィンドウには、C# 言語の選択と請求書 OCR API 実装の Windows ターゲット プラットフォームを含む、コンソール アプリケーション 'IronOCR' のプロジェクト設定が表示されています。 プロジェクト設定

最後に、ターゲット フレームワークを選択し、"作成"をクリックします。

! Visual Studio プロジェクト作成ウィザードでは、請求書処理アプリケーションで最適な IronOCR 互換性を実現するために .NET 5.0 フレームワークが選択された"追加情報"ステップが表示されています。 ターゲットフレームワーク

新しい Visual Studio プロジェクトの準備ができました。 IronOCRをインストールしましょう。

OCR アプリケーションに最適なプロジェクト タイプは何ですか?

このチュートリアルでは簡潔にするためにコンソール アプリケーションを使用していますが、IronOCR はさまざまなプロジェクト タイプをサポートしています。

-コンソールアプリケーション: バッチ処理やコマンドラインツールに最適

  • Webアプリケーション: APIやWebベースのサービスの構築に最適
  • 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 をダウンロードしてインストールするには、次の 2 つの簡単な方法があります。

  1. Visual Studio NuGet パッケージ マネージャーの使用
  2. Visual Studio コマンドラインの使用

NuGet パッケージ マネージャーとコマンド ラインはいつ使用すればよいですか?

ワークフローに応じて、NuGet パッケージ マネージャー GUI とコマンド ラインのいずれかを選択します。

NuGet パッケージ マネージャー GUI は、次の場合に最適に機能します。

  • NuGet パッケージを初めて使用する
  • IronOCR言語パックを閲覧したい
  • 視覚的な確認を好む
  • 複数のパッケージを管理する

コマンドライン (パッケージ マネージャー コンソール)は次の場合に最適です:

  • コマンドインターフェースに慣れている
  • スクリプト化された展開に従う
  • 特定のバージョンがすぐに必要になる -高度なインストールオプションを使用する

どちらの方法でも同じ結果が得られます。快適さと要件に基づいて選択してください。

どのような追加言語パックが必要になるでしょうか?

IronOCR は、専用パックを通じて125 の国際言語をサポートします。 請求書処理については、次の点を考慮してください。

-ビジネス固有のパック:財務文書用の財務言語パック -地域言語: 請求書のソースに基づく(スペイン語、フランス語、ドイツ語) -多言語サポート複数の言語の請求書の場合 -カスタム言語: 特殊なフォントやカスタムトレーニングデータ

言語パックはメインの IronOCR パッケージと一緒にインストールされ、英語以外のテキストの精度が大幅に向上します。

Visual Studio NuGetパッケージマネージャーを使用する

Visual Studio NuGet パッケージ マネージャーを使用して、C# プロジェクトに IronOCR を組み込みます。

ツール> NuGet パッケージ マネージャー>ソリューションの NuGet パッケージの管理に移動します。

! Visual Studio IDE に NuGet パッケージ マネージャー インターフェイスが表示され、IronOCR パッケージの検索結果が表示されます。請求書 OCR 機能を設定するためのインストール オプションとパッケージの詳細が表示されます。 NuGetパッケージマネージャー

IronOCR を検索し、プロジェクトにパッケージをインストールします。

! NuGet パッケージ マネージャー インターフェイスには、IronOCR v2022.1.0 と、アラビア語、ヘブライ語、スペイン語の OCR 機能を含む関連言語パッケージが、各特殊認識パッケージのバージョン番号と説明とともに表示されています。 NuGet パッケージ マネージャー UI で IronOCR パッケージを選択します。

同じ方法を使用して追加の言語パックをインストールします。

Visual Studio コマンドラインの使用

  1. Visual Studioで、 [ツール] > [NuGet パッケージ マネージャー] > [パッケージ マネージャー コンソール]に移動します。
  2. パッケージ マネージャー コンソールに次のコマンドを入力します。

    Install-Package IronOcr

! Visual Studio パッケージ マネージャー コンソールに 'Install-Package IronOCR' コマンドの実行が成功したことが表示され、OCR ライブラリのコマンドライン インストール方法が示されています。 パッケージマネージャーコンソール

パッケージは現在のプロジェクトにダウンロードされ、インストールされてすぐに使用できるようになります。

IronOCR を使用して請求書からデータを抽出するにはどうすればよいですか?

わずか数行のコードを使用して、IronOCR で請求書データを簡単に抽出します。 これにより、手動によるデータ入力が不要になり、ワークフローが効率化されます。

以下はテキスト抽出の請求書の例です。

顧客の詳細、請求書番号 INV/2023/00039、清掃サービスの3つの明細項目(合計80.50ドル)が表示されたサンプル請求書文書。OCR抽出用の一般的な請求書形式を示しています。 サンプル請求書

この請求書からすべてのデータを抽出してみましょう。

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 = "~`$#^*_}{]___PROTECTED_LINK_48___ method from ___PROTECTED_LINK_49___ class. Key enhancements include:

- **Image preprocessing**: ___PROTECTED_LINK_50___ corrects tilted scans; ___PROTECTED_LINK_51___ removes artifacts
- **Resolution enhancement**: Setting ___PROTECTED_LINK_52___ improves recognition
- **Character blacklisting**: Prevents common OCR misinterpretations
- **Confidence scoring**: Assesses extraction reliability

!___PROTECTED_LINK_53___
**Invoice Parser**

<h3>How Do I Handle Different Invoice Formats?</h3>

Invoice formats vary between vendors, but IronOCR provides flexible solutions:

1. **Template-based**: Define ___PROTECTED_LINK_54___
2. **Computer vision**: Use ___PROTECTED_LINK_55___ to locate text
3. **Table extraction**: Leverage ___PROTECTED_LINK_56___ for line items
4. **Multi-format**: Process ___PROTECTED_LINK_57___, ___PROTECTED_LINK_58___, and ___PROTECTED_LINK_59___

For complex layouts, implement the ___PROTECTED_LINK_60___ which uses machine learning to identify structures automatically.

<h3>What Are Common Extraction Patterns for Invoice Data?</h3>

Invoice data follows recognizable patterns extractable using regular expressions with OCR results:

```csharp
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;

// 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 = "~`$#^*_}{]___PROTECTED_LINK_48___ method from ___PROTECTED_LINK_49___ class. Key enhancements include:

- **Image preprocessing**: ___PROTECTED_LINK_50___ corrects tilted scans; ___PROTECTED_LINK_51___ removes artifacts
- **Resolution enhancement**: Setting ___PROTECTED_LINK_52___ improves recognition
- **Character blacklisting**: Prevents common OCR misinterpretations
- **Confidence scoring**: Assesses extraction reliability

!___PROTECTED_LINK_53___
**Invoice Parser**

<h3>How Do I Handle Different Invoice Formats?</h3>

Invoice formats vary between vendors, but IronOCR provides flexible solutions:

1. **Template-based**: Define ___PROTECTED_LINK_54___
2. **Computer vision**: Use ___PROTECTED_LINK_55___ to locate text
3. **Table extraction**: Leverage ___PROTECTED_LINK_56___ for line items
4. **Multi-format**: Process ___PROTECTED_LINK_57___, ___PROTECTED_LINK_58___, and ___PROTECTED_LINK_59___

For complex layouts, implement the ___PROTECTED_LINK_60___ which uses machine learning to identify structures automatically.

<h3>What Are Common Extraction Patterns for Invoice Data?</h3>

Invoice data follows recognizable patterns extractable using regular expressions with OCR results:

```csharp
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 As 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 dateValue As DateTime
            If DateTime.TryParse(match.Groups(1).Value, dateValue) Then
                Return dateValue
            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
$vbLabelText   $csharpLabel

請求書から特定のデータを抽出する請求書処理

次のコードを使用して、顧客請求書番号などの特定の請求書データを抽出します。

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 As New IronTesseract()

' Use the OcrInput object to load the image file
Using input As 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 As String = "INV/\d{4}/\d{5}"

    ' Match the pattern in the extracted text
    Dim lineMatch As Match = 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 As String = lineMatch.Value
        Console.WriteLine("Customer Invoice number: " & lineValue)
    End If
End Using
$vbLabelText   $csharpLabel

Visual Studio デバッグ コンソールに、IronOCR を使用して抽出された顧客請求書番号 INV/2023/00039 で PDF が作成されたことが示され、OCR プロセスがエラーなく完了したことが確認されています。 請求書のスキャン

複雑な抽出シナリオの場合は、請求書の種類に合わせて最適化された専用のOCR設定を使用してください。OcrResultクラスは、認識された各要素の詳細情報(座標や検証の信頼度スコアなど)を提供します。

請求書 OCR API の主な利点は何ですか?

IronOCR の請求書 OCR API は、機械学習とコンピューター ビジョンを通じて請求書処理を変革します。 このテクノロジーは、請求書のテキストを機械が読み取り可能な形式に変換し、分析、統合、プロセス改善のためのデータ抽出を簡素化します。 請求書処理の強力な自動化を実現し、正確性を向上させ、買掛金などのワークフローを最適化します。

IronOCR は、追加の構成なしで最適化された Tesseract 結果を使用して、優れた精度を提供します。 マルチページフレームの TIFFPDF ファイル、およびすべての一般的な画像形式をサポートします。 画像からバーコードを読み取ると、抽出の次元がさらに広がります。

請求書処理の主な利点:

1.時間の節約:時間を数秒に短縮 2.正確性信頼スコアリングでエラーを最小限に抑える 3.スケーラビリティ:マルチスレッドで数千を処理 4.統合:検索可能なPDFまたは構造化形式へのエクスポート 5.コスト削減:運用コストの削減

ライブラリの導入の柔軟性により、オンプレミス、クラウド、ハイブリッドなど、既存のシステムへの統合が可能になります。 DockerAzureAWSをサポートしているため、IronOCR はニーズに合わせて拡張できます。

実稼働環境では、専用サポートや定期的なアップデートなどの IronOCR のライセンス オプションのメリットを享受できます。 ライブラリのトラブルシューティング ガイドエンジニアリング サポートにより、スムーズな実装が保証されます。

IronOCR の詳細についてはホームページをご覧ください。 追加の請求書 OCR チュートリアルについては、詳細な請求書 OCR ガイドを参照してください。 請求書フィールドでのコンピューター ビジョンの使用について詳しくは、このコンピューター ビジョン チュートリアルをご覧ください。

よくある質問

OCRを使用してインボイスデータ処理をどのように自動化できますか?

IronOCRを使用して機械学習アルゴリズムを活用することで、インボイスデータ処理を自動化できます。IronOCRは、デジタルおよびスキャンされたインボイスからベンダー情報、インボイス番号、価格などの詳細を抽出し、手動入力のエラーを減らし、効率を向上させます。

インボイスOCR APIのセットアップにはどのような手順が含まれていますか?

IronOCRを使用してインボイスOCR APIをセットアップするには、まずVisual StudioのNuGetパッケージマネージャーを介してライブラリをダウンロードしてインストールします。次に、新しいC#プロジェクトを作成し、IronOCRを統合し、テキスト抽出のために画像ファイルを読み込み、読み取るためのメソッドを使用します。

IronOCRはインボイス番号などの特定のデータを抽出できますか?

はい、IronOCRはインボイス番号のような特定のデータを抽出できます。通常の表現を使用して抽出されたテキストのパターンと一致させることで、インボイスから特定の情報を引き出せます。

インボイス処理に役立つIronOCRのいくつかの機能は何ですか?

IronOCRには、画像の前処理、バーコード認識、ファイル解析などの機能があります。これにより、さまざまな請求書形式からテキストを正確に抽出および処理する能力が向上し、データキャプチャおよびワークフローの効率が改善されます。

画像の前処理はどのようにしてOCRの結果を改善できますか?

IronOCRの画像前処理は、テキスト抽出前に画像の品質を最適化することで、OCRの結果を改善します。これには、コントラスト調整やノイズ削減などの操作が含まれ、インボイスからのデータ抽出の精度を高めることができます。

デジタルおよびスキャンされたインボイスの両方にIronOCRを使用することは可能ですか?

はい、IronOCRはデジタルおよびスキャンされた両方のインボイスを処理できます。先進的な機械学習およびコンピュータビジョン技術を使用して、さまざまな形式および画像品質から正確にテキストを抽出します。

IronOCRは複数のページ形式およびファイルタイプをどのように処理しますか?

IronOCRは、複数のページ形式および一般的な画像およびPDFファイルタイプをサポートしています。複雑なドキュメントから効率的にテキストを抽出できるため、さまざまなインボイス処理アプリケーションにおいて非常に柔軟です。

開発者はIronOCRを使用するためのチュートリアルをどこで見つけることができますか?

開発者はIronOCRのウェブサイトでチュートリアルや追加のリソースを見つけることができます。このサイトは、さまざまな状況でIronOCRを適用するためのハウツーガイドやブログ投稿を含む幅広い学習資料を提供しています。

Kannaopat Udonpant
ソフトウェアエンジニア
ソフトウェアエンジニアになる前に、Kannapatは北海道大学で環境資源の博士号を修了しました。博士号を追求する間に、彼はバイオプロダクションエンジニアリング学科の一部である車両ロボティクスラボラトリーのメンバーになりました。2022年には、C#のスキルを活用してIron Softwareのエンジニアリングチームに参加し、IronPDFに注力しています。Kannapatは、IronPDFの多くのコードを執筆している開発者から直接学んでいるため、この仕事を大切にしています。同僚から学びながら、Iron Softwareでの働く社会的側面も楽しんでいます。コードやドキュメントを書いていない時は、KannapatはPS5でゲームをしたり、『The Last of Us』を再視聴したりしていることが多いです。