跳至頁尾內容
使用IRONPDF

HtmlToPdfDocument C# - DinkToPdf 替代軟體 | IronPDF

顯示OCRNet處理流程的圖表,包含五個階段:輸入圖像、預處理、特徵提取、使用OCRNet進行序列建模和解碼以生成提取的文字內容。

OCR.net是一個用於光學字元識別的深度學習框架,與IronPDF配合使用以從PDF中提取文字,並在.NET應用程式中生成可搜尋的文件。 此教學將向您展示如何連接這兩個工具,以便您的應用程式可以處理掃描文件、光柵化PDF頁面進行OCR,並將識別出的文字重新組裝成新的可搜尋PDF。

OCR.net模型在場景文字檢測和複雜環境中的字元識別方面表現優異。 當您將其與IronPDF的渲染引擎結合使用時,您將獲得完整的流程:生成或載入PDF,將其頁面導出為高解析度圖像,將這些圖像發送到OCR.net,並將結果重建為完整可搜尋的文件。

現在開始使用IronPDF。
green arrow pointer

如何開始使用IronPDF?

在構建OCR工作流程之前,您需要在您的專案中安裝IronPDF。 最快的方法是使用NuGet Package Manager控制台:

Install-Package IronPdf

或者直接通過NuGet UI搜索IronPDF來新增。 安裝後,在應用程式啟動時使用您的授權金鑰:

using IronPdf;

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
using IronPdf;

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
Imports IronPdf

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
$vbLabelText   $csharpLabel

免費試用授權可用,使您能夠在無任何限制的情況下測試全部功能。 IronPDF 支援在Windows、Linux和macOS上運行.NET 6, 7, 8和10,這意味著相同的程式碼可以在桌面應用程式、ASP.NET Core網路服務和容器化部署中運行。

對於 Docker 環境,IronPDF提供了一個預先配置的Linux部署指南精簡包變體以減少映像大小。如果您偏好遠程渲染架構,IronPDF Engine可以作為一個獨立的服務運行,支持任何支持的平台上的客戶端。

什麼是OCRNet,以及光學字元識別是如何運作的?

OCR.net是一種光學字元識別(OCR)的深度學習方法,可以識別不同字體樣式的字母和數字字元。 該模型使用優化的神經網路架構來捕捉輸入圖像中的空間特徵。 結合PDF生成能力,這些訓練模型在常見文件型別的識別方面提供了高精度。

OCR.net 背後的識別框架整合了一個門控迴圈單元(GRU)來提高特徵學習能力,並處理基於圖像的序列識別任務。 這種混合模型通過連接主義時效分類(CTC)實現了顯著的準確度,這是一種最初為序列標籤引入的技術,它能夠很好地應用於文件OCR。 持續進步不斷擴展OCR.net的語言支援,尤其是在與PDF文字提取工具整合時。

現代OCR流程的關鍵組成部分包括:

  • 文字檢測:使用訓練模型識別圖像中的文字內容區域
  • 場景文字檢測:在複雜背景和動態環境中定位文字
  • 字母數字字元識別:使用訓練模型以高驗證準確度識別字元
  • 模式識別:應用圖像處理技術進行輕量級場景文字識別

基於GRU的架構和連接主義時效分類能夠在容器化環境中有效利用資源,使OCR.net成為在Kubernetes部署中關心記憶體和CPU約束的實際選擇。 輕量級架構在保持強大的識別準確度的同時,保持Docker映像大小可控。

您應該在什麼時候使用OCR.net而不是傳統OCR庫?

當處理複雜場景文字、手寫文件或多語言內容時使用OCR.net更佳,特別是在基於模板的OCR失效的情況下。 它在需要跨硬體配置一致性能且無外部依賴的容器化應用程式中表現尤為出色。 該模型乾淨地處理UTF-8編碼,這對於國際語言支援非常重要。

基於傳統正則表達式或模板匹配的OCR系統在可變字體、手寫體或光線不均勻的圖像上會崩潰。 OCR.net的神經方法在這些情況下具有更好的泛化能力,因為它學習特徵,而不是匹配固定模板。 也就是說,如果您的文件是乾淨的、機器輸入的文字且格式一致,那麼較輕的庫可能速度更快且足夠使用。

在生產環境中OCR.net的常見資源需求是什麼?

生產部署通常需要2-4個CPU核心和4-8 GB的RAM以獲得良好的性能。 GPU加速在使用NVIDIA Docker運行時能夠為批量處理提供顯著的速度提升。這些需求與Azure App ServiceAWS Lambda部署相配合,儘管Lambda的記憶體上限意味著您應該在承諾前基準測試您的具體文件大小。

IronPDF如何建立用于OCR處理的PDF文件?

IronPDF給予.NET開發者對PDF生成的完整控制。 該程式庫可以透過其基於Chrome的渲染引擎將HTML字串URL和文件輸入渲染至光滑的PDF中。對於OCR工作流程,關鍵功能是RasterizeToImageFiles(),它將PDF頁面導出為適合識別的高解析度圖像。

using IronPdf;

// Create a PDF document with IronPDF
var renderer = new ChromePdfRenderer();

// Set 300 DPI for OCR accuracy -- higher DPI preserves text sharpness
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.DPI = 300;
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;

var pdf = renderer.RenderHtmlAsPdf(@"
    <h1>Document Report</h1>
    <p>Scene text integration for computer vision analysis.</p>
    <p>Text detection results for dataset and model analysis.</p>");

// Tag the document with searchable metadata
pdf.MetaData.Author = "OCR Processing Pipeline";
pdf.MetaData.Keywords = "OCR, Text Recognition, Computer Vision";
pdf.MetaData.ModifiedDate = DateTime.Now;

pdf.SaveAs("document-for-ocr.pdf");

// Export pages as PNG images for OCR.net -- 300 DPI is the recommended minimum
pdf.RasterizeToImageFiles("page-*.png", IronPdf.Imaging.ImageType.Png, 300);
using IronPdf;

// Create a PDF document with IronPDF
var renderer = new ChromePdfRenderer();

// Set 300 DPI for OCR accuracy -- higher DPI preserves text sharpness
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.DPI = 300;
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;

var pdf = renderer.RenderHtmlAsPdf(@"
    <h1>Document Report</h1>
    <p>Scene text integration for computer vision analysis.</p>
    <p>Text detection results for dataset and model analysis.</p>");

// Tag the document with searchable metadata
pdf.MetaData.Author = "OCR Processing Pipeline";
pdf.MetaData.Keywords = "OCR, Text Recognition, Computer Vision";
pdf.MetaData.ModifiedDate = DateTime.Now;

pdf.SaveAs("document-for-ocr.pdf");

// Export pages as PNG images for OCR.net -- 300 DPI is the recommended minimum
pdf.RasterizeToImageFiles("page-*.png", IronPdf.Imaging.ImageType.Png, 300);
Imports IronPdf

' Create a PDF document with IronPDF
Dim renderer As New ChromePdfRenderer()

' Set 300 DPI for OCR accuracy -- higher DPI preserves text sharpness
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.DPI = 300
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50

Dim pdf = renderer.RenderHtmlAsPdf("
    <h1>Document Report</h1>
    <p>Scene text integration for computer vision analysis.</p>
    <p>Text detection results for dataset and model analysis.</p>")

' Tag the document with searchable metadata
pdf.MetaData.Author = "OCR Processing Pipeline"
pdf.MetaData.Keywords = "OCR, Text Recognition, Computer Vision"
pdf.MetaData.ModifiedDate = DateTime.Now

pdf.SaveAs("document-for-ocr.pdf")

' Export pages as PNG images for OCR.net -- 300 DPI is the recommended minimum
pdf.RasterizeToImageFiles("page-*.png", IronPdf.Imaging.ImageType.Png, 300)
$vbLabelText   $csharpLabel

RasterizeToImageFiles()方法將PDF頁面轉換為指定DPI的PNG圖像。 在300 DPI時,文字邊緣仍然足夠清晰,以使OCR模型能夠區分相似的字元。 在150 DPI或更低時,在襯線字體和小字上辨識的準確度顯著下降。 導出後,將PNG文件上傳至OCR.net或直接傳遞給本地模型。

顯示PDF文件在圖像檢視器中顯示的截圖,顯示標題為

為什麼DPI設置影響OCR準確性?

較高的DPI設置(300-600)保留了文字的清晰度,OCR模型需要準確區分字元。 權衡是文件大小和處理時間。在300 DPI時,單個A4頁面大約會生成一個2-3 MB的PNG。 在600 DPI時會增至8-12 MB。 對於大部分文件來說,300 DPI是最佳平衡。 渲染選項讓您可以根據文件型別調整,而壓縮技術在OCR完成後幫助優化文件大小。

IronPDF如何處理容器化環境?

IronPDF的原生引擎確保在LinuxWindowsmacOS容器中的一致渲染。 對於高可用性服務,IronPDF與ASP.NET Core健康檢查端點整合,因此您可以實施準備性和活躍性檢查,以確保PDF渲染在將流量路由到容器實例之前是正常運行的。

using IronPdf;

// Kubernetes-compatible health check endpoint
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/health/ready", async () =>
{
    try
    {
        var renderer = new ChromePdfRenderer();
        var testPdf = await renderer.RenderHtmlAsPdfAsync("<p>Health check</p>");
        return testPdf.PageCount > 0 ? Results.Ok() : Results.Problem();
    }
    catch
    {
        return Results.Problem("PDF rendering unavailable");
    }
});

await app.RunAsync();
using IronPdf;

// Kubernetes-compatible health check endpoint
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/health/ready", async () =>
{
    try
    {
        var renderer = new ChromePdfRenderer();
        var testPdf = await renderer.RenderHtmlAsPdfAsync("<p>Health check</p>");
        return testPdf.PageCount > 0 ? Results.Ok() : Results.Problem();
    }
    catch
    {
        return Results.Problem("PDF rendering unavailable");
    }
});

await app.RunAsync();
Imports IronPdf

' Kubernetes-compatible health check endpoint
Dim builder = WebApplication.CreateBuilder(args)
Dim app = builder.Build()

app.MapGet("/health/ready", Async Function()
    Try
        Dim renderer = New ChromePdfRenderer()
        Dim testPdf = Await renderer.RenderHtmlAsPdfAsync("<p>Health check</p>")
        Return If(testPdf.PageCount > 0, Results.Ok(), Results.Problem())
    Catch
        Return Results.Problem("PDF rendering unavailable")
    End Try
End Function)

Await app.RunAsync()
$vbLabelText   $csharpLabel

使用自定義日誌記錄與此端點一起捕捉渲染時間,並識別在完全故障前degrad的容器。

OCR.net如何從PDF圖像中提取文字?

一旦IronPDF生成了PNG導出,您就會將它們上傳到OCR.net進行文字識別。 OCR.net流程處理圖像並返回各種字體樣式下的標準文字輸出。 它同時處理印刷及手寫文字,並支援60多種文件語言。

在線使用OCR.net:

  1. 前往https://ocr.net/
  2. 上傳從IronPDF導出的PNG或JPG圖像(最大2 MB)
  3. 從60多個可用選項中選擇文件語言
  4. 選擇輸出格式:純文字或可搜尋PDF
  5. 點擊"立即轉換"以使用OCR.net模型處理圖像

 OCR.net Web介面顯示文件上傳對話,設定語言為英語,且輸出格式設為文字。

OCR.net也提供API以實現自動化處理。 免費帳戶每小時限制50次請求,這是自動化流程的重要約束。 設計您的整合以優雅地處理速率限制響應,使用指數回退而不是硬性失敗:

using System;
using System.Net.Http;
using System.Threading.Tasks;

// Queue-based OCR processing with exponential backoff retry
async Task<string> ProcessOcrWithRetry(string imagePath, int maxRetries = 3)
{
    for (int attempt = 0; attempt < maxRetries; attempt++)
    {
        try
        {
            // Replace with your actual OCR.net API call
            return await CallOcrNetApi(imagePath);
        }
        catch (HttpRequestException ex) when (ex.Message.Contains("429"))
        {
            if (attempt == maxRetries - 1) throw;
            var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));
            await Task.Delay(delay);
        }
    }
    throw new InvalidOperationException("OCR processing failed after all retries");
}
using System;
using System.Net.Http;
using System.Threading.Tasks;

// Queue-based OCR processing with exponential backoff retry
async Task<string> ProcessOcrWithRetry(string imagePath, int maxRetries = 3)
{
    for (int attempt = 0; attempt < maxRetries; attempt++)
    {
        try
        {
            // Replace with your actual OCR.net API call
            return await CallOcrNetApi(imagePath);
        }
        catch (HttpRequestException ex) when (ex.Message.Contains("429"))
        {
            if (attempt == maxRetries - 1) throw;
            var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));
            await Task.Delay(delay);
        }
    }
    throw new InvalidOperationException("OCR processing failed after all retries");
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks

' Queue-based OCR processing with exponential backoff retry
Async Function ProcessOcrWithRetry(imagePath As String, Optional maxRetries As Integer = 3) As Task(Of String)
    For attempt As Integer = 0 To maxRetries - 1
        Try
            ' Replace with your actual OCR.net API call
            Return Await CallOcrNetApi(imagePath)
        Catch ex As HttpRequestException When ex.Message.Contains("429")
            If attempt = maxRetries - 1 Then Throw
            Dim delay As TimeSpan = TimeSpan.FromSeconds(Math.Pow(2, attempt))
            Await Task.Delay(delay)
        End Try
    Next
    Throw New InvalidOperationException("OCR processing failed after all retries")
End Function
$vbLabelText   $csharpLabel

對於無障礙工作流程,OCR文字提取允許視障使用者從先前僅為圖像的文件中接收音訊反饋。 將OCR.net輸出與IronPDF的PDF/UA合規性配對,建立輔助技術可以有效導航的文件。

如何構建完整的IronPDF和OCR.net工作流程?

將IronPDF與OCR.net連接,生成端對端的文件解決方案。 此工作流程有三個階段:導出PDF頁面為圖像、將圖像發送到OCR.net進行文字提取,然後將識別的文字重建為新的可搜尋PDF。

using IronPdf;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

// --- Stage 1: Export PDF pages as images for OCR ---
var scannedPdf = PdfDocument.FromFile("input-document.pdf");
var imageFiles = scannedPdf.RasterizeToImageFiles(
    "scan-page-{0}.png",
    IronPdf.Imaging.ImageType.Png,
    300 // 300 DPI -- minimum for reliable OCR accuracy
);

// --- Stage 2: Process each image through OCR.net ---
var ocrResults = new List<string>();
foreach (var imageFile in imageFiles)
{
    // Replace this placeholder with your actual OCR.net API integration
    string ocrText = await SendImageToOcrNet(imageFile);
    ocrResults.Add(ocrText);
}

// --- Stage 3: Reassemble recognized text as a searchable PDF ---
var htmlBuilder = new StringBuilder();
htmlBuilder.Append(@"<!DOCTYPE html><html><head>
    <style>body{font-family:Arial,sans-serif;margin:40px;}
    .page{page-break-after:always;} pre{white-space:pre-wrap;}</style>
    </head><body>");

for (int i = 0; i < ocrResults.Count; i++)
{
    htmlBuilder.AppendFormat(
        "<div class='page'><h2>Page {0}</h2><pre>{1}</pre></div>",
        i + 1,
        System.Web.HttpUtility.HtmlEncode(ocrResults[i])
    );
}
htmlBuilder.Append("</body></html>");

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.DPI = 300;
renderer.RenderingOptions.EnableJavaScript = false;

var searchablePdf = await renderer.RenderHtmlAsPdfAsync(htmlBuilder.ToString());
searchablePdf.MetaData.Title = "OCR Processed Document";
searchablePdf.MetaData.Subject = "Searchable PDF from OCR";
searchablePdf.MetaData.CreationDate = DateTime.UtcNow;
searchablePdf.SecuritySettings.AllowUserPrinting = true;
searchablePdf.SecuritySettings.AllowUserCopyPasteContent = true;

searchablePdf.SaveAs("searchable-document.pdf");
using IronPdf;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

// --- Stage 1: Export PDF pages as images for OCR ---
var scannedPdf = PdfDocument.FromFile("input-document.pdf");
var imageFiles = scannedPdf.RasterizeToImageFiles(
    "scan-page-{0}.png",
    IronPdf.Imaging.ImageType.Png,
    300 // 300 DPI -- minimum for reliable OCR accuracy
);

// --- Stage 2: Process each image through OCR.net ---
var ocrResults = new List<string>();
foreach (var imageFile in imageFiles)
{
    // Replace this placeholder with your actual OCR.net API integration
    string ocrText = await SendImageToOcrNet(imageFile);
    ocrResults.Add(ocrText);
}

// --- Stage 3: Reassemble recognized text as a searchable PDF ---
var htmlBuilder = new StringBuilder();
htmlBuilder.Append(@"<!DOCTYPE html><html><head>
    <style>body{font-family:Arial,sans-serif;margin:40px;}
    .page{page-break-after:always;} pre{white-space:pre-wrap;}</style>
    </head><body>");

for (int i = 0; i < ocrResults.Count; i++)
{
    htmlBuilder.AppendFormat(
        "<div class='page'><h2>Page {0}</h2><pre>{1}</pre></div>",
        i + 1,
        System.Web.HttpUtility.HtmlEncode(ocrResults[i])
    );
}
htmlBuilder.Append("</body></html>");

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.DPI = 300;
renderer.RenderingOptions.EnableJavaScript = false;

var searchablePdf = await renderer.RenderHtmlAsPdfAsync(htmlBuilder.ToString());
searchablePdf.MetaData.Title = "OCR Processed Document";
searchablePdf.MetaData.Subject = "Searchable PDF from OCR";
searchablePdf.MetaData.CreationDate = DateTime.UtcNow;
searchablePdf.SecuritySettings.AllowUserPrinting = true;
searchablePdf.SecuritySettings.AllowUserCopyPasteContent = true;

searchablePdf.SaveAs("searchable-document.pdf");
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks

' --- Stage 1: Export PDF pages as images for OCR ---
Dim scannedPdf = PdfDocument.FromFile("input-document.pdf")
Dim imageFiles = scannedPdf.RasterizeToImageFiles(
    "scan-page-{0}.png",
    IronPdf.Imaging.ImageType.Png,
    300 ' 300 DPI -- minimum for reliable OCR accuracy
)

' --- Stage 2: Process each image through OCR.net ---
Dim ocrResults As New List(Of String)()
For Each imageFile In imageFiles
    ' Replace this placeholder with your actual OCR.net API integration
    Dim ocrText As String = Await SendImageToOcrNet(imageFile)
    ocrResults.Add(ocrText)
Next

' --- Stage 3: Reassemble recognized text as a searchable PDF ---
Dim htmlBuilder As New StringBuilder()
htmlBuilder.Append("<!DOCTYPE html><html><head>
    <style>body{font-family:Arial,sans-serif;margin:40px;}
    .page{page-break-after:always;} pre{white-space:pre-wrap;}</style>
    </head><body>")

For i As Integer = 0 To ocrResults.Count - 1
    htmlBuilder.AppendFormat(
        "<div class='page'><h2>Page {0}</h2><pre>{1}</pre></div>",
        i + 1,
        System.Web.HttpUtility.HtmlEncode(ocrResults(i))
    )
Next
htmlBuilder.Append("</body></html>")

Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.DPI = 300
renderer.RenderingOptions.EnableJavaScript = False

Dim searchablePdf = Await renderer.RenderHtmlAsPdfAsync(htmlBuilder.ToString())
searchablePdf.MetaData.Title = "OCR Processed Document"
searchablePdf.MetaData.Subject = "Searchable PDF from OCR"
searchablePdf.MetaData.CreationDate = DateTime.UtcNow
searchablePdf.SecuritySettings.AllowUserPrinting = True
searchablePdf.SecuritySettings.AllowUserCopyPasteContent = True

searchablePdf.SaveAs("searchable-document.pdf")
$vbLabelText   $csharpLabel

此流程有意簡化。 第1階段生成有編號的PNG文件。 第2階段將每個文件發送到OCR.net,並收集返回的文字字串。 第3階段將這些字串包裹在HTML中,使用IronPDF渲染最終PDF,其中的文字完全可選擇並可搜尋。 您可以擴展第3階段以應用PDF元資料以進行文件管理,或安全設置以進行存取控制。

 顯示兩個PDF檢視器窗口並排比較的截圖,左側顯示關於'What is a PDF?'的掃描PDF,右側顯示成功提取相同文字內容的OCR.net結果。

這個工作流程的最佳Docker配置是什麼?

多階段Docker構建保持最終映像小型化,同時包含IronPDF在Linux上需要的所有運行時依賴項:

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app

COPY *.csproj ./
RUN dotnet restore

COPY . ./
RUN dotnet publish -c Release -o out

FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app

# IronPDF Linux runtime dependencies
RUN apt-get update && apt-get install -y \
    libgdiplus \
    libc6-dev \
    libx11-dev \
    && rm -rf /var/lib/apt/lists/*

COPY --from=build /app/out .

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8080/health/ready || exit 1

ENTRYPOINT ["dotnet", "OcrWorkflow.dll"]

對於生產規模,考慮Kubernetes作業以進行批量OCR操作。 Kubernetes作業提供自動重試,並行控制和資源隔離,使失敗的文件任務不會影響其他服務。 設定parallelism以匹配您的OCR.net API等級,並設backoffLimit為控制失敗容器重試的次數,在作業將任務標記為失敗之前。

如何監測生產中的性能指標?

跟踪OCR處理時間和成功率有助於在影響使用者之前識別瓶頸。 Prometheus與自定義指標是一種實用的方法:

using Prometheus;
using System;
using System.Threading.Tasks;

// Prometheus metrics for OCR pipeline observability
var ocrRequestsTotal = Metrics
    .CreateCounter("ocr_requests_total", "Total OCR requests processed");

var ocrDuration = Metrics
    .CreateHistogram("ocr_duration_seconds", "OCR processing duration in seconds",
        new HistogramConfiguration
        {
            Buckets = Histogram.LinearBuckets(0.1, 0.1, 10)
        });

var activeOcrJobs = Metrics
    .CreateGauge("ocr_active_jobs", "Currently active OCR jobs");

// Wrapper that tracks every OCR operation automatically
async Task<t> TrackOcrOperation<t>(Func<Task<t>> operation)
{
    using (ocrDuration.NewTimer())
    {
        activeOcrJobs.Inc();
        try
        {
            var result = await operation();
            ocrRequestsTotal.Inc();
            return result;
        }
        finally
        {
            activeOcrJobs.Dec();
        }
    }
}
using Prometheus;
using System;
using System.Threading.Tasks;

// Prometheus metrics for OCR pipeline observability
var ocrRequestsTotal = Metrics
    .CreateCounter("ocr_requests_total", "Total OCR requests processed");

var ocrDuration = Metrics
    .CreateHistogram("ocr_duration_seconds", "OCR processing duration in seconds",
        new HistogramConfiguration
        {
            Buckets = Histogram.LinearBuckets(0.1, 0.1, 10)
        });

var activeOcrJobs = Metrics
    .CreateGauge("ocr_active_jobs", "Currently active OCR jobs");

// Wrapper that tracks every OCR operation automatically
async Task<t> TrackOcrOperation<t>(Func<Task<t>> operation)
{
    using (ocrDuration.NewTimer())
    {
        activeOcrJobs.Inc();
        try
        {
            var result = await operation();
            ocrRequestsTotal.Inc();
            return result;
        }
        finally
        {
            activeOcrJobs.Dec();
        }
    }
}
Imports Prometheus
Imports System
Imports System.Threading.Tasks

' Prometheus metrics for OCR pipeline observability
Dim ocrRequestsTotal = Metrics.CreateCounter("ocr_requests_total", "Total OCR requests processed")

Dim ocrDuration = Metrics.CreateHistogram("ocr_duration_seconds", "OCR processing duration in seconds", 
    New HistogramConfiguration With {
        .Buckets = Histogram.LinearBuckets(0.1, 0.1, 10)
    })

Dim activeOcrJobs = Metrics.CreateGauge("ocr_active_jobs", "Currently active OCR jobs")

' Wrapper that tracks every OCR operation automatically
Async Function TrackOcrOperation(Of T)(operation As Func(Of Task(Of T))) As Task(Of T)
    Using ocrDuration.NewTimer()
        activeOcrJobs.Inc()
        Try
            Dim result = Await operation()
            ocrRequestsTotal.Inc()
            Return result
        Finally
            activeOcrJobs.Dec()
        End Try
    End Using
End Function
$vbLabelText   $csharpLabel

將這些指標與IronPDF的日誌記錄功能結合作以關聯渲染時間與OCR持續時間。 當OCR持續時間激增而渲染時間未相應增加時,瓶頸出現在OCR.net API調用或至其的網路路徑,而不是在PDF生成過程中。

下一步如何?

OCR.net與IronPDF的結合為您提供一個在.NET中進行文字提取和可搜尋PDF生成的實際途徑。 此流程涵蓋核心使用情況:從HTML創造PDF、高解析度導出適合OCR圖像、將圖像發送到OCR.net,並重組結果成為可完全搜尋的文件。

將此流程移至生產中的關鍵考慮因素:

  • 容器設置:使用IronPDF精簡包和多階段Docker構建以保持映像大小可控
  • 資源規劃:設定記憶體限制以適合您的文件大小和並發目標
  • 監控:實施Prometheus指標以及IronPDF的日誌記錄快速捕捉性能衰退
  • 吞吐量:利用異步操作和批次隊列管理以在OCR.net的速率限制下運行
  • 可靠性:在OCR.net API調用中構建指數退避重試邏輯和斷路器

先從免費試用授權開始,以在提交至生產授權前完整測試整個工作流程。 試用去除水印並解鎖所有功能,因此您的基準測試結果真實反映生產行為。 當您準備部署時,檢閱IronPDF授權選項以找到符合您使用模式的等級。

常見問題

OCR.net的功能是什麼以及它如何與IronPDF連接?

OCR.net是一種深度學習的OCR服務,它接受圖像輸入並返回辨識到的文字。IronPDF生成PDF並將其頁面匯出為圖像。這兩個工具在圖像層面上進行連接:IronPDF用RasterizeToImageFiles()匯出頁面,這些圖像被傳送到OCR.net以進行文字提取,並由IronPDF重新組裝成一個可搜尋的PDF。

當匯出PDF頁面以進行OCR時應使用什麼DPI?

300 DPI是可靠OCR準確率的標準最低要求。在300 DPI,文字邊緣足夠清晰,模型能夠區分相似字元。在150 DPI或更低時,準確率會在襯線字體和小字上下降。僅在來源文件包含非常小或退化的文字時才使用600 DPI,因為在600 DPI下每頁會產生大4-5倍的文件。

如何在生產中處理OCR.net API速率限制?

OCR.net免費帳戶允許每小時50次請求。在OCR調用中建立指數退避重試邏輯:接收到429響應時,等待Math.Pow(2, attempt)秒,然後重試到配置的最大次數。對於更高的吞吐量,升級到付費的OCR.net計畫或使用背景工作服務排隊請求。

IronPDF可以在Linux上的Docker容器中運行嗎?

可以。將libgdipluslibc6-devlibx11-dev新增到您的Dockerfile運行階段。使用多階段構建以保持最終映像體積小。IronPDF Slim包變體通過在您將IronPDF Engine運行作為單獨服務時排除內嵌的瀏覽器二進製檔進一步減少影像體積。

如何從OCR結果建立可搜尋PDF?

收集OCR.net返回的文字字串,將它們包裹在每個文件頁面的分頁課程的HTML中,並將HTML傳遞給ChromePdfRenderer.RenderHtmlAsPdfAsync()。生成的PDF包含可選擇、可搜尋的文字,供使用者和搜索引擎索引。

此工作流程是否支持多語言文件?

支持。OCR.net支持超過60種語言。在處理之前,在OCR.net介面或API調用中選擇目標語言。IronPDF本機處理UTF-8輸出,因此非拉丁字母的語言在重建的可搜尋PDF中能正確渲染。

如何在生產中監控OCR管道性能?

將Prometheus計數器、直方圖和計量器新增到您的處理服務中,以追蹤總請求數、持續時間分佈和活動作業。將Prometheus指標與IronPDF的自定義日誌記錄配對,以對應渲染時間和OCR API延遲,找出瓶頸發生的位置。

OCR.net和IronOCR有什麼區別?

OCR.net是一個外部的網路服務,通過API處理您上傳的圖像。IronOCR是Iron Software的一個.NET程式庫,它在您的應用程式中本地運行OCR處理,而不需要外部API呼叫。IronOCR更適合於離線環境或者當您需要更低延遲或更大的OCR引擎控制時。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話