跳至頁尾內容
USING IRONOCR

如何在 C# 中對 PDF 進行 OCR 識別:使用 .NET 從掃描文件中提取文字

掃描PDF文件為.NET開發人員帶來持續的挑戰:文字僅以圖像形式存在,使得搜尋、複製或程式化處理變得不可能。 光學字元識別(OCR)透過將掃描的圖像轉換為可編輯和可搜尋的資料來解決此問題——將紙質文件、相機拍攝的圖片或任何以圖像為基礎的PDF文件轉換為機器可讀的文字。 無論是將紙質檔案數位化、自動化資料擷取,還是構建文件處理管道,能夠在C#中對PDF文件進行OCR是一個關鍵能力。

IronOCR是一個基於Tesseract 5引擎構建的.NET OCR庫,具有額外的精確度增強。 它可以讓開發者通過少量程式碼從任何PDF文件——無論是掃描的還是其他的——中提取文字。 本文介紹了核心工作流程:基本的PDF OCR、頁面選擇性處理、區域定位提取以及難以掃描的圖像預處理。

如何在C#中對PDF進行OCR?

.NET中PDF文字提取的最快路徑始於安裝IronOCR via NuGet。 在您的專案目錄中打開終端並執行:

dotnet add package IronOcr

安裝包後,以下頂層語句程式讀取掃描的PDF並列印其提取的文字:

using IronOcr;

// Initialize the OCR engine
var ocr = new IronTesseract();

// Load the PDF and perform OCR
using var input = new OcrInput();
input.LoadPdf("scanned-report.pdf");

// Run recognition
OcrResult result = ocr.Read(input);

// Access the extracted text
string text = result.Text;
Console.WriteLine(text);
using IronOcr;

// Initialize the OCR engine
var ocr = new IronTesseract();

// Load the PDF and perform OCR
using var input = new OcrInput();
input.LoadPdf("scanned-report.pdf");

// Run recognition
OcrResult result = ocr.Read(input);

// Access the extracted text
string text = result.Text;
Console.WriteLine(text);
Imports IronOcr

' Initialize the OCR engine
Dim ocr As New IronTesseract()

' Load the PDF and perform OCR
Using input As New OcrInput()
    input.LoadPdf("scanned-report.pdf")

    ' Run recognition
    Dim result As OcrResult = ocr.Read(input)

    ' Access the extracted text
    Dim text As String = result.Text
    Console.WriteLine(text)
End Using
$vbLabelText   $csharpLabel

IronTesseract類將Tesseract 5與.NET原生優化以適用於.NET Core和.NET Framework目標封裝起來。 OcrInput物件管理PDF載入和內部頁面渲染。 當OcrResult,其中包含完整提取的文字以及段落、行、單詞及其像素座標的結構化資料。

結果可以寫入文字文件,傳遞給下游處理邏輯,儲存在資料庫中,或送入文件索引管道。若要進一步閱讀底層引擎,請參閱Tesseract OCR文件IronOCR API參考

輸入

如何OCR PDF:透過C# .NET OCR從掃描文件中提取文字:圖片1 - 範例PDF輸入

輸出

如何OCR PDF:透過C# .NET OCR從掃描文件中提取文字:圖片2 - 控制台輸出

如何讀取PDF中特定頁面?

處理一個長文件的每一頁是浪費時間和記憶體的,當只有某些頁包含相關內容時。 IronOCR允許您透過傳遞基於零的頁面索引到LoadPdf來針對特定頁面:

using IronOcr;
using System.Collections.Generic;

var ocr = new IronTesseract();

// Specify pages to process (zero-based: 0 = first page)
var targetPages = new List<int> { 0, 2, 4 };

using var input = new OcrInput();
input.LoadPdf("lengthy-document.pdf", pageIndices: targetPages);

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
using IronOcr;
using System.Collections.Generic;

var ocr = new IronTesseract();

// Specify pages to process (zero-based: 0 = first page)
var targetPages = new List<int> { 0, 2, 4 };

using var input = new OcrInput();
input.LoadPdf("lengthy-document.pdf", pageIndices: targetPages);

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr
Imports System.Collections.Generic

Dim ocr As New IronTesseract()

' Specify pages to process (zero-based: 0 = first page)
Dim targetPages As New List(Of Integer) From {0, 2, 4}

Using input As New OcrInput()
    input.LoadPdf("lengthy-document.pdf", pageIndices:=targetPages)

    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

選擇性頁面載入減少了處理時間和記憶體消耗,這在處理多達幾百頁的資料時尤其重要,其中只有幾頁包含所需資料。 基於零的索引約定符合標準的.NET集合:頁面索引0是文件的第一頁。

對於事先未知相關頁面的文件,建議先用降低DPI的快速全文件遍歷來識別頁碼,然後再用完整設置針對這些頁面重新運行。

了解更多關於頁面級控制的資訊,請參閱IronOCR頁面選擇文件

如何從頁面的特定區域提取資料?

處理發票、表單數位化和結構化文件解析經常需要從定義的區域提取文字,而不是掃描整頁。 IronOCR支持透過Rectangle物件陣列,指定每頁要分析的部分:

using IronOcr;
using IronSoftware.Drawing;

var ocr = new IronTesseract();

// Define the scan region: X, Y, Width, Height (all in pixels from top-left)
var invoiceFields = new Rectangle[]
{
    new Rectangle(130, 290, 250, 50)   // Invoice number field
};

using var input = new OcrInput();
input.LoadPdf("invoice.pdf", contentAreas: invoiceFields);

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
using IronOcr;
using IronSoftware.Drawing;

var ocr = new IronTesseract();

// Define the scan region: X, Y, Width, Height (all in pixels from top-left)
var invoiceFields = new Rectangle[]
{
    new Rectangle(130, 290, 250, 50)   // Invoice number field
};

using var input = new OcrInput();
input.LoadPdf("invoice.pdf", contentAreas: invoiceFields);

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr
Imports IronSoftware.Drawing

Dim ocr As New IronTesseract()

' Define the scan region: X, Y, Width, Height (all in pixels from top-left)
Dim invoiceFields As Rectangle() = {
    New Rectangle(130, 290, 250, 50)   ' Invoice number field
}

Using input As New OcrInput()
    input.LoadPdf("invoice.pdf", contentAreas:=invoiceFields)

    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

Rectangle構造函式接受四個整數參數:X座標、Y座標、寬度和高度——全部從渲染頁面的左上角以像素為單位測量。 針對小區域而不是整頁目標減少了OCR時間及引擎拾取周圍噪音或不相關文字欄位的機會。

對於批量發票處理工作流程,將區域提取與result.Pages迭代相結合,從數百個文件的相同字段位置中提取結構化資料。 每頁結果獨立暴露其內容區域的識別文字。

IronOCR內容區域範例為多區域情境提供了其他配置選項。

輸入

如何OCR PDF:透過C# .NET OCR從掃描文件中提取文字:圖片3 - 範例發票

輸出

如何OCR PDF:透過C# .NET OCR從掃描文件中提取文字:圖片4 - 提取的資料輸出

如何提高掃描文件的OCR準確性?

現實中的掃描文件經常存在質量問題:頁面歪斜、低解析度或數字噪音由掃描硬體或軟體引入。 IronOCR包括一組圖像預處理濾鏡,可在識別引擎運行前校正這些問題:

using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
// Load PDF at higher DPI for improved text recognition on small fonts
input.LoadPdf("poor-quality-scan.pdf", dpi: 300);

// Apply image correction filters
input.Deskew();    // Automatically straighten rotated pages
input.DeNoise();   // Remove scanning artifacts and speckles

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
// Load PDF at higher DPI for improved text recognition on small fonts
input.LoadPdf("poor-quality-scan.pdf", dpi: 300);

// Apply image correction filters
input.Deskew();    // Automatically straighten rotated pages
input.DeNoise();   // Remove scanning artifacts and speckles

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr

Dim ocr = New IronTesseract()

Using input = New OcrInput()
    ' Load PDF at higher DPI for improved text recognition on small fonts
    input.LoadPdf("poor-quality-scan.pdf", dpi:=300)

    ' Apply image correction filters
    input.Deskew()    ' Automatically straighten rotated pages
    input.DeNoise()   ' Remove scanning artifacts and speckles

    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

dpi參數控制在識別運行前PDF頁面的渲染解析度。 較高的值——200到300 DPI——提高了小或密集文字的文件的準確性,代價是處理期間稍微增加了記憶體。 Deskew方法自動檢測和校正頁面旋轉。 DeNoise移除可能困擾字元識別步驟的雜點和偽影。

對於需要更積極的圖像校正的文件,IronOCR也提供了對比度增強、二值化(將頁面轉換為黑白)和比例調整。 序列中結合多個濾鏡可以從掃描中恢復可用的文字,而這些掃描本來會產生亂碼輸出。 請查看IronOCR圖像濾鏡參考以獲取可用預處理操作的完整清單。

如何處理受密碼保護和多格式文件?

IronOCR不僅限於標準PDF文件。 該庫可以處理文件處理工作流程中常見的一系列輸入場景。

受密碼保護的PDF透過在輸入構建過程中傳遞憑證來支持:

using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.LoadPdf("protected.pdf", password: "secret123");

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.LoadPdf("protected.pdf", password: "secret123");

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    input.LoadPdf("protected.pdf", password:="secret123")

    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

圖像格式——PNG、JPEG、TIFF、BMP、GIF和多頁TIFF——通過相應的LoadImageFrames方法載入。 無論輸入格式如何,相同的預處理濾鏡和區域定位選項都適用。

多語言文件透過IronOCR的語言包系統處理。 該庫預設帶有英語,並支持超過125種其他語言包,涵蓋拉丁文、西里爾文、CJK、阿拉伯文及其他字元集。在調用Read之前載入其他語言:

var ocr = new IronTesseract();
ocr.Language = OcrLanguage.German;
var ocr = new IronTesseract();
ocr.Language = OcrLanguage.German;
Dim ocr As New IronTesseract()
ocr.Language = OcrLanguage.German
$vbLabelText   $csharpLabel

對於同一頁上混合多種語言的文件,MultiLanguage模式可用。 這對於需要處理國際環境中的發票處理特別有價值,因為標題、項目行和地址可能會以不同語言顯示。

部署支持跨Windows、Linux、macOS和包括Azure和Docker容器的雲環境。

如何從掃描文件中建立可搜尋PDF?

除了將文字提取到字串中,IronOCR還能生成可搜尋的PDF輸出——原始掃描圖像作為視覺層保留,同時嵌入一個不可見的文字層以進行搜尋和複製操作。 這是專業文件掃描儀產生的標准格式。

IronOCR可搜尋PDF功能接受OcrResult並寫入一個新PDF文件:

using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.LoadPdf("scanned-archive.pdf");

OcrResult result = ocr.Read(input);

// Save as a searchable PDF
result.SaveAsSearchablePdf("output-searchable.pdf");
using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.LoadPdf("scanned-archive.pdf");

OcrResult result = ocr.Read(input);

// Save as a searchable PDF
result.SaveAsSearchablePdf("output-searchable.pdf");
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    input.LoadPdf("scanned-archive.pdf")

    Dim result As OcrResult = ocr.Read(input)

    ' Save as a searchable PDF
    result.SaveAsSearchablePdf("output-searchable.pdf")
End Using
$vbLabelText   $csharpLabel

輸出文件可在任何PDF閱讀器中打開。 文字選擇、搜尋和複製操作在嵌入的文字層上工作,同時原始掃描外觀保留。 該格式通常需要用於合規性檔案庫、法律文件儲存庫和企業內容管理系統。

對於額外的輸出格式,OcrResult物件還暴露每頁的信心分數、詞級包圍框和結構化段落資料——這些對下游分類或索引用途非常有用。

如何同時讀取條碼和QR碼?

批量文件處理管道常常需要從同一文件中提取可讀文字和機器可讀碼。 IronOCR可以在同一次OCR中檢測和解碼條碼和QR碼,無需使用單獨的庫。

在處理前在IronTesseract實例上啟用條碼讀取:

using IronOcr;

var ocr = new IronTesseract();
ocr.Configuration.ReadBarCodes = true;

using var input = new OcrInput();
input.LoadPdf("shipment-labels.pdf");

OcrResult result = ocr.Read(input);

// Access recognized text
Console.WriteLine(result.Text);

// Access barcode data
foreach (var barcode in result.Barcodes)
{
    Console.WriteLine($"Type: {barcode.Format}, Value: {barcode.Value}");
}
using IronOcr;

var ocr = new IronTesseract();
ocr.Configuration.ReadBarCodes = true;

using var input = new OcrInput();
input.LoadPdf("shipment-labels.pdf");

OcrResult result = ocr.Read(input);

// Access recognized text
Console.WriteLine(result.Text);

// Access barcode data
foreach (var barcode in result.Barcodes)
{
    Console.WriteLine($"Type: {barcode.Format}, Value: {barcode.Value}");
}
Imports IronOcr

Dim ocr As New IronTesseract()
ocr.Configuration.ReadBarCodes = True

Using input As New OcrInput()
    input.LoadPdf("shipment-labels.pdf")

    Dim result As OcrResult = ocr.Read(input)

    ' Access recognized text
    Console.WriteLine(result.Text)

    ' Access barcode data
    For Each barcode In result.Barcodes
        Console.WriteLine($"Type: {barcode.Format}, Value: {barcode.Value}")
    Next
End Using
$vbLabelText   $csharpLabel

這對於運送標籤處理、庫存管理以及任何條碼和印刷文字一起出現在掃描文件中的工作流尤其有用。 IronOCR條碼讀取指南介紹了支援的格式,包括Code 128、QR碼、Data Matrix和PDF417。

IronOCR輸入型別之間有什麼區別?

IronOCR提供了兩種主要的方法來載入PDF文件,每一種都適合不同場景:

比較IronOCR PDF輸入方法
方法 類別 最佳適用 備註
一般輸入 OcrInput.LoadPdf() 大多數使用情境 支持所有預處理濾鏡、頁面選擇、內容區域
PDF專用 OcrPdfInput 簡單場景 便利的包裝器;配置選項較少
圖像文件 OcrInput.LoadImage() PNG、JPEG、TIFF、BMP 與PDF輸入相同的預處理和區域定位
多頁TIFF OcrInput.LoadImageFrames() 傳真檔案、掃描儀輸出 將每一幀作為單獨頁面處理

對於大多數生產場景,OcrInput.LoadPdf()是推薦的方法,因為它暴露了完整的預處理和配置API。 OcrPdfInput在快速原型設計或預設設定足夠的情況下工作良好。

您的下一步是什麼?

上述程式碼範例涵蓋了以C#進行PDF OCR的核心IronOCR工作流。 下面是一個簡單的清單,幫助您邁出下一步:

  • 安裝軟體包dotnet add package IronOcr或搜索NuGet上的IronOCR
  • 運行基本範例:在構建完整管道邏輯之前,確認從範例PDF中提取文字
  • 應用預處理:如果使用掃描文件,新增DeNoise調用並使用代表性樣本進行測試
  • 探索其他功能可搜尋PDF輸出條碼讀取多語言支持結構化資料輸出
  • 查看部署指導:Azure、Docker和Linux部署文章涵蓋特定環境配置
  • 嘗試免費試用開始免費試用,在承諾購買授權前測試完整版功能
  • 獲取授權IronOCR授權選項涵蓋從個人開發者到企業部署,並提供免版稅再發行

對於特定案例的問題,IronOCR實用程式庫提供涵蓋數十種情境的逐步文章。 完整的API表面文件記載在IronOCR API參考中。

常見問題

在C#中OCR PDF的最低程式碼需求是什麼?

使用IronOCR,最低程式碼是:建立一個IronTesseract實例,建立一個OcrInput,調用input.LoadPdf輸入路徑,然後調用ocr.Read(input)。result.Text屬性返回擷取的字串。

如何在.NET項目中安裝IronOCR?

在終端中運行'dotnet add package IronOcr',或在Visual Studio中使用NuGet套餐管理器搜尋IronOcr。

IronOCR可以只處理PDF的特定頁面嗎?

可以。將以零為基數的頁面索引列表List傳遞給LoadPdf的pageIndices參數。只有指定的頁面被渲染和處理,從而減少時間和記憶體用量。

如何從掃描PDF的特定區域擷取文字?

將Rectangle物件的陣列傳遞給LoadPdf的contentAreas參數。每個矩形指定頁面左上角的X位置、Y位置、寬度和高度(以像素為單位)。

IronOCR為掃描文件提供了哪些預處理濾鏡?

IronOCR提供了Deskew(校正頁面旋轉)、DeNoise(去除掃描的雜訊)、對比增強、二值化、比例調整等功能。這些可以串聯使用以提高低質量掃描的準確性。

IronOCR支持密碼保護的PDF文件嗎?

是的。將密碼字串傳遞給LoadPdf的password參數。該程式庫在渲染頁面進行OCR之前解密文件。

IronOCR可以建立可搜尋的PDF輸出嗎?

是的。在調用ocr.Read(input)之後,調用result.SaveAsSearchablePdf輸出檔案路徑。生成的PDF保留原始掃描作為可視層,並嵌入為搜尋及複製操作的不可見文字層。

IronOCR支持哪些語言?

IronOCR支持超過125種語言包,包括拉丁、斯拉夫、CJK、阿拉伯等多種字母。在調用Read之前,設置IronTesseract實例的Language屬性。

IronOCR能從PDF文件中讀取條碼和QR碼嗎?

是的。在調用Read之前設置ocr.Configuration.ReadBarCodes為true。OcrResult.Barcodes集合包含所有檢測到的程式碼的解碼值和格式型別。

IronOCR可以在Linux和Docker容器中運行嗎?

是的。IronOCR支持在Windows、Linux、macOS和包括Azure和Docker容器在內的雲環境中部署。IronSoftware文件中包括針對特定環境的設置指南。

Kannaopat Udonpant
軟體工程師
在成為軟體工程師之前,Kannapat在日本北海道大學完成了環境資源博士學位。在攻讀學位期間,Kannapat還成為車輛機器人實驗室的一員,該實驗室隸屬於生產工程系。在2022年,他憑藉C#技能加入了Iron Software的工程團隊,專注於IronPDF。Kannapat珍視他的工作,因為他能直接向撰寫大部分IronPDF程式碼的開發者學習。除了同儕學習,Kannapat還喜歡在Iron Software工作的社交方面。不寫程式碼或文件時,Kannapat通常在他的PS5上玩遊戲或重看The Last of Us。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話