使用IronOCR在C#中保存可搜索PDF
IronOCR 使C#开发人员能够使用OCR技术将扫描文档和图像转换为可搜索的PDF,仅需几行代码即可支持以文件、字节或流形式输出。
可搜索的 PDF 通常也称为 OCR(光学字符识别)PDF,同时包含扫描图像和机器可读文本。对扫描的纸质文档或图像执行 OCR,即可识别图像中的文字,生成可选择、可搜索的文本。
SaveAsSearchablePdf 也适用于来自 ReadPhoto、ReadScreenShot 和 ReadDocumentAdvanced 的结果,从而支持从照片和高级文档OCR工作流创建可搜索PDF。 在将纸质档案数字化或使旧版 PDF 文件可搜索以实现更佳文档管理时,此功能尤为实用。
设置 RenderSearchablePdf = true,调用 Read(...) 识别输入,再调用 SaveAsSearchablePdf(...)。只需这几步,即可使用 IronOCR 生成可全文搜索的 PDF。
-
1使用 IronOCR 安装 NuGet Package Manager
-
2复制并运行这段代码。
new IronOcr.IronTesseract { Configuration = { RenderSearchablePdf = true } } .Read(new IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf");Dim Ocr = New IronOcr.IronTesseract With { .Configuration = { .RenderSearchablePdf = True } } Ocr.Read(New IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf")Dim Ocr = New IronOcr.IronTesseract With { .Configuration = { .RenderSearchablePdf = True } } Ocr.Read(New IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf") -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronOCR
基本流程(5 步)
- 下载一个C#库以将结果保存为可搜索的PDF
- 为OCR准备图像和PDF文档
- 将RenderSearchablePdf属性设置为
true - 使用
SaveAsSearchablePdf方法输出可搜索的 PDF 文件 - 将可搜索的 PDF 导出为字节流
如何将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");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 UsingImports 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输出
searchablePdf.pdf:可搜索的 PDF 输出文件。请选中或搜索任意单词,以验证 OCR 文本层。
生成的 PDF 会嵌入扫描页面的原始图像,并在识别出的每个单词上叠加不可见的文本层。在 PDF 阅读器中选择或搜索任意单词,即可确认文本层是否存在。
IronOCR 在叠加层中使用了特定字体,这可能会导致渲染后的文本大小与原文存在轻微差异。
在处理多页TIFF文件或复杂文档时,IronOCR会自动处理所有页面并将其包含在输出中。 该库可自动处理页面排序和文本叠加定位,确保文本到图像的映射准确无误。
如何从照片或高级文档扫描创建可搜索的 PDF?
在使用 ReadPhoto、ReadScreenShot 或 ReadDocumentAdvanced 时,也可以导出可搜索PDF。 这些方法中的每一个都会返回支持SaveAsSearchablePdf的结果类型。
调用这些方法时,您可以选择传递一个ModelType。 默认值是 Normal,而 Enhanced 提供更高的精度,但速度较慢。
输入
通过 LoadImage 加载一张绘有文字的墙面壁画照片。照片包含现实场景中的多个单词,适合用来测试 ReadPhoto 的 Enhanced 模型。

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);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);Imports IronOcr
Dim ocr = New IronTesseract()
Using input = 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.SaveAsSearchablePdfBytes()
File.WriteAllBytes("searchable-photo.pdf", pdfBytes)
End UsingImports IronOcr
Dim ocr = New IronTesseract()
Using input = 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.SaveAsSearchablePdfBytes()
File.WriteAllBytes("searchable-photo.pdf", pdfBytes)
End Using输出
searchable-photo.pdf:由 ReadPhoto 生成的可搜索 PDF。其文本层支持在任何 PDF 阅读器中进行全文搜索。
生成的可搜索 PDF 在识别出的文字上叠加了不可见的文本层。在 PDF 阅读器中搜索“Milk”会找到 3 处匹配,均直接提取自原照片中绘制的文字。
相同的方式也适用于 ReadDocumentAdvanced,它返回一个 OcrDocAdvancedResult:
输入
通过 LoadImage 加载扫描发票。发票包含供应商名称、明细项和合计金额等结构化字段。使用 ReadDocumentAdvanced 的 Enhanced 模型识别这些字段,并将其嵌入可搜索的文本层。

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);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);Imports IronOcr
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage("invoice.png")
' ReadDocumentAdvanced with Enhanced model
Dim docResult As OcrDocAdvancedResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced)
Dim docPdfBytes As Byte() = docResult.SaveAsSearchablePdfBytes()
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes)
End UsingImports IronOcr
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage("invoice.png")
' ReadDocumentAdvanced with Enhanced model
Dim docResult As OcrDocAdvancedResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced)
Dim docPdfBytes As Byte() = docResult.SaveAsSearchablePdfBytes()
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes)
End Using输出
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);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);Imports IronOcr
Imports System.Linq
' Create the OCR engine. RenderSearchablePdf is false by default; no need to set it when using OcrPdfInput directly
Dim ocrTesseract = New IronTesseract()
' Load pages 1–10 (indices 0–9) only; PageIndices avoids loading and OCR-ing the full document unnecessarily
Using pdfInput = 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 UsingImports IronOcr
Imports System.Linq
' Create the OCR engine. RenderSearchablePdf is false by default; no need to set it when using OcrPdfInput directly
Dim ocrTesseract = New IronTesseract()
' Load pages 1–10 (indices 0–9) only; PageIndices avoids loading and OCR-ing the full document unnecessarily
Using pdfInput = 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输出
searchable-multi-page.pdf:生成的 10 页可搜索 PDF。每页均包含用于全文搜索的不可见文本层。
生成的PDF包含10页(原始报告的页面1-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);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)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)可使用滤镜向导自动选择适合当前文档类型的最佳滤镜组合。该工具会分析输入并推荐预处理步骤。
如何修复可搜索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")result.SaveAsSearchablePdf("output.pdf", False, "Fonts/LiberationSerif-Regular.ttf")您还可以将自定义字体名称指定为第四个参数:
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")result.SaveAsSearchablePdf("output.pdf", False, "Fonts/LiberationSerif-Regular.ttf", "MyFont")此方法适用于所有结果类型,包括 OcrResult、OcrPhotoResult 和 OcrDocAdvancedResult,与生成结果时使用的读取方法无关。
如果无法将结果写入文件,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();// 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()' 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()这些输出选项在与云存储服务、数据库或网络应用程序集成时特别有用,因为文件系统访问可能会受到限制。 以下示例展示了实际应用场景:
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
Public Class SearchablePdfExporter
Public Async Function ProcessAndUploadPdf(inputPath As String) As Task
Dim ocr As New IronTesseract With {
.Configuration = { .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 ClassImports IronOcr
Imports System.IO
Public Class SearchablePdfExporter
Public Async Function ProcessAndUploadPdf(inputPath As String) As Task
Dim ocr As New IronTesseract With {
.Configuration = { .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性能考虑
在处理大量文档时,请考虑实现多线程OCR操作以提高吞吐量。 IronOCR支持并发处理,允许您同时处理多个文档。
这里有两层并行。外层循环一次分派多个文档,每次 Read 调用又会并行识别多个页面,每个同时处理的页面各占用一个原生 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");
}
}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");
}
}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
{
.Language = OcrLanguage.English,
.MaxDegreeOfParallelism = 2,
.Configuration = New OcrConfiguration With
{
.RenderSearchablePdf = True
}
}
End Sub
Public Async Function ProcessBatchAsync(filePaths As String()) As Task
Dim results As New ConcurrentBag(Of (source As String, output As String))()
Dim options As New ParallelOptions With {.MaxDegreeOfParallelism = 4}
Await Parallel.ForEachAsync(filePaths, options, Async Function(filePath, ct)
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 Function)
Console.WriteLine($"Processed {results.Count} files")
End Function
End ClassImports IronOcr
Imports System.Threading.Tasks
Imports System.Collections.Concurrent
Public Class BatchPdfProcessor
Private ReadOnly _ocr As IronTesseract
Public Sub New()
_ocr = New IronTesseract With
{
.Language = OcrLanguage.English,
.MaxDegreeOfParallelism = 2,
.Configuration = New OcrConfiguration With
{
.RenderSearchablePdf = True
}
}
End Sub
Public Async Function ProcessBatchAsync(filePaths As String()) As Task
Dim results As New ConcurrentBag(Of (source As String, output As String))()
Dim options As New ParallelOptions With {.MaxDegreeOfParallelism = 4}
Await Parallel.ForEachAsync(filePaths, options, Async Function(filePath, ct)
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 Function)
Console.WriteLine($"Processed {results.Count} files")
End Function
End Class高级配置选项
对于更高级的场景,您可以利用详细的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
}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
}这些配置选项同样适用于所有三种输出方法:SaveAsSearchablePdf、SaveAsSearchablePdfBytes 和 SaveAsSearchablePdfStream。 下方的摘要汇总了所有可搜索的 PDF 处理方法及其对应的输出格式。
总结
使用 IronOCR 创建可搜索的 PDF,既可以处理单张图像和多页文档,也可以通过 ReadPhoto 识别照片,或通过 ReadDocumentAdvanced 处理高级文档扫描。库提供多种输出方式,可通过 ModelType 选择标准或增强的机器学习模型,以满足识别准确率要求。结果可导出为文件、字节数组或流,适用于桌面应用程序和云服务等不同架构。
对于更高级的OCR场景,可以探索全面的代码示例或参考API文档以了解详细的方法签名和选项。
常见问题
什么是可搜索PDF以及如何使用IronOCR创建?
可搜索PDF是一种将扫描图像和机器可读文本结合在一起的PDF文档。它是通过使用IronOCR对扫描文档执行OCR,将图像中的文本转换为可搜索文本而创建的。在C#中,可以通过将'RenderSearchablePdf'配置设置为true并使用'SaveAsSearchablePdf'方法来完成。
IronOCR可以处理多页文档转换为可搜索PDF吗?
是的,IronOCR可以处理多页文档。当使用 'OcrPdfInput' 时,IronOCR会依次处理每一页并保留原始结构,允许将多页文档转换为可搜索PDF。
如何使用IronOCR将OCR结果导出为可搜索PDF?
要将OCR结果导出为可搜索PDF,请将 'Configuration.RenderSearchablePdf' 属性设置为true,运行 'Read' 方法以获取OCR结果,然后使用 'SaveAsSearchablePdf' 将结果导出到文件路径。
使用IronOCR导出可搜索PDF有哪些选项?
IronOCR允许通过'的方法将可搜索PDF导出为文件、字节数组或流,这些选项提供了与云存储或数据库集成的灵活性。
IronOCR可以从照片或高级文档扫描生成可搜索PDF吗?
是的,IronOCR支持从照片生成可搜索PDF,使用 'ReadPhoto' 方法;从高级文档扫描生成可搜索PDF,使用 'ReadDocumentAdvanced' 方法。两种方法都允许将结果导出为可搜索PDF。
IronOCR如何提高低质量扫描的OCR准确度?
IronOCR通过应用图像优化过滤器来提高低质量扫描的OCR准确度。例如,使用 'ToGrayScale' 方法可以减少颜色噪声,有助于增强文本识别。
如何修正IronOCR生成的可搜索PDF中的错误字符?
可以通过在使用 'SaveAsSearchablePdf' 时指定一种Unicode兼容字体来修正可搜索PDF中的错误字符。这允许完全支持所有的Unicode字符,解决了非ASCII字符的问题。
IronOCR有优化处理大量文档性能的方法吗?
是的,IronOCR支持并发处理,允许您实现多线程OCR操作。这有助于同时处理多个文档,提高处理大量文档时的吞吐量。
IronOCR创建可搜索PDF有哪些高级配置选项?
IronOCR提供高级配置选项,包括详细的Tesseract配置、设置Tesseract变量和选择不同的页面分割模式。这些都可以针对特定文档类型或语言进行微调OCR。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。