C#とIronOCRで検索可能なPDFを保存する方法
IronOCR を使用すると、C# の数行のコードで、スキャンした文書や画像をOCR技術によって検索可能なPDFに変換できます。出力形式はファイル、バイト列、ストリームから選べます。
検索可能な PDF は、OCR (光学式文字認識) PDF とも呼ばれ、スキャンされた画像と機械で読み取り可能なテキストの両方を含む PDF ドキュメントの一種です。 これらの PDF は、スキャンされた紙の文書または画像に対して OCR を実行し、画像内のテキストを認識して、選択および検索可能なテキストに変換することによって作成されます。
ReadPhoto、ReadScreenShot、ReadDocumentAdvanced の結果でも SaveAsSearchablePdf を使用でき、写真や高度な文書OCRの結果から検索可能なPDFを作成できます。紙の資料をデジタル化したり、既存のPDFを検索可能にして管理しやすくしたりする場合に役立ちます。
RenderSearchablePdf = true を設定し、入力に対して Read(...) を実行し、SaveAsSearchablePdf(...) を呼び出します。 IronOCR を使えば、これだけで完全に検索可能な PDF を作成できます。
-
1IronOCR を 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ステップ)
- 検索可能なPDFとして結果を保存するためのC#ライブラリをダウンロード
- OCRの対象となる画像とPDF文書を準備します。
- RenderSearchablePdfプロパティを
trueに設定します。 SaveAsSearchablePdfメソッドで検索可能なPDFファイルを出力します。- 検索可能なPDFをバイト列またはストリームとしてエクスポートします。
OCR結果を検索可能なPDFとしてエクスポートする方法は?
IronOCR で結果を検索可能なPDFとしてエクスポートするには、Configuration.RenderSearchablePdf プロパティを true に設定し、Read メソッドでOCR結果オブジェクトを取得します。その後、出力ファイルパスを渡して SaveAsSearchablePdf を呼び出します。
入力
『ハリー・ポッター』の小説の1ページをTIFFファイルにスキャンし、OcrImageInput で読み込みます。印刷された文字が密に並んでいるため、検索可能なPDFのテキストレイヤーを実際の文書でテストできます。

potter.tiff:小説のページをスキャンした画像。非表示のテキストレイヤーを持つ検索可能なPDFを作成するために、OCRの入力として使用します。
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を作成するにはどうすればよいですか?
検索可能な PDF エクスポートは、ReadPhoto、ReadScreenShot、または ReadDocumentAdvanced を使用する場合にも利用可能です。 これらのメソッドのそれぞれは、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に読み込み、Enhancedモデルを指定して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.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は各ページを順次処理し、元のドキュメント構造を維持します。
入力
Hartwell Capital Managementの全11ページの年次報告書を OcrPdfInput で読み込みます。PageIndices で1~10ページ(インデックス0~9)を指定し、1回の Read 呼び出しで処理します。
multi-page-scan.pdf: 複数ページの検索可能なPDFへの変換の入力として使用された、11ページのHartwell Capital Management年次報告書。
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には、元の報告書の1~10ページが含まれます。各ページに非表示のテキストレイヤーがあり、任意のPDFビューアで抽出したテキストを選択、検索できます。
検索可能なPDFを作成する際にフィルタを適用するには?
SaveAsSearchablePdf の第2引数には、PDFに埋め込む画像にフィルタを適用するかどうかを指定するブール値を渡します。画像の最適化フィルタを使うと、特に低品質のスキャンでOCRの精度を大幅に向上できます。
以下の例ではグレースケールフィルタを適用し、第2引数として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文字を含む言語に影響します。
この問題を解決するには、3番目のパラメータとして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")4番目のパラメータとして、カスタムフォント名を指定することもできます。
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をバイト列またはストリームとしてエクスポートするには?
検索可能なPDFは、SaveAsSearchablePdfBytes でバイト列として、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
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()これらの出力オプションは、ファイルシステムへのアクセスが制限される可能性のあるクラウドストレージサービス、データベース、または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
}
}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 呼び出しは内部で複数ページに対して並列にOCRを実行します。同時処理するページごとにネイティブのTesseractエンジンを1つ使用します。制限を設けないと並列度が掛け合わされるため、外側のループは 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高度な設定オプション
文書の種類や言語に合わせてOCRエンジンを細かく調整するには、Tesseractの詳細設定を使用できます。
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 の3つの出力メソッドすべてに適用できます。以下のまとめでは、検索可能なPDFの出力メソッドと、それぞれの出力形式を説明します。
まとめ
IronOCR では、単一の画像や複数ページの文書に加え、ReadPhoto で読み取った写真や ReadDocumentAdvanced で処理した文書からも、検索可能なPDFを作成できます。認識精度に応じて、ModelType パラメータで標準または高精度のMLモデルを選択します。ファイル、バイト列、ストリームとして出力できるため、デスクトップアプリケーションからクラウドサービスまで幅広く利用できます。
より高度なOCR処理については、詳しいコード例や、メソッドのシグネチャとオプションを掲載したAPIドキュメントを参照してください。
よくある質問
検索可能なPDFとは何ですか、そしてIronOCRを使用してどのように作成されますか?
検索可能なPDFは、スキャンされた画像と機械可読なテキストを組み合わせたPDFドキュメントの一種です。IronOCRを使用して、スキャンされたドキュメントにOCRを実行し、画像内のテキストを検索可能なテキストに変換することで作成されます。C#では、'RenderSearchablePdf'の設定をtrueにして、'SaveAsSearchablePdf'メソッドを使用することで行うことができます。
IronOCRは複数ページのドキュメントを検索可能なPDFに変換できますか?
はい、IronOCRは複数ページのドキュメントを処理できます。'OcrPdfInput'を使用する場合、IronOCRは各ページを順次処理し、元の構造を維持して複数ページのドキュメントを検索可能なPDFに変換できます。
IronOCRを使用してOCR結果を検索可能なPDFとしてエクスポートするにはどうすればよいですか?
'Configuration.RenderSearchablePdf'プロパティをtrueに設定し、'Read'メソッドを実行してOCR結果を取得した後、'SaveAsSearchablePdf'を使用して結果をファイルパスにエクスポートします。
IronOCRで検索可能なPDFをエクスポートするためのオプションはどのようなものがありますか?
IronOCRは、'SaveAsSearchablePdf'、'SaveAsSearchablePdfBytes'、'SaveAsSearchablePdfStream'などのメソッドを使用して、ファイル、バイト配列、ストリームとして検索可能なPDFをエクスポートできます。これらのオプションは、クラウドストレージやデータベースとの統合に柔軟性を提供します。
IronOCRは写真または高度なドキュメントスキャンから検索可能なPDFを生成できますか?
はい、IronOCRは'ReadPhoto'を使用して写真から、また'ReadDocumentAdvanced'を使用して高度なドキュメントスキャンから検索可能なPDFを生成できます。両方の方法で、結果を検索可能なPDFとしてエクスポートできます。
IronOCRは低品質のスキャンでOCRの精度をどのように向上させますか?
IronOCRは、画像最適化フィルタを適用することで低品質スキャンのOCR精度を向上させます。例えば、'ToGrayScale'メソッドを使用することで、色情報を削減し、テキスト認識を向上させます。
IronOCRで生成された検索可能なPDFの誤った文字を修正するにはどうすればよいですか?
'SaveAsSearchablePdf'を使用する際にユニコード対応のフォントを指定することで、検索可能なPDFの誤った文字を修正できます。これにより、全てのユニコード文字を完全にサポートし、非ASCII文字に関する問題を解決できます。
IronOCRを使用して大量のドキュメントを処理する際にパフォーマンスを最適化する方法はありますか?
はい、IronOCRは同時処理をサポートしており、マルチスレッドOCR操作を実装することができます。これにより、複数のドキュメントを同時に処理し、大量のドキュメントを処理する際のスループットを改善します。
IronOCRで検索可能なPDFを作成するための高度な設定オプションはありますか?
IronOCRは、高度なTesseract設定、Tesseract変数の設定、および異なるページ分割モードの選択を含む高度な設定オプションを提供します。これらのオプションは、特定のドキュメントタイプや言語に対してOCRを微調整するためにカスタマイズできます。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。