C#で検索可能なPDFとして結果を保存する方法

C#で検索可能なPDFを保存する with IronOCR

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

IronOCRはOCRテクノロジーを使用して、C#開発者がスキャンした文書や画像を検索可能なPDFに変換することを可能にし、わずか数行のコードでファイル、バイト、ストリームとしての出力をサポートします。

検索可能な PDF は、OCR (光学式文字認識) PDF とも呼ばれ、スキャンされた画像と機械で読み取り可能なテキストの両方を含む PDF ドキュメントの一種です。 これらの PDF は、スキャンされた紙の文書または画像に対して OCR を実行し、画像内のテキストを認識して、選択および検索可能なテキストに変換することによって作成されます。

IronOCR は、ドキュメントに対して光学文字認識を実行し、その結果を検索可能な PDF としてエクスポートするためのソリューションを提供します。 検索可能な PDF をファイル、バイト、ストリームとしてエクスポートすることをサポートします。 この機能は、スキャンされたドキュメントを扱うとき、紙のアーカイブをデジタル化するとき、またはより良いドキュメント管理のためにレガシーPDFを検索可能にするときに特に役立ちます。

クイックスタート: 検索可能なPDFを1行でエクスポート

. 。 <!コードの概念を示す図またはスクリーンショット -->。

RenderSearchablePdf = trueを設定し、入力に対してRead(...)を実行し、SaveAsSearchablePdf(...)を呼び出す。

Nuget Icon今すぐ NuGet で PDF を作成してみましょう:

  1. NuGet パッケージ マネージャーを使用して IronOCR をインストールします

    PM > Install-Package IronOcr

  2. このコード スニペットをコピーして実行します。

    new IronOcr.IronTesseract { Configuration = { RenderSearchablePdf = true } } .Read(new IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf");
  3. 実際の環境でテストするためにデプロイする

    今すぐ無料トライアルでプロジェクトに IronOCR を使い始めましょう
    arrow pointer


OCR結果を検索可能なPDFとしてエクスポートするにはどうすればよいですか?

. 。 。

IronOCR を使用して結果を検索可能な PDF としてエクスポートする方法は次のとおりです。 まず、 Configuration.RenderSearchablePdfプロパティをtrueに設定する必要があります。 Readメソッドから OCR 結果オブジェクトを取得した後、出力ファイル パスを指定してSaveAsSearchablePdfメソッドを使用します。 以下のコードは、サンプル TIFF ファイルの使用方法を示しています。

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

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Enable render as searchable PDF
ocrTesseract.Configuration.RenderSearchablePdf = True

' Add image
Dim imageInput = New OcrImageInput("Potter.tiff")
' Perform OCR
Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Export as searchable PDF
ocrResult.SaveAsSearchablePdf("searchablePdf.pdf")
$vbLabelText   $csharpLabel

複数ページのTIFFファイルや複雑な文書を扱う場合、IronOCRは自動的にすべてのページを処理し、検索可能なPDF出力に含めます。 このライブラリは、ページの順序とテキストオーバーレイの位置を自動的に処理し、テキストと画像の正確なマッピングを保証します。

以下は、サンプル TIFF と埋め込まれた検索可能な PDF のスクリーンショットです。 PDF 内のテキストを選択して、検索可能かどうかを確認します。 The ability to select also means the text can be searched in a PDF viewer.

IronOcrは画像ファイルにテキストをオーバーレイするために特定のフォントを使用しています。

Page from Harry Potter book showing Chapter Eight 'The Deathday Party' with text about Harry meeting Nearly Headless Nick

複数ページのドキュメントを扱う

複数ページの文書に対する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");
Imports IronOcr

' Initialize IronTesseract with configuration
Dim ocrTesseract As New IronTesseract With {
    .Configuration = New OcrConfiguration With {
        .RenderSearchablePdf = True,
        .PageSegmentationMode = TesseractPageSegmentationMode.Auto
    }
}

' Load a multi-page PDF
Using pdfInput As New OcrPdfInput("multi-page-scan.pdf")
    ' Optionally specify page range (e.g., pages 1-10)
    pdfInput.SelectPages(1, 10)

    ' Perform OCR with progress tracking
    Dim result As OcrResult = ocrTesseract.Read(pdfInput)

    ' Save as searchable PDF
    result.SaveAsSearchablePdf("searchable-multi-page.pdf")

    ' Display total pages processed
    Console.WriteLine($"Processed {result.Pages.Length} pages")
End Using
$vbLabelText   $csharpLabel

検索可能なPDFを作成するときにフィルタを適用するにはどうすればよいですか?

SaveAsSearchablePdfは、検索可能な PDF にフィルターを適用するかどうかを指定できるブール フラグを 2 番目のパラメーターとして受け入れるため、開発者は柔軟に選択できます。 画像最適化フィルターを使用すると、特に低品質スキャンを扱う場合に、OCRの精度を大幅に向上させることができます。

以下は、グレースケール・フィルタを適用し、SaveAsSearchablePdfの2番目のパラメータにtrueを入れてフィルタ付きPDFを保存する例です。

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

Dim ocr As New IronTesseract()
Dim ocrInput As New OcrInput()

' Load a PDF file
ocrInput.LoadPdf("invoice.pdf")

' Apply gray scale filter
ocrInput.ToGrayScale()
Dim result As OcrResult = ocr.Read(ocrInput)

' Save the result as a searchable PDF with filters applied
result.SaveAsSearchablePdf("outputGrayscale.pdf", True)
$vbLabelText   $csharpLabel

最適な結果を得るには、フィルタウィザードを使用して、特定のドキュメントタイプに最適なフィルタの組み合わせを自動的に決定することを検討してください。 このツールは、入力を分析し、適切な前処理ステップを提案します。


検索可能なPDFをバイトまたはストリームとしてエクスポートするにはどうすればよいですか?

検索可能な PDF の出力は、それぞれSaveAsSearchablePdfBytesSaveAsSearchablePdfStreamメソッドを使用して、バイトまたはストリームとして処理することもできます。 以下のコード例は、これらのメソッドを活用する方法を示しています。

: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();
' Export searchable PDF byte
Dim pdfByte() As Byte = ocrResult.SaveAsSearchablePdfBytes()

' Export searchable PDF stream
Dim pdfStream As Stream = ocrResult.SaveAsSearchablePdfStream()
$vbLabelText   $csharpLabel

これらの出力オプションは、ファイルシステムへのアクセスが制限される可能性のあるクラウドストレージサービス、データベース、または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
Imports System.Threading.Tasks

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

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

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

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

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

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

パフォーマンスの考慮事項

大量のドキュメントを処理する場合は、マルチスレッド OCR 操作を実装してスループットを向上させることを検討してください。 IronOCRは同時処理をサポートしており、複数のドキュメントを同時に扱うことができます:

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

public class BatchPdfProcessor
{
    private readonly IronTesseract _ocr;

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

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

        await Parallel.ForEachAsync(filePaths, async (filePath, ct) =>
        {
            using var input = new OcrImageInput(filePath);
            var result = _ocr.Read(input);

            string outputPath = Path.ChangeExtension(filePath, ".searchable.pdf");
            result.SaveAsSearchablePdf(outputPath);

            results.Add((filePath, outputPath));
        });

        Console.WriteLine($"Processed {results.Count} files");
    }
}
using IronOcr;
using System.Threading.Tasks;
using System.Collections.Concurrent;

public class BatchPdfProcessor
{
    private readonly IronTesseract _ocr;

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

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

        await Parallel.ForEachAsync(filePaths, async (filePath, ct) =>
        {
            using var input = new OcrImageInput(filePath);
            var result = _ocr.Read(input);

            string outputPath = Path.ChangeExtension(filePath, ".searchable.pdf");
            result.SaveAsSearchablePdf(outputPath);

            results.Add((filePath, outputPath));
        });

        Console.WriteLine($"Processed {results.Count} files");
    }
}
Imports IronOcr
Imports System.Threading.Tasks
Imports System.Collections.Concurrent

Public Class BatchPdfProcessor
    Private ReadOnly _ocr As IronTesseract

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

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

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

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

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

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

高度な設定オプション

より高度なシナリオでは、詳細なTesseract設定を活用して、特定のドキュメントタイプや言語向けにOCRエンジンを微調整することができます:

var advancedOcr = new IronTesseract
{
    Configuration = 
    {
        RenderSearchablePdf = true,
        TesseractVariables = new Dictionary<string, object>
        {
            { "preserve_interword_spaces", 1 },
            { "tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" }
        },
        PageSegmentationMode = TesseractPageSegmentationMode.SingleColumn
    },
    Language = OcrLanguage.EnglishBest
};
var advancedOcr = new IronTesseract
{
    Configuration = 
    {
        RenderSearchablePdf = true,
        TesseractVariables = new Dictionary<string, object>
        {
            { "preserve_interword_spaces", 1 },
            { "tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" }
        },
        PageSegmentationMode = TesseractPageSegmentationMode.SingleColumn
    },
    Language = OcrLanguage.EnglishBest
};
Imports IronOcr

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

まとめ

IronOCRで検索可能なPDFを作成するのは簡単で柔軟です。 単一の画像、複数ページの文書、またはバッチ操作のいずれを処理する必要があるかにかかわらず、ライブラリは、さまざまな形式で検索可能なPDFを生成するための堅牢なメソッドを提供します。 ファイル、バイト、ストリームとしてエクスポートできるため、デスクトップアプリケーションからクラウドベースのサービスまで、あらゆるアプリケーションアーキテクチャに適応できます。

より高度な OCR シナリオについては、包括的なコード例を参照するか、APIドキュメントで詳細なメソッドのシグネチャとオプションを参照してください。

よくある質問

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を作成するのは、たった1行のコードで可能です: new IronOcr.IronTesseract { Configuration = { RenderSearchablePdf = true }.}.Read(new IronOcr.OcrImageInput("file.jpg")).SaveAsSearchablePdf("searchable.pdf").これはIronOCRの合理化されたAPI設計を示している。

検索可能PDFのテキストオーバーレイはどのように機能しますか?

IronOCRは、認識されたテキストをPDFの原画像の上に不可視のオーバーレイとして自動的に配置します。これにより、テキストと画像の正確なマッピングが保証され、ユーザーは元の文書の外観を維持したままテキストを選択、検索することができます。このライブラリは、特殊なフォントと位置決めアルゴリズムを使用してこれを実現します。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

レビュー済み
Jeff Fritz
Jeffrey T. Fritz
プリンシパルプログラムマネージャー - .NETコミュニティチーム
Jeffはまた、.NETとVisual Studioチームのプリンシパルプログラムマネージャーです。彼は.NET Conf仮想会議シリーズのエグゼクティブプロデューサーであり、週に二回放送される開発者向けライブストリーム『Fritz and Friends』のホストを務め、テクノロジーについて話すことや視聴者と一緒にコードを書くことをしています。Jeffはワークショップ、プレゼンテーション、およびMicrosoft Build、Microsoft Ignite、.NET Conf、Microsoft MVPサミットを含む最大のMicrosoft開発者イベントのコンテンツを企画しています。
準備はできましたか?
Nuget ダウンロード 5,384,824 | バージョン: 2026.2 リリース