Salve PDFs pesquisáveis em C# com IronOCR
Com a tecnologia de OCR do IronOCR, desenvolvedores C# podem converter documentos e imagens digitalizados em PDFs pesquisáveis e gerar a saída como arquivos, bytes ou streams com poucas linhas de código.
Um PDF pesquisável, também conhecido como PDF com OCR (reconhecimento óptico de caracteres), contém imagens digitalizadas e texto legível por máquina. Para criar esse tipo de PDF, aplique OCR aos documentos em papel digitalizados ou às imagens. O OCR reconhece o texto nas imagens e o torna selecionável e pesquisável.
SaveAsSearchablePdf também está disponível nos resultados de ReadPhoto, ReadScreenShot e ReadDocumentAdvanced, o que permite criar PDFs pesquisáveis a partir de fotos e em fluxos avançados de OCR de documentos. Esse recurso é útil para digitalizar arquivos em papel ou tornar PDFs antigos pesquisáveis e facilitar o gerenciamento de documentos.
Defina RenderSearchablePdf = true, execute Read(...) sobre os dados de entrada e chame SaveAsSearchablePdf(...). Com isso, o IronOCR gera um PDF totalmente pesquisável.
-
1Instale o IronOCR com NuGet Package Manager
-
2Copie e execute este trecho de código.
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") -
3Implante para testar em seu ambiente de produção.
Comece a usar o IronOCR em seu projeto hoje com uma avaliação gratuita
Fluxo de trabalho mínimo (5 etapas)
- Baixe uma biblioteca C# para salvar resultados como PDF pesquisável
- Prepare a imagem e o documento PDF para OCR.
- Defina a propriedade RenderSearchablePdf como
true - Utilize o método
SaveAsSearchablePdfpara gerar um arquivo PDF pesquisável. - Exporte o PDF pesquisável como um array de bytes ou um stream.
Como faço para exportar os resultados do OCR como um PDF pesquisável?
Para exportar o resultado como PDF pesquisável com o IronOCR, defina a propriedade Configuration.RenderSearchablePdf como true, obtenha o objeto de resultado de OCR retornado por Read e chame SaveAsSearchablePdf com o caminho do arquivo de saída.
Entrada
Uma única página de um romance de Harry Potter, escaneada como um arquivo TIFF e carregada via OcrImageInput. A página contém texto impresso denso, uma entrada realista para testar a camada de texto pesquisável do PDF.

potter.tiff: Página digitalizada do romance usada como entrada de OCR para produzir um PDF pesquisável com uma camada de texto invisível.
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 UsingSaída
searchablePdf.pdf: PDF pesquisável. Selecione ou pesquise qualquer palavra para verificar a camada de texto OCR.
O PDF resultante incorpora a imagem original da página digitalizada com uma camada de texto invisível posicionada sobre cada palavra reconhecida. Selecione ou pesquise qualquer palavra no visualizador para confirmar se a camada de texto está presente.
O IronOCR utiliza uma fonte específica para a sobreposição, o que pode causar pequenas discrepâncias no tamanho do texto renderizado em comparação com o original.
Ao trabalhar com arquivos TIFF de várias páginas ou documentos complexos, o IronOCR processa automaticamente todas as páginas e as inclui na saída. A biblioteca gerencia automaticamente a ordem das páginas e o posicionamento da sobreposição de texto, garantindo um mapeamento preciso entre texto e imagem.
Como criar PDFs pesquisáveis a partir de fotos ou digitalizações avançadas de documentos?
Exportação de PDF pesquisável também está disponível ao usar ReadPhoto, ReadScreenShot ou ReadDocumentAdvanced. Cada um desses métodos retorna um tipo de resultado que suporta SaveAsSearchablePdf.
Você pode opcionalmente passar um ModelType ao chamar esses métodos. O padrão é Normal, enquanto Enhanced oferece melhor precisão em detrimento da velocidade.
Entrada
Uma foto de um mural com texto pintado, carregada com LoadImage. As várias palavras pintadas em um cenário real servem como teste prático para ReadPhoto com o modelo Enhanced.

photo.png: Foto de um mural carregada com ReadPhoto usando o modelo Enhanced para gerar um PDF pesquisável.
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 UsingSaída
searchable-photo.pdf: PDF pesquisável gerado pelo ReadPhoto. A camada de texto permite a busca de texto completo em qualquer visualizador de PDF.
O PDF pesquisável resultante contém uma camada de texto invisível sobre as palavras reconhecidas. Ao buscar "Milk" no visualizador de PDF, aparecem três ocorrências extraídas diretamente do texto pintado na foto original.
A mesma abordagem funciona com ReadDocumentAdvanced, que retorna um OcrDocAdvancedResult:
Entrada
Uma fatura digitalizada, carregada com LoadImage. Ela contém campos estruturados (nome do fornecedor, itens da fatura e totais) que ReadDocumentAdvanced reconhece com o modelo Enhanced e incorpora em uma camada de texto pesquisável.

invoice.png: Fatura digitalizada carregada no OcrInput e passada para ReadDocumentAdvanced com o modelo Enhanced.
using IronOcr;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("invoice.png");
// ReadDocumentAdvanced with Enhanced model
OcrDocAdvancedResult docResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced);
byte[] docPdfBytes = docResult.SaveAsSearchablePdfBytes();
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes);using IronOcr;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("invoice.png");
// ReadDocumentAdvanced with Enhanced model
OcrDocAdvancedResult docResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced);
byte[] docPdfBytes = docResult.SaveAsSearchablePdfBytes();
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes);Imports IronOcr
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage("invoice.png")
' ReadDocumentAdvanced with Enhanced model
Dim docResult As OcrDocAdvancedResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced)
Dim docPdfBytes As Byte() = docResult.SaveAsSearchablePdfBytes()
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes)
End UsingImports IronOcr
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage("invoice.png")
' ReadDocumentAdvanced with Enhanced model
Dim docResult As OcrDocAdvancedResult = ocr.ReadDocumentAdvanced(input, ModelType.Enhanced)
Dim docPdfBytes As Byte() = docResult.SaveAsSearchablePdfBytes()
File.WriteAllBytes("searchable-doc.pdf", docPdfBytes)
End UsingSaída
searchable-doc.pdf: PDF pesquisável gerado pelo ReadDocumentAdvanced. Os campos da fatura podem ser selecionados e pesquisados.
SaveAsSearchablePdf não é compatível com os resultados de ReadPassport ou ReadLicensePlate. Nessas situações, a chamada lança uma ExtensionAdvancedScanException.Trabalhando com documentos de várias páginas
Ao lidar com operações de OCR em PDFs com várias páginas, o IronOCR processa cada página sequencialmente e mantém a estrutura original do documento.
Entrada
Um relatório anual de 11 páginas da Hartwell Capital Management carregado via OcrPdfInput. Páginas 1-10 (índices 0-9) são selecionadas usando o intervalo PageIndices e processadas em uma única chamada Read.
multi-page-scan.pdf: Relatório anual de 11 páginas da Hartwell Capital Management usado como entrada para a conversão em PDF pesquisável de várias páginas.
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 UsingSaída
searchable-multi-page.pdf: PDF pesquisável de 10 páginas. Cada página possui uma camada de texto invisível para pesquisa de texto completo.
O PDF resultante contém 10 páginas (páginas 1-10 do relatório original), cada uma com uma camada de texto invisível que torna o conteúdo extraído selecionável e pesquisável em qualquer visualizador de PDF.
Como posso aplicar filtros ao criar PDFs pesquisáveis?
O segundo parâmetro de SaveAsSearchablePdf aceita um valor booleano que determina se os filtros de imagem são aplicados à imagem incorporada no PDF de saída. Usar filtros de otimização de imagem pode melhorar significativamente a precisão do OCR, especialmente com digitalizações de baixa qualidade.
O exemplo abaixo aplica o filtro de escala de cinza e passa true como o segundo argumento para incorporar a imagem filtrada na saída de PDF pesquisável.
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)Para resultados otimizados, considere usar o Filter Wizard para determinar automaticamente a melhor combinação de filtros para seu tipo específico de documento. Esta ferramenta analisa os seus dados de entrada e sugere etapas de pré-processamento adequadas.
Como corrigir caracteres incorretos em PDFs pesquisáveis?
Se o texto parecer correto visualmente no PDF, mas apresentar caracteres corrompidos ao pesquisar ou copiar, o problema é causado pela fonte padrão usada na camada de texto pesquisável. Por padrão, SaveAsSearchablePdf usa Times New Roman, que não suporta completamente todos os caracteres Unicode. Isso afeta idiomas com caracteres acentuados ou não ASCII.
Para corrigir isso, forneça um arquivo de fonte compatível com Unicode como terceiro parâmetro:
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")Você também pode especificar um nome de fonte personalizado como quarto parâmetro:
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")Isso se aplica a todos os tipos de resultado, incluindo OcrResult, OcrPhotoResult e OcrDocAdvancedResult, então a correção funciona independentemente de qual método de leitura produziu o resultado.
Quando não for possível gravar o PDF em um arquivo, o IronOCR também pode retornar o PDF pesquisável como um array de bytes ou um stream.
Como exportar PDFs pesquisáveis como bytes ou streams?
A saída do PDF pesquisável também pode ser tratada como bytes ou streams usando os métodos SaveAsSearchablePdfBytes e SaveAsSearchablePdfStream, respectivamente. O exemplo de código abaixo mostra como usar esses métodos.
// 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()Essas opções de saída são particularmente úteis ao integrar com serviços de armazenamento em nuvem, bancos de dados ou aplicativos da web, onde o acesso ao sistema de arquivos pode ser limitado. O exemplo abaixo demonstra aplicações práticas:
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 ClassConsiderações sobre o desempenho
Ao processar grandes volumes de documentos, considere implementar operações de OCR multithread para aumentar o volume processado por unidade de tempo. O IronOCR permite processar vários documentos simultaneamente.
O paralelismo ocorre em dois níveis. O loop externo despacha vários documentos de uma vez, e cada chamada a Read aplica OCR a várias páginas em paralelo, com uma instância nativa do Tesseract por página processada simultaneamente. Sem limites, os dois níveis se multiplicam. Use ParallelOptions.MaxDegreeOfParallelism para limitar o loop externo e IronTesseract.MaxDegreeOfParallelism para limitar as leituras internas.
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 ClassOpções de configuração avançadas
Para cenários mais avançados, você pode aproveitar a configuração detalhada do Tesseract para ajustar o motor de OCR para tipos de documentos ou idiomas específicos:
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
}Essas opções de configuração se aplicam igualmente aos três métodos de saída: SaveAsSearchablePdf, SaveAsSearchablePdfBytes e SaveAsSearchablePdfStream. O resumo abaixo reúne os métodos de geração de PDFs pesquisáveis e seus respectivos formatos de saída.
Resumo
Criar PDFs pesquisáveis com o IronOCR é simples e flexível. A biblioteca gera PDFs pesquisáveis em vários formatos de saída, seja a partir de imagens individuais, documentos de várias páginas, fotos lidas com ReadPhoto ou digitalizações processadas com ReadDocumentAdvanced. Use o parâmetro ModelType para escolher entre os modelos de aprendizado de máquina padrão e aprimorado de acordo com a precisão necessária. A exportação como arquivos, bytes ou streams atende a diferentes arquiteturas, de aplicativos de desktop a serviços em nuvem.
Para cenários de OCR mais avançados, explore os exemplos de código abrangentes ou consulte a documentação da API para assinaturas de métodos detalhadas e opções.
Perguntas frequentes
O que é um PDF pesquisável e como é criado usando IronOCR?
Um PDF pesquisável é um tipo de documento PDF que combina imagens digitalizadas e texto legível por máquina. Ele é criado usando IronOCR ao realizar OCR em documentos digitalizados, convertendo o texto das imagens em texto pesquisável. Isso pode ser feito em C# configurando 'RenderSearchablePdf' como verdadeiro e usando o método 'SaveAsSearchablePdf'.
O IronOCR pode lidar com a conversão de documentos de várias páginas para PDFs pesquisáveis?
Sim, o IronOCR pode processar documentos de várias páginas. Ao usar o 'OcrPdfInput', o IronOCR processa cada página sequencialmente e mantém a estrutura original, permitindo a conversão de documentos de várias páginas em PDFs pesquisáveis.
Como exporto resultados de OCR como um PDF pesquisável com IronOCR?
Para exportar resultados de OCR como um PDF pesquisável, configure a propriedade 'Configuration.RenderSearchablePdf' como verdadeira, execute o método 'Read' para obter o resultado de OCR e, em seguida, use 'SaveAsSearchablePdf' para exportar o resultado para um caminho de arquivo.
Quais opções estão disponíveis para exportar um PDF pesquisável com IronOCR?
O IronOCR permite exportar PDFs pesquisáveis como arquivos, arrays de bytes ou fluxos usando métodos como 'SaveAsSearchablePdf', 'SaveAsSearchablePdfBytes' e 'SaveAsSearchablePdfStream'. Essas opções oferecem flexibilidade para integração com armazenamento em nuvem ou bancos de dados.
O IronOCR pode gerar PDFs pesquisáveis a partir de fotos ou digitalizações de documentos avançados?
Sim, o IronOCR suporta a geração de PDFs pesquisáveis a partir de fotos usando 'ReadPhoto' e de digitalizações de documentos avançados usando 'ReadDocumentAdvanced'. Ambos os métodos permitem exportar os resultados como PDFs pesquisáveis.
Como o IronOCR melhora a precisão do OCR com digitalizações de baixa qualidade?
O IronOCR melhora a precisão do OCR em digitalizações de baixa qualidade aplicando filtros de otimização de imagem. Usar o método 'ToGrayScale', por exemplo, reduz o ruído de cor, ajudando a melhorar o reconhecimento de texto.
Como podem ser corrigidos caracteres incorretos em PDFs pesquisáveis gerados por IronOCR?
Caracteres incorretos em PDFs pesquisáveis podem ser corrigidos especificando uma fonte compatível com Unicode ao usar 'SaveAsSearchablePdf'. Isso permite suporte total para todos os caracteres Unicode, resolvendo problemas com caracteres não ASCII.
Existe uma maneira de otimizar o desempenho com o IronOCR ao processar grandes volumes de documentos?
Sim, o IronOCR suporta processamento simultâneo, permitindo implementar operações de OCR multithread. Isso facilita o manuseio de vários documentos simultaneamente, melhorando o desempenho ao processar grandes volumes de documentos.
Quais opções de configuração avançadas estão disponíveis no IronOCR para criar PDFs pesquisáveis?
O IronOCR oferece opções de configuração avançadas, incluindo configuração detalhada do Tesseract, definição de variáveis do Tesseract e escolha de diferentes modos de segmentação de página. Estas podem ser ajustadas para afinar o OCR para tipos específicos de documentos ou idiomas.
Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.