# C#で検索可能なPDFを保存する with IronOCR
IronOCRは[OCRテクノロジー](https://ironsoftware.com/csharp/ocr/features/)を使用して、C#開発者がスキャンした文書や画像を検索可能なPDFに変換することを可能にし、わずか数行のコードでファイル、バイト、ストリームとしての出力をサポートします。
検索可能な PDF は、OCR (光学式文字認識) PDF とも呼ばれ、スキャンされた画像と機械で読み取り可能なテキストの両方を含む PDF ドキュメントの一種です。 これらの PDF は、スキャンされた紙の文書または画像に対して OCR を実行し、画像内のテキストを認識して、選択および検索可能なテキストに変換することによって作成されます。
`ReadDocumentAdvanced`からの結果でも利用可能で、写真や高度な文書OCRワークフローから検索可能なPDFの作成を可能にします。 この機能は、紙のアーカイブをデジタル化したり、文書管理を改善するためにレガシーPDFを検索可能にしたりする際に特に役立ちます。
*as-heading:2(クイックスタート: 検索可能なPDFを1行でエクスポート)*
`SaveAsSearchablePdf(...)`を呼び出します。 IronOCR を使えば、これだけで完全に検索可能な PDF を作成できます。
```cs
:title=Quickly Make a PDF Searchable with IronOCR
new IronOcr.IronTesseract { Configuration = { RenderSearchablePdf = true } } .Read(new IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf");
```
<div class="hsg-featured-snippet">
<h3>最小限のワークフロー(5ステップ)</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/IronOcr/">結果を検索可能な PDF として保存するための C# ライブラリをダウンロードします</a></li>
<li>OCRのための画像とPDFドキュメントを準備</li>
<li><strong>RenderSearchablePdf</strong>プロパティを<code>true</code>に設定してください。</li>
<li><code>SaveAsSearchablePdf</code>メソッドを利用して検索可能なPDFファイルを出力します</li>
<li>検索可能なPDFをバイト・ストリームとしてエクスポートする。</li>
</ol>
</div>
<br class="clear" />
## OCR結果を検索可能なPDFとしてエクスポートするにはどうすればよいですか?
IronOCRを使用して検索可能なPDFとして結果をエクスポートするには、`SaveAsSearchablePdf`を呼び出します。
### 入力
ハリー・ポッター小説からの単一ページがTIFFファイルとしてスキャンされ、`OcrImageInput`を使用してロードされました。 このページには文字が密集して印刷されており、検索可能なPDFテキストレイヤーをテストするための現実的な入力データとなります。
<div class="content-img-align-center">
<div class="center-image-wrapper" style="max-width: 380px; margin: 0 auto;">
<img src="/static-assets/ocr/how-to/searchable-pdf/potter.webp" alt=""ハリー・ポッター"の書籍のページで、第8章"死の日パーティー"が掲載されており、ハリーが"ほぼ首なしニック"と出会う場面についての記述がある。" class="img-responsive add-shadow" />
</div>
</div>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">potter.tiff: OCRの入力として使用され、不可視のテキストレイヤーを含む検索可能なPDFを生成するためにスキャンされた小説のページ。</p>
```csharp
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");
```
### 出力
<iframe loading="lazy" src="/static-assets/ocr/how-to/searchable-pdf/searchablePdf.pdf" width="100%" height="400px"></iframe>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">searchablePdf.pdf: 検索可能なPDF出力。任意の単語を選択または検索して、OCRテキストレイヤーを確認してください。</p>
生成されるPDFには、元のスキャン画像が埋め込まれ、認識された各単語の上に非表示のテキストレイヤーが配置されます。 ビューア内で任意のWORDを選択または検索し、テキストレイヤーが存在することを確認してください。
IronOCRはオーバーレイに特定のフォントを使用しているため、元のテキストと比較して表示されるテキストサイズに若干の差異が生じる場合があります。
[複数ページの TIFF ファイル](https://ironsoftware.com/csharp/ocr/examples/csharp-tesseract-multipage-tiff/)や複雑なドキュメントを扱う場合、IronOCR はすべてのページを自動的に処理し、出力に含めます。 このライブラリは、ページの順序とテキストオーバーレイの位置を自動的に処理し、テキストと画像の正確なマッピングを保証します。
### 写真や高度なドキュメントスキャンから検索可能なPDFを作成するにはどうすればよいですか?
検索可能なPDFエクスポートは、`ReadDocumentAdvanced`を使用する際も利用可能です。 これらの各メソッドは、`SaveAsSearchablePdf`をサポートする結果タイプを返します。
オプションとして、これらのメソッドを呼び出す際に`ModelType`を引数として渡すことができます。 デフォルトは`Enhanced`は速度の犠牲を伴いながらもより高い精度を提供します。
#### 入力
壁画の写真に描かれたテキストが含まれており、`LoadImage`を通じてロードされました。 このシーンは現実世界環境に埋め込まれた複数の単語を含んでおり、`Enhanced`モデルと実用的なテストのための試験です。
<div class="content-img-align-center">
<div class="center-image-wrapper" style="max-width: 450px; margin: 0 auto;">
<img src="/static-assets/ocr/how-to/searchable-pdf/photo-input.webp" alt="ReadPhoto OCRの入力として使用された、テキストを含む写真" class="img-responsive add-shadow" />
</div>
</div>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">photo.png: ReadPhotoのEnhancedモデルを使用して読み込まれた壁画の写真。検索可能なPDFを生成するために使用されました。</p>
```csharp
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);
```
#### 出力
<iframe loading="lazy" src="/static-assets/ocr/how-to/searchable-pdf/searchable-photo.pdf" width="100%" height="400px"></iframe>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">searchable-photo.pdf: ReadPhotoから出力された検索可能なPDF。テキストレイヤーは、あらゆるPDFビューアでの全文検索に対応しています。</p>
生成される検索可能なPDFには、認識された単語の上に非表示のテキストレイヤーが含まれています。 PDFビューアで"Milk"を検索すると、元の写真内の描画テキストから直接抽出された3件の一致が返されます。
同じアプローチは`OcrDocAdvancedResult`を返します:
#### 入力
スキャンされた請求書が`LoadImage`を通じてロードされました。 それは構造化されたフィールド(ベンダー名、品目、合計)を含み、`Enhanced`モデルによって認識され、検索可能なテキストレイヤーとして埋め込まれます。
<div class="content-img-align-center">
<div class="center-image-wrapper" style="max-width: 400px; margin: 0 auto;">
<img src="/static-assets/ocr/how-to/searchable-pdf/invoice-input.webp" alt="ReadDocumentAdvanced OCRの入力として使用される請求書文書" class="img-responsive add-shadow" />
</div>
</div>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">invoice.png: OcrInputに読み込まれたスキャン済みの請求書で、Enhancedモデルを使用してReadDocumentAdvancedに渡されたもの。</p>
```csharp
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);
```
#### 出力
<iframe loading="lazy" src="/static-assets/ocr/how-to/searchable-pdf/searchable-doc.pdf" width="100%" height="400px"></iframe>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">searchable-doc.pdf: ReadDocumentAdvanced から出力された検索可能な PDF。請求書の各フィールドを選択および検索可能です。</p>
`ExtensionAdvancedScanException`を投げます。
### 複数ページのドキュメントを扱う
複数ページのドキュメントに対してPDF OCR処理を行う際、IronOCRは各ページを順次処理し、元のドキュメント構造を維持します。
#### 入力
Hartwell Capital Managementによる11ページの年間報告書が`OcrPdfInput`でロードされました。 ページ1~10(インデックス0~9)は`Read`呼び出しで処理されます。
<iframe loading="lazy" src="/static-assets/ocr/how-to/searchable-pdf/multi-page-scan.pdf" width="100%" height="400px"></iframe>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">multi-page-scan.pdf: 複数ページの検索可能なPDFへの変換の入力として使用された、11ページのHartwell Capital Management年次報告書。</p>
```csharp
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);
```
#### 出力
<iframe loading="lazy" src="/static-assets/ocr/how-to/searchable-pdf/searchable-multi-page.pdf" width="100%" height="400px"></iframe>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">searchable-multi-page.pdf: 10ページの検索可能なPDF出力。各ページには全文検索用の非表示テキストレイヤーが含まれています。</p>
生成されたPDFは10ページ(元のレポートの1~10ページ)で構成されており、各ページには非表示のテキストレイヤーが含まれており、これにより、どのPDFビューアでも抽出されたコンテンツを選択および検索できるようになっています。
### 検索可能なPDFを作成するときにフィルタを適用するにはどうすればよいですか?
`SaveAsSearchablePdf`セカンドパラメーターは、埋め込まれた出力に画像フィルターが適用されるかどうかを制御する真偽値を受け取ります。 [画像最適化フィルター](https://ironsoftware.com/csharp/ocr/examples/ocr-image-filters-for-net-tesseract/)を使用すると、特に[低品質スキャン](https://ironsoftware.com/csharp/ocr/examples/ocr-low-quality-scans-tesseract/)を扱う場合に、OCRの精度を大幅に向上させることができます。
以下の例では、グレースケールフィルターを適用し、`true`を第二引数に渡すことでフィルター処理された画像を検索可能な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);
```
最適な結果を得るには、[フィルタウィザード](https://ironsoftware.com/csharp/ocr/examples/filter-wizard/)を使用して、特定のドキュメントタイプに最適なフィルタの組み合わせを自動的に決定することを検討してください。 このツールは、入力を分析し、適切な前処理ステップを提案します。
### 検索可能なPDFファイル内の誤った文字を修正するにはどうすればよいですか?
PDF上ではテキストが正しく表示されているのに、検索やコピーを行うと文字化けが発生する場合は、検索可能なテキストレイヤーで使用されているデフォルトフォントが原因です。 デフォルトで、`SaveAsSearchablePdf`は、すべてのユニコード文字を完全にサポートしないTimes New Romanを使用しています。 これは、アクセント記号付き文字や非ASCII文字を含む言語に影響します。
この問題を解決するには、3番目のパラメータとしてUnicode互換のフォントファイルを指定してください。
```csharp
result.SaveAsSearchablePdf("output.pdf", false, "Fonts/LiberationSerif-Regular.ttf");
```
4番目のパラメータとして、カスタムフォント名を指定することもできます。
```csharp
result.SaveAsSearchablePdf("output.pdf", false, "Fonts/LiberationSerif-Regular.ttf", "MyFont");
```
これは`OcrDocAdvancedResult`を含むすべての結果タイプに適用されるため、どの読み取りメソッドで結果が生成されたかに関係なく修正が機能します。
[[i:(Times New Romanで組版された文書の場合、Liberation Serifは計量的に互換性があり、元の間隔とレイアウトが維持されるため推奨されます。 汎用的な多言語使用には、Noto SansまたはDejaVu Sansが良い代替品です。)
)]]
ファイルパスへの書き込みが不可能な場合、IronOCRは検索可能なPDFをバイト配列またはストリームとして返すこともサポートしています。
<hr />
## 検索可能なPDFをバイトまたはストリームとしてエクスポートするにはどうすればよいですか?
検索可能なPDFの出力は、`SaveAsSearchablePdfStream`メソッドを使用してバイトまたはストリームとして処理することもできます。 以下のコード例は、これらのメソッドの使用方法を示しています。
```csharp
// 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();
```
これらの出力オプションは、ファイルシステムへのアクセスが制限される可能性のあるクラウドストレージサービス、データベース、またはWebアプリケーションと統合する場合に特に便利です。 以下の例は、実際の活用例を示しています:
```csharp
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 操作](https://ironsoftware.com/csharp/ocr/examples/csharp-tesseract-multithreading-for-speed/)を実装してスループットを向上させることを検討してください。 IronOCRは同時処理をサポートしており、複数のドキュメントを同時に扱うことができます:
```csharp
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設定](https://ironsoftware.com/csharp/ocr/examples/csharp-configure-setup-tesseract/)を活用して、特定のドキュメントタイプや言語向けにOCRエンジンを微調整することができます:
```csharp
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
};
```
これらの構成オプションは、`SaveAsSearchablePdfStream`のすべての3つの出力メソッドに同等に適用されます。 以下の概要には、検索可能なすべてのPDF処理メソッドと、それぞれの適切な出力形式がまとめられています。
## まとめ
IronOCRで検索可能なPDFを作成するのは簡単で柔軟です。 単一の画像処理、`ReadDocumentAdvanced`を使用した高度なドキュメントスキャンのどれを必要とするかに関係なく、ライブラリはさまざまな形式で検索可能なPDFを生成するための頑健な方法を提供します。 精度を選択するために標準のMLモデルと強化型MLモデルを選択するには、`ModelType`パラメーターを使用してください。 ファイル、バイト、ストリームとしてエクスポートできるため、デスクトップアプリケーションからクラウドベースのサービスまで、あらゆるアプリケーションアーキテクチャに適応できます。
より高度なOCRのシナリオについては、[包括的なコード例](https://ironsoftware.com/csharp/ocr/examples/csharp-tesseract-5/)を参照するか、詳細なメソッドのシグネチャやオプションについてはAPIドキュメントを参照してください。
検索可能な PDF は、OCR (光学式文字認識) PDF とも呼ばれ、スキャンされた画像と機械で読み取り可能なテキストの両方を含む PDF ドキュメントの一種です。 これらの PDF は、スキャンされた紙の文書または画像に対して OCR を実行し、画像内のテキストを認識して、選択および検索可能なテキストに変換することによって作成されます。
using IronOcr;// Create the OCR engine: defaults to English with balanced speed and accuracyIronTesseract ocrTesseract = new IronTesseract();// Required: without this flag the text overlay layer is not built, and SaveAsSearchablePdf produces a plain image PDFocrTesseract.Configuration.RenderSearchablePdf = true;// Wrap the TIFF in OcrImageInput: handles DPI detection and page layout automaticallyusing var imageInput = new OcrImageInput("Potter.tiff");// Run OCR; returns a result containing the recognized text and spatial layout dataOcrResult ocrResult = ocrTesseract.Read(imageInput);// Write the output: the original scanned image is preserved with an invisible text layer on topocrResult.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");
ImportsIronOcr' Create the OCR engine: defaults to English with balanced speed and accuracyDim ocrTesseract As New IronTesseract()' Required: without this flag the text overlay layer is not built, and SaveAsSearchablePdf produces a plain image PDFocrTesseract.Configuration.RenderSearchablePdf = True' Wrap the TIFF in OcrImageInput: handles DPI detection and page layout automaticallyUsing imageInput As New OcrImageInput("Potter.tiff") ' Run OCR; returns a result containing the recognized text and spatial layout data Dim ocrResult AsOcrResult = ocrTesseract.Read(imageInput) ' Write the output: the original scanned image is preserved with an invisible text layer on top ocrResult.SaveAsSearchablePdf("searchablePdf.pdf")EndUsing
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
using IronOcr;var ocr = new IronTesseract();using var input = new OcrInput();input.LoadImage("photo.png");// ReadPhoto with Enhanced modelOcrPhotoResult photoResult = ocr.ReadPhoto(input, ModelType.Enhanced);Console.WriteLine(photoResult.Text);// Save as searchable PDFbyte[] 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);
using IronOcr;var ocr = new IronTesseract();using var input = new OcrInput();input.LoadImage("invoice.png");// ReadDocumentAdvanced with Enhanced modelOcrDocAdvancedResult 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);
Hartwell Capital Managementによる11ページの年間報告書がOcrPdfInputでロードされました。 ページ1~10(インデックス0~9)はRead呼び出しで処理されます。
multi-page-scan.pdf: 複数ページの検索可能なPDFへの変換の入力として使用された、11ページのHartwell Capital Management年次報告書。
using IronOcr;// Create the OCR engine. RenderSearchablePdf is false by default; no need to set it when using OcrPdfInput directlyvar ocrTesseract = new IronTesseract();// Load pages 1–10 (indices 0–9) only; PageIndices avoids loading and OCR-ing the full document unnecessarilyusing var pdfInput = new OcrPdfInput("multi-page-scan.pdf", PageIndices: Enumerable.Range(0, 10));// Run OCR across all selected pages in orderOcrResult result = ocrTesseract.Read(pdfInput);// Write the searchable PDF; true = apply the input's image filters to the embedded page images in the outputresult.SaveAsSearchablePdf("searchable-multi-page.pdf", true);
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);
ImportsIronOcr' Create the OCR engine. RenderSearchablePdf is false by default; no need to set it when using OcrPdfInput directlyDim ocrTesseract As New IronTesseract()' Load pages 1–10 (indices 0–9) only; PageIndices avoids loading and OCR-ing the full document unnecessarilyUsing pdfInput As New OcrPdfInput("multi-page-scan.pdf", PageIndices:=Enumerable.Range(0, 10)) ' Run OCR across all selected pages in order Dim result AsOcrResult = 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)EndUsing
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
using IronOcr;// Create OCR engine: filters are applied at the OcrInput level, so no configuration changes are needed herevar ocr = new IronTesseract();var ocrInput = new OcrInput();// Load the scanned PDF as the OCR sourceocrInput.LoadPdf("invoice.pdf");// Convert to grayscale: removes color noise that can reduce OCR accuracy on color-printed documentsocrInput.ToGrayScale();// Run OCR on the preprocessed inputOcrResult result = ocr.Read(ocrInput);// Write the searchable PDF; true = embed the grayscale-filtered image rather than the original color scanresult.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);
ImportsIronOcr' Create OCR engine: filters are applied at the OcrInput level, so no configuration changes are needed hereDim ocr As New IronTesseract()Dim ocrInput As New OcrInput()' Load the scanned PDF as the OCR sourceocrInput.LoadPdf("invoice.pdf")' Convert to grayscale: removes color noise that can reduce OCR accuracy on color-printed documentsocrInput.ToGrayScale()' Run OCR on the preprocessed inputDim result AsOcrResult = ocr.Read(ocrInput)' Write the searchable PDF; True = embed the grayscale-filtered image rather than the original color scanresult.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上ではテキストが正しく表示されているのに、検索やコピーを行うと文字化けが発生する場合は、検索可能なテキストレイヤーで使用されているデフォルトフォントが原因です。 デフォルトで、SaveAsSearchablePdfは、すべてのユニコード文字を完全にサポートしないTimes New Romanを使用しています。 これは、アクセント記号付き文字や非ASCII文字を含む言語に影響します。
// Return as a byte array: suited for storing in a database or sending in an HTTP response bodybyte[] pdfByte = ocrResult.SaveAsSearchablePdfBytes();// Return as a stream: suited for uploading to cloud storage or piping to another I/O operation without buffering the full fileStream 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 bodyDim pdfByte AsByte() = ocrResult.SaveAsSearchablePdfBytes()' Return as a stream: suited for uploading to cloud storage or piping to another I/O operation without buffering the full fileDim pdfStream AsStream = 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 TaskProcessAndUploadPdf(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. awaitUploadToCloudStorage(pdfStream, "searchable-output.pdf"); } // Option 3: Return as web response // return File(pdfBytes, "application/pdf", "searchable.pdf"); } private async TaskUploadToCloudStorage(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
}
}
ImportsIronOcrImportsSystem.IOPublic Class SearchablePdfExporter PublicAsync Function ProcessAndUploadPdf(inputPath AsString) AsTask Dim ocr As New IronTesseractWith { .Configuration = { .RenderSearchablePdf = True } } ' Process the inputUsing input As New OcrImageInput(inputPath) Dim result = ocr.Read(input) ' Option 1: Save to database as byte array Dim pdfBytes AsByte() = result.SaveAsSearchablePdfBytes() ' Store pdfBytes in database BLOB field ' Option 2: Upload to cloud storage using streamUsing pdfStream AsStream = result.SaveAsSearchablePdfStream() ' Upload stream to Azure Blob Storage, AWS S3, etc.AwaitUploadToCloudStorage(pdfStream, "searchable-output.pdf")EndUsing ' Option 3: Return as web response ' Return File(pdfBytes, "application/pdf", "searchable.pdf")EndUsing End Function PrivateAsync Function UploadToCloudStorage(stream AsStream, fileName AsString) AsTask ' Cloud upload implementation End FunctionEnd Class
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 Class
using IronOcr;using System.Threading.Tasks;using System.Collections.Concurrent;public class BatchPdfProcessor{ private readonly IronTesseract _ocr; publicBatchPdfProcessor() { _ocr = new IronTesseract {Configuration = {RenderSearchablePdf = true, // Configure for optimal performanceLanguage = OcrLanguage.English } }; } public async TaskProcessBatchAsync(string[] filePaths) { var results = new ConcurrentBag<(string source, string output)>(); awaitParallel.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");
}
}
ImportsIronOcrImportsSystem.Threading.TasksImportsSystem.Collections.ConcurrentPublic Class BatchPdfProcessor PrivateReadOnly _ocr AsIronTesseract Public Sub New() _ocr = New IronTesseractWith { .Configuration = { .RenderSearchablePdf = True, ' Configure for optimal performance .Language = OcrLanguage.English } } End Sub PublicAsync Function ProcessBatchAsync(filePaths AsString()) AsTask Dim results As New ConcurrentBag(Of (source AsString, output AsString))()AwaitTask.Run(Sub()Parallel.ForEach(filePaths, Sub(filePath)Using input As New OcrImageInput(filePath) Dim result = _ocr.Read(input) Dim outputPath AsString = Path.ChangeExtension(filePath, ".searchable.pdf") result.SaveAsSearchablePdf(outputPath) results.Add((filePath, outputPath))EndUsing End Sub) End Function)Console.WriteLine($"Processed {results.Count} files") End FunctionEnd Class
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 = {
.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 Function)
Console.WriteLine($"Processed {results.Count} files")
End Function
End Class
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
};
ImportsIronOcrDim advancedOcr As New IronTesseractWith { .Configuration = New TesseractConfigurationWith { .RenderSearchablePdf = True, .TesseractVariables = New Dictionary(OfString, 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
}
ModelType パラメータは、OCR に使用する事前学習済み ML モデルを制御します。デフォルトは Normal で、高速な結果を得るために画像を 960 ピクセルにリサイズして処理します。Enhanced は最大 2560 ピクセルの画像に対応しており、細部をより忠実に保持し、高解像度の入力に対する精度を向上させます。
検索可能なPDFで、コピーまたは検索した文字が破損して表示されるのはなぜですか?
これは、検索可能なテキストレイヤーで使用されるデフォルトのフォント(Times New Roman)が、すべてのUnicode文字を完全にサポートしていないために発生します。これを修正するには、SaveAsSearchablePdfの3番目のパラメータとして、Unicode互換のフォントファイルを指定してください。もしドキュメントがもともとTimes New Romanで組版されており、他のフォントとの間で文字間隔の不一致が見られる場合は、Liberation Serifを試してみてください。このフォントは同じグリフメトリクスを共有しており、元のレイアウトを維持します。
What advanced configuration options are available in IronOCR for creating searchable PDFs?
IronOCR offers advanced configuration options, including detailed Tesseract configuration, setting Tesseract variables, and choosing different page segmentation modes. These can be tailored to fine-tune OCR for specific document types or languages.