如何在 C# 中將結果儲存為可搜尋的 PDF

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

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronOCR 讓 C# 開發人員能夠利用 OCR 技術,將掃描的文件和圖像轉換為可搜尋的 PDF 檔案,僅需幾行程式碼即可支援以檔案、位元組或資料流的形式輸出。

可搜尋的 PDF(常稱為 OCR(光學字元辨識)PDF)是一種同時包含掃描影像與機器可讀文字的 PDF 文件。 這些 PDF 檔案是透過對掃描的紙本文件或圖像執行 OCR 處理所產生,其過程包含識別圖像中的文字,並將其轉換為可選取及可搜尋的文字。

SaveAsSearchablePdf 亦可應用於 ReadScreenShotReadDocumentAdvanced 的搜尋結果,支援透過照片及進階文件 OCR 工作流程建立可搜尋的 PDF 檔案。 此功能在將紙本檔案數位化,或使舊版 PDF 文件具備搜尋功能以提升文件管理效率時,尤為實用。

快速入門:一行指令即可匯出可搜尋的 PDF

設定 RenderSearchablePdf = true,在您的輸入資料上執行 Read(...),並呼叫 SaveAsSearchablePdf(...)。 只需如此,即可使用 IronOCR 生成一份可完整搜尋的 PDF 檔案。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronOcr

    PM > Install-Package IronOcr
  2. 請複製並執行此程式碼片段。

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

    立即透過免費試用,在您的專案中開始使用 IronOCR

    arrow pointer


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

若要使用 IronOCR 將結果匯出為可搜尋的 PDF,請將 Configuration.RenderSearchablePdf 屬性設定為 true,從 Read 方法取得 OCR 結果物件,並傳入輸出檔案路徑來呼叫 SaveAsSearchablePdf

輸入

《哈利波特》小說中的一頁,已掃描為 TIFF 檔案並透過 OcrImageInput 載入。 該頁面包含密集的印刷文字,是測試可搜尋 PDF 文字層的理想素材。

《哈利波特》書頁,顯示第八章

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

:path=/static-assets/ocr/content-code-examples/how-to/searchable-pdf-searchable-pdf.cs
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");
Imports IronOcr

' Create the OCR engine: defaults to English with balanced speed and accuracy
Dim ocrTesseract As 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 imageInput As New OcrImageInput("Potter.tiff")
    ' Run OCR; returns a result containing the recognized text and spatial layout data
    Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

    ' Write the output: the original scanned image is preserved with an invisible text layer on top
    ocrResult.SaveAsSearchablePdf("searchablePdf.pdf")
End Using
$vbLabelText   $csharpLabel

輸出

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

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

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

在處理多頁 TIFF 檔案或複雜文件時,IronOCR 會自動處理所有頁面並將其納入輸出結果中。 該函式庫會自動處理頁面排序與文字疊加定位,確保文字與影像的對應精準無誤。

如何將照片或高解析度掃描文件轉為可搜尋的 PDF 檔案?

使用 ReadScreenShotReadDocumentAdvanced 時,亦可輸出可搜尋的 PDF 檔案。 這些方法各自返回的結果類型皆支援 SaveAsSearchablePdf

您可選擇在呼叫這些方法時傳入 ModelType。 預設選項為 Normal,而 Enhanced 雖以犧牲速度為代價,但能提供更高的精準度。

輸入

一張透過 LoadImage 載入的牆面壁畫照片,上面繪有文字。 此情境包含嵌入真實世界環境中的多個 WORD,因此是對 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.SaveAsSearchablePdf();
File.WriteAllBytes("searchable-photo.pdf", pdfBytes);
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.SaveAsSearchablePdf();
File.WriteAllBytes("searchable-photo.pdf", pdfBytes);
Imports IronOcr

Dim ocr As New IronTesseract()
Using input As New OcrInput()
    input.LoadImage("photo.png")

    ' ReadPhoto with Enhanced model
    Dim photoResult As OcrPhotoResult = ocr.ReadPhoto(input, ModelType.Enhanced)
    Console.WriteLine(photoResult.Text)

    ' Save as searchable PDF
    Dim pdfBytes As Byte() = photoResult.SaveAsSearchablePdf()
    File.WriteAllBytes("searchable-photo.pdf", pdfBytes)
End Using
$vbLabelText   $csharpLabel

輸出

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

生成的可搜尋 PDF 會在識別出的文字上方疊加一層隱形文字層。 在 PDF 檢視器中搜尋"Milk"會找到 3 個匹配結果,這些內容直接從原始照片中的塗繪文字中提取。

此方法同樣適用於 ReadDocumentAdvanced,其會返回 OcrDocAdvancedResult

輸入

透過 LoadImage 載入的掃描發票。 它包含結構化欄位(供應商名稱、明細項目和總計),這些欄位會與 ReadDocumentAdvanced 模型進行整合,並被 Enhanced 模型識別並嵌入為可搜尋的文字層。

用作 ReadDocumentAdvanced OCR 輸入的發票文件

invoice.png:掃描後的發票已載入 OcrInput,並透過增強型模型傳遞至 ReadDocumentAdvanced。

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.SaveAsSearchablePdf();
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes);
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.SaveAsSearchablePdf();
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes);
Imports IronOcr

Dim ocr As New IronTesseract()
Using input As New OcrInput()
    input.LoadImage("invoice.png")

    ' ReadDocumentAdvanced with Enhanced model
    Dim docResult As OcrDocAdvancedResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced)
    Dim docPdfBytes As Byte() = docResult.SaveAsSearchablePdf()
    File.WriteAllBytes("searchable-doc.pdf", docPdfBytes)
End Using
$vbLabelText   $csharpLabel

輸出

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

SaveAsSearchablePdf 不支援 ReadPassportReadLicensePlate 的結果,並會拋出 ExtensionAdvancedScanException

處理多頁文件

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

輸入

OcrPdfInput 載入的 Hartwell Capital Management 11 頁年度報告。 透過 PageIndices 範圍選取第 1 至 10 頁(索引 0 至 9),並在單一 Read 呼叫中進行處理。

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

:path=/static-assets/ocr/content-code-examples/how-to/searchable-pdf-multi-page.cs
using IronOcr;

// 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);
Imports IronOcr

' Create the OCR engine. RenderSearchablePdf is false by default; no need to set it when using OcrPdfInput directly
Dim ocrTesseract As New IronTesseract()

' Load pages 1–10 (indices 0–9) only; PageIndices avoids loading and OCR-ing the full document unnecessarily
Using pdfInput As New OcrPdfInput("multi-page-scan.pdf", PageIndices:=Enumerable.Range(0, 10))
    ' Run OCR across all selected pages in order
    Dim result As OcrResult = 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)
End Using
$vbLabelText   $csharpLabel

輸出

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

生成的 PDF 文件共 10 頁(源自原始報告的第 1 至 10 頁),每頁均含一個隱形文字圖層,使提取的內容可在任何 PDF 檢視器中進行選取與搜尋。

如何在建立可搜尋 PDF 時套用篩選條件?

SaveAsSearchablePdf 第二個參數接受一個布林值,用以控制是否對嵌入式輸出套用影像濾鏡。 使用影像優化濾鏡可顯著提升 OCR 準確度,特別是在處理低品質掃描檔時。

以下範例應用灰階濾鏡,並將 true 作為第二個參數傳入,以將經過濾鏡處理的圖片嵌入可搜尋的 PDF/A 輸出檔中。

:path=/static-assets/ocr/content-code-examples/how-to/image-quality-correction-searchable-pdf.cs
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);
Imports IronOcr

' Create OCR engine: filters are applied at the OcrInput level, so no configuration changes are needed here
Dim ocr As New IronTesseract()
Dim ocrInput As 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
Dim result As OcrResult = ocr.Read(ocrInput)

' Write the searchable PDF; True = embed the grayscale-filtered image rather than the original color scan
result.SaveAsSearchablePdf("outputGrayscale.pdf", True)
$vbLabelText   $csharpLabel

為獲得最佳效果,建議使用"篩選器精靈"自動為您的特定文件類型確定最佳的篩選器組合。 此工具會分析您的輸入內容,並建議適當的預處理步驟。

如何修正可搜尋 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");
result.SaveAsSearchablePdf("output.pdf", False, "Fonts/LiberationSerif-Regular.ttf")
$vbLabelText   $csharpLabel

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

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

此修正適用於所有結果類型,包括 OcrPhotoResultOcrDocAdvancedResult,因此無論結果由哪種讀取方法產生,此修正皆能生效。

請注意對於原始排版使用 Times New Roman 的文件,建議採用 Liberation Serif,因其字距相容性良好,可保留原始的間距與版面配置。 若需通用多語言用途,Noto Sans 或 DejaVu Sans 都是不錯的替代選項。)}]

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


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

可搜尋 PDF 的輸出內容亦可透過 SaveAsSearchablePdfBytesSaveAsSearchablePdfStream 方法,分別以位元組或串流形式進行處理。 以下程式碼範例展示了如何使用這些方法。

:path=/static-assets/ocr/content-code-examples/how-to/searchable-pdf-searchable-pdf-byte-stream.cs
// 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();
' Return as a byte array: suited for storing in a database or sending in an HTTP response body
Dim pdfByte As Byte() = ocrResult.SaveAsSearchablePdfBytes()

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

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

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
    }
}
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
    }
}
Imports IronOcr
Imports System.IO
Imports System.Threading.Tasks

Public Class SearchablePdfExporter
    Public Async Function ProcessAndUploadPdf(inputPath As String) As Task
        Dim ocr As New IronTesseract With {
            .Configuration = New TesseractConfiguration With {
                .RenderSearchablePdf = True
            }
        }

        ' Process the input
        Using input As New OcrImageInput(inputPath)
            Dim result = ocr.Read(input)

            ' Option 1: Save to database as byte array
            Dim pdfBytes As Byte() = result.SaveAsSearchablePdfBytes()
            ' Store pdfBytes in database BLOB field

            ' Option 2: Upload to cloud storage using stream
            Using pdfStream As Stream = result.SaveAsSearchablePdfStream()
                ' Upload stream to Azure Blob Storage, AWS S3, etc.
                Await UploadToCloudStorage(pdfStream, "searchable-output.pdf")
            End Using

            ' Option 3: Return as web response
            ' Return File(pdfBytes, "application/pdf", "searchable.pdf")
        End Using
    End Function

    Private Async Function UploadToCloudStorage(stream As Stream, fileName As String) As Task
        ' Cloud upload implementation
    End Function
End Class
$vbLabelText   $csharpLabel

效能考量

在處理大量文件時,請考慮實作多執行緒 OCR 操作以提升處理量。 IronOCR 支援並行處理,讓您能同時處理多份文件:

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

public class BatchPdfProcessor
{
    private readonly IronTesseract _ocr;

    public BatchPdfProcessor()
    {
        _ocr = new IronTesseract
        {
            Configuration = 
            {
                RenderSearchablePdf = true,
                // Configure for optimal performance
                Language = OcrLanguage.English
            }
        };
    }

    public async Task ProcessBatchAsync(string[] filePaths)
    {
        var results = new ConcurrentBag<(string source, string output)>();

        await Parallel.ForEachAsync(filePaths, 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");
    }
}
using IronOcr;
using System.Threading.Tasks;
using System.Collections.Concurrent;

public class BatchPdfProcessor
{
    private readonly IronTesseract _ocr;

    public BatchPdfProcessor()
    {
        _ocr = new IronTesseract
        {
            Configuration = 
            {
                RenderSearchablePdf = true,
                // Configure for optimal performance
                Language = OcrLanguage.English
            }
        };
    }

    public async Task ProcessBatchAsync(string[] filePaths)
    {
        var results = new ConcurrentBag<(string source, string output)>();

        await Parallel.ForEachAsync(filePaths, 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");
    }
}
Imports IronOcr
Imports System.Threading.Tasks
Imports System.Collections.Concurrent

Public Class BatchPdfProcessor
    Private ReadOnly _ocr As IronTesseract

    Public Sub New()
        _ocr = New IronTesseract With {
            .Configuration = New OcrConfiguration With {
                .RenderSearchablePdf = True,
                ' Configure for optimal performance
                .Language = OcrLanguage.English
            }
        }
    End Sub

    Public Async Function ProcessBatchAsync(filePaths As String()) As Task
        Dim results As New ConcurrentBag(Of (source As String, output As String))()

        Await Task.Run(Sub()
                           Parallel.ForEach(filePaths, Sub(filePath)
                                                           Using input As New OcrImageInput(filePath)
                                                               Dim result = _ocr.Read(input)

                                                               Dim outputPath As String = Path.ChangeExtension(filePath, ".searchable.pdf")
                                                               result.SaveAsSearchablePdf(outputPath)

                                                               results.Add((filePath, outputPath))
                                                           End Using
                                                       End Sub)
                       End Sub)

        Console.WriteLine($"Processed {results.Count} files")
    End Function
End Class
$vbLabelText   $csharpLabel

進階設定選項

針對更複雜的場景,您可以利用 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
};
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
};
Imports IronOcr

Dim advancedOcr As New IronTesseract With {
    .Configuration = New TesseractConfiguration With {
        .RenderSearchablePdf = True,
        .TesseractVariables = New Dictionary(Of String, Object) From {
            {"preserve_interword_spaces", 1},
            {"tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"}
        },
        .PageSegmentationMode = TesseractPageSegmentationMode.SingleColumn
    },
    .Language = OcrLanguage.EnglishBest
}
$vbLabelText   $csharpLabel

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

摘要

使用 IronOCR 建立可搜尋的 PDF 檔案既簡單又靈活。 無論您需要處理單一圖像、多頁文件、透過 ReadPhoto 處理的照片,或是透過 ReadDocumentAdvanced 處理的高階文件掃描檔,此函式庫皆提供強大的方法,可產生多種格式的可搜尋 PDF 檔案。 請使用 ModelType 參數,在標準與增強型機器學習模型之間進行選擇,以確保翻譯準確性。 其支援以檔案、位元組或串流形式匯出的功能,使其能適應任何應用程式架構,從桌面應用程式到雲端服務皆然。

若需處理更進階的 OCR 情境,請參閱詳盡的程式碼範例,或查閱 API 文件以了解詳細的方法簽名與選項。

常見問題

如何使用 C# 從掃描的圖像建立可搜尋的 PDF?

IronOCR 讓您能輕鬆地從掃描影像建立可搜尋的 PDF 檔案。只需在設定中將 RenderSearchablePdf 設為 true,對輸入影像使用 Read() 方法,並傳入您想要的輸出路徑來呼叫 SaveAsSearchablePdf()。IronOCR 將對影像執行 OCR 處理,並產生一個 PDF 檔案,其中可選取且可搜尋的文字會疊加在原始影像上。

哪些檔案格式可以轉換為可搜尋的 PDF 檔案?

IronOCR 可將各種圖像格式(包括 JPG、PNG、TIFF)以及現有的 PDF 文件轉換為可搜尋的 PDF。IronOCR程式庫同時支援單頁圖像與多頁文件(如 TIFF 檔案),能自動處理所有頁面,並在輸出之可搜尋 PDF 中維持正確的頁面順序。

能否將可搜尋的 PDF 匯出為位元組陣列或串流,而非檔案?

是的,IronOCR 支援以多種格式匯出可搜尋的 PDF 檔案。除了使用 SaveAsSearchablePdf() 直接儲存為檔案外,您也可以將 OCR 結果匯出為位元組陣列或資料流,讓您無需建立臨時檔案,即可輕鬆整合至網頁應用程式、雲端儲存或資料庫系統中。

建立可搜尋 PDF 所需的最低程式碼量為何?

使用 IronOCR 建立可搜尋的 PDF 只需一行程式碼:new IronOcr.IronTesseract { Configuration = { RenderSearchablePdf = true } }.Read(new IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf")。這充分展現了 IronOCR 簡潔的 API 設計。

在可搜尋的 PDF 中,隱形文字層是如何運作的?

IronOCR 會自動將辨識出的文字定位為 PDF 原始影像上方的隱形圖層。此機制確保文字與影像的精準對應,讓使用者能在維持原始文件視覺外觀的同時,選取並搜尋文字內容。該程式庫透過專用字型與定位演算法來實現此功能。

我可以將照片或螢幕截圖轉為可搜尋的 PDF 檔案嗎?

是的,ReadPhotoReadScreenShotReadDocumentAdvanced 的結果皆支援 SaveAsSearchablePdf 功能。每個方法返回的結果類型均支援可搜尋 PDF 匯出,讓您能輕鬆將實際照片、螢幕截圖或複雜的文件掃描檔轉換為可搜尋的 PDF 檔案。

ModelType 參數的作用是什麼?

ModelType 參數用於控制 OCR 所使用的預訓練機器學習模型。預設值為 Normal,會將圖片調整為 960 像素以獲得快速結果;Enhanced 則支援最高 2560 像素的圖片,能保留更細緻的細節,並針對高解析度輸入提升準確度。

為何我在可搜尋 PDF 中複製或搜尋的字元會顯示為亂碼?

發生這種情況是因為可搜尋文字層所使用的預設字型(Times New Roman)並未完全支援所有 Unicode 字元。要解決此問題,請將相容於 Unicode 的字型檔案作為 SaveAsSearchablePdf 的第三個參數傳入。若您的文件原始排版使用的是 Times New Roman,且發現與其他字型在間距上不一致,請嘗試使用 Liberation Serif,因為它具有相同的字形度量,並能保留原始版面配置。

IronOCR 如何提升資料準確性?

IronOCR 透過其先進的辨識演算法與影像校正功能來提升資料準確性,確保文字擷取過程既可靠又精確。

IronOCR 是否有提供免費試用版?

是的,Iron Software 提供 IronOCR 的免費試用版,讓使用者能在決定購買前測試其功能與效能。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

審閱者:
Jeff Fritz
Jeffrey T. Fritz
首席程式經理 - .NET 社群團隊
Jeff 同時也是 .NET 與 Visual Studio 團隊的首席程式經理。他是 .NET Conf 虛擬會議系列的執行製作人,並主持每週播出兩次的開發者直播節目《Fritz and Friends》,在節目中他會與觀眾一起探討技術話題並共同編寫程式碼。Jeff 負責撰寫工作坊內容、準備簡報,並為 Microsoft Build、Microsoft Ignite、.NET Conf 以及 Microsoft MVP Summit 等微軟最大規模的開發者活動規劃內容。
準備開始了嗎?
Nuget 下載 5,896,332 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronOcr
執行範例 觀看您的圖片轉為可搜尋文字。