在 C# 中使用 IronOCR 儲存可搜尋的 PDF

Curtis Chau
Curtis Chau
已更新: 2026年8月26日

C# 開發人員只需幾行程式碼,就能用 IronOCR 的 OCR 技術將掃描文件和影像轉成可搜尋的 PDF,並以檔案、位元組或串流輸出。

可搜尋的 PDF 通常稱為 OCR(光學字元辨識)PDF,內含掃描影像和機器可讀的文字。對掃描的紙本文件或影像執行 OCR,即可辨識影像中的文字,並將其轉換為可選取及搜尋的文字。

SaveAsSearchablePdf 也適用於 ReadPhoto、ReadScreenShot 和 ReadDocumentAdvanced 的結果,因此您可以在照片和進階文件 OCR 流程中建立可搜尋的 PDF。這項功能特別適合用於將紙本檔案數位化,或讓既有 PDF 可供搜尋,以提升文件管理效率。

快速入門:一行匯出可搜尋 PDF

將 RenderSearchablePdf = true 設定好後,對輸入執行 Read(...),再呼叫 SaveAsSearchablePdf(...)。完成這幾個步驟,IronOCR 就會產生可全文搜尋的 PDF 檔案。

  1. 1使用 IronOCR 安裝 NuGet Package Manager

    PM > Install-Package IronOcr

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

    new IronOcr.IronTesseract { Configuration = { RenderSearchablePdf = true } } .Read(new IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf");
  3. 3部署到您的生產環境進行測試

    立即在您的項目中開始使用 IronOCR,並使用 免費試用
    arrow pointer

如何將OCR結果匯出為可搜尋PDF?

若要使用 IronOCR 將結果匯出為可搜尋的 PDF,請將 Configuration.RenderSearchablePdf 屬性設為 true,透過 Read 方法取得 OCR 結果物件,再將輸出檔案路徑傳給 SaveAsSearchablePdf。

輸入

將《哈利波特》小說中的一頁掃描為 TIFF 檔,再透過 OcrImageInput 載入。這一頁的印刷文字相當密集,適合用來測試可搜尋 PDF 的文字層。

《哈利波特》書頁,顯示第八章「死亡紀念派對」,內容描述哈利遇見「幾乎無頭尼克」

potter.tiff:掃描的小說頁面,用作 OCR 輸入以產生帶有隱形文字層的可搜尋 PDF。

using IronOcr;

// Create the OCR engine: defaults to English with balanced speed and accuracy
IronTesseract ocrTesseract = new IronTesseract();

// Required: without this flag the text overlay layer is not built, and SaveAsSearchablePdf produces a plain image PDF
ocrTesseract.Configuration.RenderSearchablePdf = true;

// Wrap the TIFF in OcrImageInput: handles DPI detection and page layout automatically
using var imageInput = new OcrImageInput("Potter.tiff");
// Run OCR; returns a result containing the recognized text and spatial layout data
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Write the output: the original scanned image is preserved with an invisible text layer on top
ocrResult.SaveAsSearchablePdf("searchablePdf.pdf");

輸出

searchablePdf.pdf:可搜尋 PDF 輸出檔。請選取或搜尋任何單字,以驗證 OCR 文字層。

產生的 PDF 會嵌入原始掃描頁面的影像,並在每個辨識出的單字上疊加隱形文字層。請在 PDF 檢視器中選取或搜尋任一單字,確認文字層是否存在。

IronOCR 採用特定字型進行疊加顯示,因此呈現的的文字大小可能與原始內容略有差異。

處理多頁 TIFF 檔案或複雜文件時,IronOCR 會自動處理所有頁面並納入輸出。程式庫會自動排序頁面並定位疊加的文字,讓文字能準確對應到影像。

如何從照片或進階文件掃描建立可搜尋的 PDF?

ReadPhoto、ReadScreenShot 和 ReadDocumentAdvanced 回傳的結果類型都支援 SaveAsSearchablePdf,可將結果匯出為可搜尋的 PDF。

呼叫這些方法時,可以選擇是否傳入 ModelType。預設值是 Normal,Enhanced 的準確度較高,但處理速度較慢。

輸入

透過 LoadImage 載入一張帶有彩繪文字的壁畫照片。場景中有多處文字,適合用來測試 ReadPhoto 搭配 Enhanced 模型辨識實際場景文字的效果。

作為 ReadPhoto OCR 輸入的含文字照片

photo.png:透過 ReadPhoto 搭配 Enhanced 模型載入的壁畫照片,用以產生可搜尋的 PDF 檔案。

using IronOcr;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("photo.png");

// ReadPhoto with Enhanced model
OcrPhotoResult photoResult = ocr.ReadPhoto(input, ModelType.Enhanced);
Console.WriteLine(photoResult.Text);

// Save as searchable PDF
byte[] pdfBytes = photoResult.SaveAsSearchablePdfBytes();
File.WriteAllBytes("searchable-photo.pdf", pdfBytes);

輸出

searchable-photo.pdf:由 ReadPhoto 產出的可搜尋 PDF。其文字層可在任何 PDF 檢視器中支援全文搜尋。

產生的可搜尋 PDF 會在辨識出的文字上疊加隱形文字層。在 PDF 檢視器中搜尋「Milk」會找到 3 筆符合的結果,這些文字皆取自原始照片中的彩繪文字。

相同的方法也適用於 ReadDocumentAdvanced,該方法會回傳 OcrDocAdvancedResult:

輸入

使用 LoadImage 載入掃描的發票。發票包含供應商名稱、明細項目和總金額等結構化欄位。ReadDocumentAdvanced 搭配 Enhanced 模型辨識這些欄位後,會將辨識結果嵌入可搜尋的文字層。

用作 ReadDocumentAdvanced OCR 輸入的發票文件

invoice.png:掃描後的發票已載入 OcrInput,再傳給 ReadDocumentAdvanced 搭配 Enhanced 模型處理。

using IronOcr;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("invoice.png");

// ReadDocumentAdvanced with Enhanced model
OcrDocAdvancedResult docResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced);
byte[] docPdfBytes = docResult.SaveAsSearchablePdfBytes();
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes);

輸出

searchable-doc.pdf:由 ReadDocumentAdvanced 產出的可搜尋 PDF。發票欄位可供選取與搜尋。

警告: SaveAsSearchablePdf 不支援 ReadPassport 或 ReadLicensePlate 的結果,將拋出 ExtensionAdvancedScanException。

處理多頁文件

在處理多頁文件的 PDF OCR 作業時,IronOCR 會依序處理每一頁,並保留原始文件的結構。

輸入

透過 OcrPdfInput 載入 Hartwell Capital Management 的 11 頁年報。使用 PageIndices 指定第 1 到 10 頁(索引 0 到 9),並在一次 Read 呼叫中處理這些頁面。

multi-page-scan.pdf:一份 11 頁的 Hartwell Capital Management 年報,用作多頁可搜尋 PDF 轉換的輸入檔案。

using IronOcr;
using System.Linq;

// Create the OCR engine. RenderSearchablePdf is false by default; no need to set it when using OcrPdfInput directly
var ocrTesseract = new IronTesseract();

// Load pages 1–10 (indices 0–9) only; PageIndices avoids loading and OCR-ing the full document unnecessarily
using var pdfInput = new OcrPdfInput("multi-page-scan.pdf", PageIndices: Enumerable.Range(0, 10));

// Run OCR across all selected pages in order
OcrResult result = ocrTesseract.Read(pdfInput);

// Write the searchable PDF; true = apply the input's image filters to the embedded page images in the output
result.SaveAsSearchablePdf("searchable-multi-page.pdf", true);

輸出

searchable-multi-page.pdf:10 頁的可搜尋 PDF 輸出檔。每頁皆含一個隱形文字層,以支援全文檢索。

輸出的 PDF 包含原始年報的第 1 到 10 頁,共 10 頁。每頁都有一層隱形文字,可在任何 PDF 檢視器中選取及搜尋擷取出的內容。

建立可搜尋的 PDF 時,如何套用濾鏡?

SaveAsSearchablePdf 的第二個參數接受布林值,用來控制是否對嵌入輸出的影像套用濾鏡。使用影像最佳化濾鏡可大幅提升 OCR 準確度,尤其是在處理低品質掃描時。

下方範例會套用灰階濾鏡,並傳入 true 作為第二個參數,將套用濾鏡後的影像嵌入可搜尋的 PDF。

using IronOcr;

// Create OCR engine: filters are applied at the OcrInput level, so no configuration changes are needed here
var ocr = new IronTesseract();
var ocrInput = new OcrInput();

// Load the scanned PDF as the OCR source
ocrInput.LoadPdf("invoice.pdf");

// Convert to grayscale: removes color noise that can reduce OCR accuracy on color-printed documents
ocrInput.ToGrayScale();
// Run OCR on the preprocessed input
OcrResult result = ocr.Read(ocrInput);

// Write the searchable PDF; true = embed the grayscale-filtered image rather than the original color scan
result.SaveAsSearchablePdf("outputGrayscale.pdf", true);

為取得最佳結果,可使用濾鏡精靈找出適合該文件類型的濾鏡組合。此工具會分析輸入,並建議合適的前處理步驟。

如何修復可搜尋PDF中的錯誤字元?

如果 PDF 上的文字看起來正常,但搜尋或複製時出現亂碼,原因是可搜尋文字層使用的預設字型。SaveAsSearchablePdf 預設使用 Times New Roman,這個字型無法完整支援所有 Unicode 字元,因此會影響含有重音字元或非 ASCII 字元的語言。

要解決這個問題,請提供與 Unicode 相容的字型檔案作為第三個參數:

result.SaveAsSearchablePdf("output.pdf", false, "Fonts/LiberationSerif-Regular.ttf");

您也可以將自訂字型名稱指定為第四個參數:

result.SaveAsSearchablePdf("output.pdf", false, "Fonts/LiberationSerif-Regular.ttf", "MyFont");

這項修正適用於所有結果類型,包括 OcrResult、OcrPhotoResult 和 OcrDocAdvancedResult,無論結果由哪個讀取方法產生皆可使用。

請注意: 對於最初使用Times New Roman排版的文件,推薦使用Liberation Serif,因為它在度量上兼容,可保留原始間距和佈局。 針對一般用途的多語言使用,Noto Sans或DejaVu Sans是很好的替代選擇。

若無法寫入檔案路徑,IronOCR 亦支援將可搜尋的 PDF 以位元組陣列或串流形式回傳。


如何將可搜尋的 PDF 匯出為位元組或串流?

您也可以使用 SaveAsSearchablePdfBytes 或 SaveAsSearchablePdfStream,分別以位元組或串流處理可搜尋的 PDF 輸出。以下程式碼範例示範這兩個方法的用法。

// Return as a byte array: suited for storing in a database or sending in an HTTP response body
byte[] pdfByte = ocrResult.SaveAsSearchablePdfBytes();

// Return as a stream: suited for uploading to cloud storage or piping to another I/O operation without buffering the full file
Stream pdfStream = ocrResult.SaveAsSearchablePdfStream();

在與檔案系統存取可能受限的雲端儲存服務、資料庫或網路應用程式整合時,這些輸出選項尤其有用。 以下範例展示實際應用:

using IronOcr;
using System.IO;

public class SearchablePdfExporter
{
    public async Task ProcessAndUploadPdf(string inputPath)
    {
        var ocr = new IronTesseract
        {
            Configuration = { RenderSearchablePdf = true }
        };
        
        // Process the input
        using var input = new OcrImageInput(inputPath);
        var result = ocr.Read(input);
        
        // Option 1: Save to database as byte array
        byte[] pdfBytes = result.SaveAsSearchablePdfBytes();
        // Store pdfBytes in database BLOB field
        
        // Option 2: Upload to cloud storage using stream
        using (Stream pdfStream = result.SaveAsSearchablePdfStream())
        {
            // Upload stream to Azure Blob Storage, AWS S3, etc.
            await UploadToCloudStorage(pdfStream, "searchable-output.pdf");
        }
        
        // Option 3: Return as web response
        // return File(pdfBytes, "application/pdf", "searchable.pdf");
    }
    
    private async Task UploadToCloudStorage(Stream stream, string fileName)
    {
        // Cloud upload implementation
    }
}

效能考量

處理大量文件時,可以實作多執行緒 OCR 作業以提高處理量。IronOCR 支援同時處理多份文件。

這裡有兩層平行處理。外層迴圈會同時分派多份文件,而每次 Read 呼叫又會在內部同時對多個頁面執行 OCR,每個同時處理的頁面各使用一個原生 Tesseract 引擎。兩層的平行度會相乘,因此請分別設定上限:外層迴圈使用 ParallelOptions.MaxDegreeOfParallelism,內層讀取則使用 IronTesseract.MaxDegreeOfParallelism。

using IronOcr;
using System.Threading.Tasks;
using System.Collections.Concurrent;

public class BatchPdfProcessor
{
    private readonly IronTesseract _ocr;
    
    public BatchPdfProcessor()
    {
        _ocr = new IronTesseract
        {
            // Configure for optimal performance
            Language = OcrLanguage.English,
            // Cap the pages read concurrently inside each Read call
            MaxDegreeOfParallelism = 2,
            Configuration = 
            {
                RenderSearchablePdf = true
            }
        };
    }
    
    public async Task ProcessBatchAsync(string[] filePaths)
    {
        var results = new ConcurrentBag<(string source, string output)>();
        
        // Cap how many documents are dispatched at once as well
        var options = new ParallelOptions { MaxDegreeOfParallelism = 4 };
        
        await Parallel.ForEachAsync(filePaths, options, async (filePath, ct) =>
        {
            using var input = new OcrImageInput(filePath);
            var result = _ocr.Read(input);
            
            string outputPath = Path.ChangeExtension(filePath, ".searchable.pdf");
            result.SaveAsSearchablePdf(outputPath);
            
            results.Add((filePath, outputPath));
        });
        
        Console.WriteLine($"Processed {results.Count} files");
    }
}

進階設定選項

在更進階的使用情境中,您可以透過詳細的 Tesseract 設定,依文件類型或語言微調 OCR 引擎:

var advancedOcr = new IronTesseract
{
    Configuration = 
    {
        RenderSearchablePdf = true,
        TesseractVariables = new Dictionary<string, object>
        {
            { "preserve_interword_spaces", 1 },
            { "tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" }
        },
        PageSegmentationMode = TesseractPageSegmentationMode.SingleColumn
    },
    Language = OcrLanguage.EnglishBest
};

這些設定選項同樣適用於所有三種輸出方法:SaveAsSearchablePdf、SaveAsSearchablePdfBytes 和 SaveAsSearchablePdfStream。 下方的摘要彙整了所有可搜尋的 PDF 處理方法及其對應的輸出格式。

總結

使用 IronOCR 建立可搜尋的 PDF 簡單又有彈性。無論是單張影像、多頁文件、以 ReadPhoto 讀取的照片,或以 ReadDocumentAdvanced 進行的進階文件掃描,程式庫都能可靠地以多種格式輸出可搜尋的 PDF。您可以使用 ModelType 參數,在標準和增強型機器學習模型之間選擇,以符合辨識準確度需求。輸出可採用檔案、位元組或串流,適用於桌面應用程式和雲端服務等不同架構。

若要了解更進階的 OCR 用法,請參考完整的程式碼範例或查閱 API 文件,取得詳細的方法簽章和選項。

常見問題

什麼是可搜尋的PDF,以及如何使用IronOCR創建它?

可搜尋的PDF是一種結合掃描圖像和機器可讀文本的PDF文件。通過對掃描文件進行OCR,將圖像中的文本轉換成可搜尋文本,即可使用IronOCR創建它。在C#中,通過將'RenderSearchablePdf'配置設為true並使用'SaveAsSearchablePdf'方法來完成。

IronOCR能否處理多頁文件轉換為可搜尋PDF?

是的,IronOCR可以處理多頁文件。在使用'OcrPdfInput'時,IronOCR按順序處理每一頁並保持原始結構,使多頁文件可以轉換為可搜尋的PDF。

如何使用IronOCR將OCR結果匯出為可搜尋的PDF?

要將OCR結果匯出為可搜尋的PDF,請將'Configuration.RenderSearchablePdf'屬性設為true,運行'Read'方法以獲取OCR結果,然後使用'SaveAsSearchablePdf'將結果匯出到文件路徑。

IronOCR在匯出可搜尋的PDF時有哪些選擇?

IronOCR允許通過'SaveAsSearchablePdf'、'SaveAsSearchablePdfBytes'和'SaveAsSearchablePdfStream'等方法匯出可搜尋的PDF作為文件、字節數組或流。這些選項提供了與雲端儲存或數據庫整合的靈活性。

IronOCR能否從照片或高級文件掃描中生成可搜尋的PDF?

是的,IronOCR支持使用'ReadPhoto'從照片生成可搜尋PDF,並使用'ReadDocumentAdvanced'從高級文件掃描生成可搜尋PDF。這兩種方法均可將結果匯出為可搜尋的PDF。

IronOCR如何提高低品質掃描的OCR準確度?

IronOCR通過應用圖像優化濾鏡來提高低品質掃描的OCR準確度。例如,使用'ToGrayScale'方法可以減少顏色雜訊,有助於增強文本識別。

如何修正IronOCR生成的可搜尋PDF中錯誤的字符?

可搜尋PDF中的錯誤字符可以通過在使用'SaveAsSearchablePdf'時指定支持Unicode的字體來修正。這可以完整支持所有的Unicode字符,解決非ASCII字符的問題。

是否有方法優化IronOCR在處理大量文件時的性能?

是的,IronOCR支持並發處理,允許您實現多執行緒的OCR操作。這有助於同時處理多個文件,提高處理大量文件時的吞吐量。

IronOCR在創建可搜尋PDF時有哪些進階的配置選項?

IronOCR提供了進階的配置選項,包括詳細的Tesseract配置、設置Tesseract變量以及選擇不同的頁面分隔模式。這些可以根據特定的文件類型或語言進行定製,以微調OCR。

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

閱讀更多

準備好開始了嗎?

NuGet 下載次數 6,411,693版本:2026.11剛剛發布