使用 IronOCR 在 C# 中儲存可搜尋 PDF
IronOCR 使 C# 開發人員能夠使用OCR 技術將掃描的文件和圖像轉換為可搜尋的 PDF,只需幾行程式碼即可支援以文件、位元組或串流的形式輸出。
可搜尋的 PDF,通常被稱為 OCR(光學字元辨識)PDF,是一種包含掃描影像和機器可讀文字的 PDF 文件。 這些 PDF 文件是透過對掃描的紙質文件或圖像執行 OCR 功能創建的,它可以識別圖像中的文本,並將其轉換為可選擇和可搜尋的文本。
IronOCR 提供了一種解決方案,可以對文件執行光學字元識別,並將結果匯出為可搜尋的 PDF 文件。 它支援將可搜尋的 PDF 匯出為文件、位元組和流。 在處理掃描文件、數位化紙本檔案或可搜尋舊版 PDF 以更好地進行文件管理時,此功能尤其有用。
快速入門:一行匯出可搜尋的 PDF
設定RenderSearchablePdf = true ,對輸入執行Read(...) ,然後呼叫SaveAsSearchablePdf(...) -這就是使用 IronOCR 產生完全可搜尋 PDF 的全部步驟。
立即開始使用 NuGet 建立 PDF 檔案:
使用 NuGet 套件管理器安裝 IronOCR
複製並運行這段程式碼。
new IronOcr.IronTesseract { Configuration = { RenderSearchablePdf = true } } .Read(new IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf");部署到您的生產環境進行測試
最簡工作流程(5個步驟)
- 下載一個 C# 庫,用於將結果儲存為可搜尋的 PDF 檔案。
- 準備好用於OCR辨識的影像和PDF文件。
- 將RenderSearchablePdf屬性設為
true - 使用
SaveAsSearchablePdf方法輸出可搜尋的 PDF 文件 - 將可搜尋的 PDF 匯出為位元組流和資料流。
如何將OCR結果匯出為可搜尋的PDF?
以下是如何使用 IronOCR 將結果匯出為可搜尋的 PDF 檔案。 您必須先將Configuration.RenderSearchablePdf屬性設為true 。 透過Read方法取得 OCR 結果物件後,使用SaveAsSearchablePdf方法指定輸出檔案路徑。 以下程式碼示範如何使用範例 TIFF 檔案。
:path=/static-assets/ocr/content-code-examples/how-to/searchable-pdf-searchable-pdf.csusing IronOcr;
// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();
// Enable render as searchable PDF
ocrTesseract.Configuration.RenderSearchablePdf = true;
// Add image
using var imageInput = new OcrImageInput("Potter.tiff");
// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);
// Export as searchable PDF
ocrResult.SaveAsSearchablePdf("searchablePdf.pdf");處理多頁 TIFF 檔案或複雜文件時,IronOCR 會自動處理所有頁面,並將它們包含在可搜尋的 PDF 輸出中。 該庫可自動處理頁面排序和文字疊加定位,確保準確的文字到圖像映射。
下面顯示的是範例 TIFF 檔案的螢幕截圖以及嵌入的可搜尋 PDF 檔案。 嘗試選取 PDF 中的文本,以確認其可搜尋性。 選擇功能還意味著可以在 PDF 檢視器中搜尋文字。
IronOCR 使用特定的字體將文字疊加到圖像檔案上,這可能會導致文字大小出現一些差異。

TIFF 文件
可搜尋的PDF
處理多頁文檔
在處理多頁文件的PDF OCR 操作時,IronOCR 會依序處理每一頁,並維持原始文件結構。 以下是將多頁掃描版 PDF 檔案轉換為可搜尋 PDF 檔案的範例:
using IronOcr;
// Initialize IronTesseract with configuration
var ocrTesseract = new IronTesseract
{
Configuration =
{
RenderSearchablePdf = true,
PageSegmentationMode = TesseractPageSegmentationMode.Auto
}
};
// Load a multi-page PDF
using var pdfInput = new OcrPdfInput("multi-page-scan.pdf");
// Optionally specify page range (e.g., pages 1-10)
pdfInput.SelectPages(1, 10);
// Perform OCR with progress tracking
OcrResult result = ocrTesseract.Read(pdfInput);
// Save as searchable PDF
result.SaveAsSearchablePdf("searchable-multi-page.pdf");
// Display total pages processed
Console.WriteLine($"Processed {result.Pages.Length} pages");using IronOcr;
// Initialize IronTesseract with configuration
var ocrTesseract = new IronTesseract
{
Configuration =
{
RenderSearchablePdf = true,
PageSegmentationMode = TesseractPageSegmentationMode.Auto
}
};
// Load a multi-page PDF
using var pdfInput = new OcrPdfInput("multi-page-scan.pdf");
// Optionally specify page range (e.g., pages 1-10)
pdfInput.SelectPages(1, 10);
// Perform OCR with progress tracking
OcrResult result = ocrTesseract.Read(pdfInput);
// Save as searchable PDF
result.SaveAsSearchablePdf("searchable-multi-page.pdf");
// Display total pages processed
Console.WriteLine($"Processed {result.Pages.Length} pages");創建可搜尋的PDF時如何應用篩選器?
SaveAsSearchablePdf也接受一個布林標誌作為第二個參數,讓您可以對可搜尋的 PDF 套用篩選器或不套用篩選器,從而為開發人員提供選擇的靈活性。 使用影像最佳化濾鏡可以顯著提高 OCR 準確率,尤其是在處理低品質掃描件時。
下面是一個套用灰階濾鏡,然後透過在SaveAsSearchablePdf的第二個參數中設定true來儲存帶有濾鏡的 PDF 的範例。
:path=/static-assets/ocr/content-code-examples/how-to/image-quality-correction-searchable-pdf.csusing IronOcr;
var ocr = new IronTesseract();
var ocrInput = new OcrInput();
// Load a PDF file
ocrInput.LoadPdf("invoice.pdf");
// Apply gray scale filter
ocrInput.ToGrayScale();
OcrResult result = ocr.Read(ocrInput);
// Save the result as a searchable PDF with filters applied
result.SaveAsSearchablePdf("outputGrayscale.pdf", true);為了獲得最佳效果,建議使用篩選精靈自動確定適合您特定文件類型的最佳篩選器組合。 該工具會分析您的輸入並建議合適的預處理步驟。
如何將可搜尋的 PDF 檔案匯出為位元組流或資料流?
也可以分別使用SaveAsSearchablePdfBytes和SaveAsSearchablePdfStream方法將可搜尋 PDF 的輸出作為位元組或流進行處理。 下面的程式碼範例展示如何使用這些方法。
:path=/static-assets/ocr/content-code-examples/how-to/searchable-pdf-searchable-pdf-byte-stream.cs// Export searchable PDF byte
byte[] pdfByte = ocrResult.SaveAsSearchablePdfBytes();
// Export searchable PDF stream
Stream pdfStream = ocrResult.SaveAsSearchablePdfStream();當與雲端儲存服務、資料庫或 Web 應用程式整合時,如果檔案系統存取受到限制,這些輸出選項尤其有用。 以下是一個展示實際應用的擴充範例:
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
}
}性能考量
處理大量文件時,可考慮實施 多執行緒 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");
}
}進階配置選項
對於更高階的應用程式場景,您可以利用詳細的 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
};概括
使用 IronOCR 建立可搜尋的 PDF 檔案既簡單又靈活。 無論您需要處理單一影像、多頁文件還是批次操作,該程式庫都提供了強大的方法來產生各種格式的可搜尋 PDF。 能夠匯出為文件、位元組或流,使其能夠適應任何應用程式架構,從桌面應用程式到基於雲端的服務。
常見問題解答
如何使用 C# 從掃描的影像建立可搜尋的 PDF?
IronOCR 可讓您輕鬆地從掃描影像建立可搜尋的 PDF。只需在設定中將 RenderSearchablePdf 設為 true,在輸入影像上使用 Read() 方法,然後以所需的輸出路徑呼叫 SaveAsSearchablePdf()。IronOcr 將會對影像執行 OCR,並產生 PDF,在原始影像上覆蓋可選擇、可搜尋的文字。
哪些檔案格式可以轉換成可搜尋的 PDF?
IronOCR 可以將 JPG、PNG、TIFF 等多種圖像格式以及現有的 PDF 文件轉換為可搜尋的 PDF。該函式庫支援單頁影像和 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 中原始影像上方的隱形覆蓋層。這可確保準確的文字對圖像映射,讓使用者可以選擇和搜尋文字,同時保持原始文件的視覺外觀。這個函式庫使用專門的字型和定位演算法來達成這個目標。







