C#中的批次PDF處理:大規模自動化文件工作流程

Ahmad Sohail
Ahmad Sohail
已更新: 2026年8月2日

在 C# 中使用 IronPDF 進行批次PDF處理,讓 .NET 開發人員能夠大規模自動化文件工作流程,從平行的 HTML 轉 PDF 轉換和批次合併/分割,到具備內建錯誤處理、重試邏輯和檢查點機制的非同步 PDF 管線。IronPDF 的 Chromium 引擎具備執行緒安全性,並以 IDisposable 管理記憶體,專為高吞吐量 PDF 自動化而設計,適用於地端、Azure Functions、AWS Lambda 或 Kubernetes。

TL;DR:快速入門指南

本教學涵蓋 C# 中可擴充的 PDF 自動化,從平行轉換和批次操作,到雲端部署及具備復原能力的管線模式。

  • 適合對象:負責大量文件工作流程的 .NET 開發人員和架構師,例如無法逐一處理文件的文件移轉專案、每日報告產生管線、法規遵循補救作業或檔案數位化工作。
  • 您將建置的內容:使用 Parallel.ForEach 的平行 HTML 轉換為 PDF、批次合併和分割操作、使用 SemaphoreSlim 的非同步管線進行並行控制、帶有失敗略過和重試邏輯的錯誤處理、當機恢復的檢查點/繼續模式以及適用於 Azure Functions、AWS Lambda 和 Kubernetes 的雲端部署配置。
  • 執行環境:.NET 6+、.NET Framework 4.6.2+、.NET Standard 2.0。所有轉譯均使用 IronPDF 的嵌入式 Chromium 引擎 - 不需要無頭瀏覽器依賴性或外部服務。
  • 何時使用這種方法:當您需要處理的 PDF 數量超出循序執行可負荷的範圍時,例如大規模文件移轉、必須在有限時間內完成的排程批次作業,或文件負載不固定的多租用戶平台。
  • 技術上的重要性:IronPDF 的 ChromePdfRenderer 具備執行緒安全性,且每次轉譯皆無狀態,因此多個執行緒可以安全地共用同一個轉譯器執行個體。結合 .NET 的工作平行程式庫和 PdfDocument 上的 IDisposable,即可讓記憶體使用情況可預測並充分利用 CPU,同時避免競爭條件或記憶體洩漏。

只需幾行程式碼,即可批次將整個目錄中的 HTML 檔案轉換為 PDF:

  1. 1使用 IronPDF 安裝 NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2複製並運行這段程式碼。

    using IronPdf;
    using System.IO;
    using System.Threading.Tasks;
    
    var renderer = new ChromePdfRenderer();
    var htmlFiles = Directory.GetFiles("input/", "*.html");
    
    Parallel.ForEach(htmlFiles, htmlFile =>
    {
        var pdf = renderer.RenderHtmlFileAsPdf(htmlFile);
        pdf.SaveAs($"output/{Path.GetFileNameWithoutExtension(htmlFile)}.pdf");
    });
  3. 3部署到您的生產環境進行測試

    立即在您的項目中開始使用 IronPDF,並使用 免費試用
    arrow pointer

購買或註冊 IronPDF 的 30 天試用版後,請在應用程式開始時新增您的授權金鑰。

IronPdf.License.LicenseKey = "KEY";

立即在您的項目中開始使用 IronPDF,免費試用。

第一步:
arrow pointer
NuGet使用NuGet安裝

PM > Install-Package IronPdf

在 NuGet 包管理器控制台中運行上述命令安裝 IronPDF,或在 NuGet 包管理器中搜索該包。
目錄

當您需要處理數千個 PDF 文件時

批次 PDF 處理不僅僅是小眾需求 - 它是在大企業文件管理中日常的一部分。 各行各業都會出現需要這樣做的情況,它們都有一個共同的特徵:一次只做一件事是不可行的。

文件移轉專案是最常見的觸發因素之一。 當一個組織從一個文件管理系統遷移到另一個文件管理系統時,需要轉換、重新格式化或重新標記成千上萬(有時甚至數百萬)份文件。 當一家保險公司從舊式理賠系統移轉時,可能需要將 50 萬份基於 TIFF 格式的理賠文件轉換為可搜尋的 PDF 檔案。 律師事務所遷移到新的案件管理平台時,可能需要將分散的信函合併成統一的案件檔案。 這些都是一次性工作,但規模龐大,而且容不得半點差錯。

每日報告產生則是同一問題的日常版本。金融機構每天收盤後為數千名客戶產生投資組合報告,物流公司為每個出貨貨櫃產生貨運清單,醫療系統為數百個部門建立每日病患摘要。這些工作產生的 PDF 數量龐大,若逐一處理就會超出可接受的時間範圍。當 10,000 份報告必須在早上 6 點前準備就緒,而資料到午夜才定案時,您無法花上六個小時逐一轉譯。

檔案數位化處於遷移和合規的交匯點。 政府機構、大學和擁有數十年紙本記錄的公司都面臨著將文件數位化並以符合標準的格式(通常是 PDF/A)存檔的強制性要求。 數量是驚人的 - 僅美國國家檔案和記錄局就會收到數以百萬計的聯邦記錄頁面以永久保存 - 並且該過程需要足夠可靠,以免您多年後才發現缺失之處。

合規補救措施通常是最迫切的觸發因素。 當一次審計揭示了您的文件檔案不符合新頒布的標準 - 比如,儲存的發票不符合 PDF/A-3 的電子發票規定,或者您的醫療記錄缺乏第 508 節要求的無障礙標籤 - 您需要根據新標準處理整個現有檔案。 壓力很大,時間很緊,而數量取決於您的檔案中剛好包含多少內容。

在所有這些場景中,核心挑戰都是一樣的:如何可靠、有效率地處理大量 PDF 操作,並且在出現問題時不會耗盡記憶體或留下未完成的工作?

資訊圖表顯示四個批次處理場景 —— 文件遷移、每日報告生成、檔案數位化、合規修復 —— 每個場景都有一個圖示、典型量級範圍和時間壓力指標


IronPDF 批次處理架構

在深入了解各項操作之前,您需要先了解 IronPDF 如何處理並行工作負載,以及以它建立批次管線時應做出哪些架構決策。

安裝 IronPDF

透過 NuGet 安裝 IronPDF:

PM > Install-Package IronPdf

或使用 .NET CLI:

> dotnet add package IronPdf

IronPDF 支援 .NET Framework 4.6.2+、.NET Core、.NET 5 至 .NET 10 和 .NET Standard 2.0。它可在 Windows、Linux、macOS 和 Docker 容器上執行,因此既適用於本機批次作業,也適用於雲端原生部署。

在正式環境進行批次處理時,請在應用程式啟動時,於任何 PDF 操作開始前使用 License.LicenseKey 設定授權金鑰。這可確保所有執行緒的每次轉譯呼叫都能使用完整功能,且各檔案不會加上浮水印。


並行控制和執行緒安全

IronPDF 基於 Chromium 的轉譯引擎是執行緒安全的。 您可以在多個執行緒中建立多個 ChromePdfRenderer 執行個體,或共享一個執行個體 - IronPDF 處理內部同步。 對於批次處理的官方建議是使用 .NET 的內建 Parallel.ForEach,它會自動分配工作到所有可用的 CPU 核心。

但值得指出的是,“執行緒安全”不等於“使用無限執行緒”。每次並行的 PDF 轉譯執行都會消耗記憶體(Chromium 引擎需要工作空間來解析 DOM、CSS 布局和影像光柵化),而在記憶體受限的系統上啟動過多的並行操作將降低效能或導致 OutOfMemoryException。 正確的並行級別取決於您的硬體:一個 16 核心伺服器具有 64 GB 記憶體可以輕鬆處理 8-12 的並行轉譯; 一個具有 8 GB 的 4 核心 VM 可能會限制在 2-4。使用 ParallelOptions.MaxDegreeOfParallelism 控制這一點 - 設定大約為您可用的 CPU 核心的一半作為起點,然後根據觀察到的記憶體壓力進行調整。

大規模記憶體管理

記憶體管理是批次 PDF 處理中最重要的考量。每個 PdfDocument 物件都會在記憶體中保留完整的 PDF 二進位內容,若未釋放這些物件,記憶體用量就會隨處理的檔案數量線性增加。

關鍵規則:對 PdfDocument 物件,務必使用 using 陳述式或明確呼叫 Dispose()。IronPDF 的 PdfDocument 實作了 IDisposable,未釋放物件是批次處理中最常見的記憶體問題原因。處理迴圈每次反覆執行時,都應建立 PdfDocument、完成工作並釋放物件。除非有明確理由且記憶體充足,否則切勿將 PdfDocument 物件累積在清單或集合中。

除了釋放物件之外,處理大型批次時也可考慮以下記憶體管理策略:

分塊處理,而不是一次載入所有內容。 如果您需要處理 50,000 個文件,不要將它們全部列舉到清單中然後遍歷 - 以 100 或 500 的批次處理,允許垃圾收集器在塊之間回收記憶體。

對於超大批次資料,強制在資料塊之間進行垃圾回收。 雖然您通常應該讓 GC 自行管理,但批次處理是一種少見的場景,其中在塊邊界之間呼叫 GC.Collect() 可以防止記憶體壓力的累積。

監控記憶體消耗 使用 GC.GetTotalMemory() 或處理程序級別度量。 如果記憶體使用率超過閾值(例如,可用 RAM 的 80%),則暫停處理,讓 GC 趕上進度。


進度報告和記錄

當一個批次作業需要幾個小時才能完成時,對其進度的可見性不是可選的,而是必需的。 至少,您應該記錄每個文件的開始和完成情況,追蹤成功/失敗次數,並提供剩餘時間的估計值。 在執行並行操作時,使用 Interlocked.Increment 進行執行緒安全計數,並定期記錄(每 50 或 100 個文件)而不是每個文件,以免淹沒您的輸出。 用 System.Diagnostics.Stopwatch 跟蹤您的經過時間,並計算一個執行中的每秒文件速率,以提供有意義的 ETA。

對於生產批次作業,可以考慮將進度寫入持久性儲存(資料庫、檔案或訊息佇列),以便監控儀表板可以顯示即時狀態,而無需直接連接到批次處理程序。


常見批次操作

架構基礎建置完畢後,讓我們來看看最常見的批次作業及其 IronPDF 實作。

批次 HTML 轉 PDF

HTML 轉 PDF 是最常見的大量操作。 無論您是使用範本產生發票、將 HTML 文件庫轉換為 PDF,還是從 Web 應用程式轉譯動態報告,模式都是一樣的:遍歷您的輸入,轉譯每個輸入,然後儲存輸出。

輸入(5 個 HTML 檔案)

HTML Invoice INV-2026-001

INV-2026-001

HTML Invoice INV-2026-002

INV-2026-002

HTML Invoice INV-2026-003

INV-2026-003

HTML Invoice INV-2026-004

INV-2026-004

HTML Invoice INV-2026-005

INV-2026-005

此實作使用 ChromePdfRenderer 和 Parallel.ForEach 來同時處理所有 HTML 文件,通過 MaxDegreeOfParallelism 控制並行性,以平衡吞吐量和記憶體消耗。 每個文件都使用 RenderHtmlFileAsPdf 轉譯,並保存到輸出目錄,通過執行緒安全的 Interlocked 計數器進行進度跟蹤。

using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Threading;

// Configure paths
string inputFolder = "input/";
string outputFolder = "output/";

Directory.CreateDirectory(outputFolder);

string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html");
Console.WriteLine($"Found {htmlFiles.Length} HTML files to convert");

// Create renderer instance (thread-safe, can be shared)
var renderer = new ChromePdfRenderer();

// Track progress
int processed = 0;
int failed = 0;

// Process in parallel with controlled concurrency
var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount / 2
};

Parallel.ForEach(htmlFiles, options, htmlFile =>
{
    try
    {
        string fileName = Path.GetFileNameWithoutExtension(htmlFile);
        string outputPath = Path.Combine(outputFolder, $"{fileName}.pdf");

        using var pdf = renderer.RenderHtmlFileAsPdf(htmlFile);
        pdf.SaveAs(outputPath);

        Interlocked.Increment(ref processed);
        Console.WriteLine($"[OK] {fileName}.pdf");
    }
    catch (Exception ex)
    {
        Interlocked.Increment(ref failed);
        Console.WriteLine($"[ERROR] {Path.GetFileName(htmlFile)}: {ex.Message}");
    }
});

Console.WriteLine($"\nComplete: {processed} succeeded, {failed} failed");

輸出


每張HTML發票都會產生對應的PDF檔案。 如上顯示的 INV-2026-001.pdf 是 5 個批次輸出之一。

對於基於範本的生成(例如,發票、報告),通常需要在轉譯之前將資料合併到 HTML 範本中。 方法非常簡單:載入一次您的 HTML 範本,使用 string.Replace 插入每個紀錄的資料(客戶名稱,總計,日期),將填充的 HTML 傳給並行迴圈中的 RenderHtmlAsPdf。IronPDF 也提供 RenderHtmlAsPdfAsync 以便在您想使用 async/await 而不是 Parallel.ForEach 的場景中使用 - 我們將在後面的部分詳細介紹非同步模式。


批次 PDF 合併

將多個 PDF 文件合併成組合文件在法律(合併案件檔案文件)、金融(將月度報表合併成季度報告)和出版工作流程中很常見。

using IronPdf;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

string inputFolder = "documents/";
string outputFolder = "merged/";

Directory.CreateDirectory(outputFolder);

// Group PDFs by prefix (e.g., "invoice-2026-01-*.pdf" -> one merged file)
var pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");
var groups = pdfFiles
    .GroupBy(f => Path.GetFileName(f).Split('-').Take(3).Aggregate((a, b) => $"{a}-{b}"))
    .Where(g => g.Count() > 1);

Console.WriteLine($"Found {groups.Count()} groups to merge");

foreach (var group in groups)
{
    string groupName = group.Key;
    var filesToMerge = group.OrderBy(f => f).ToList();

    Console.WriteLine($"Merging {filesToMerge.Count} files into {groupName}.pdf");

    try
    {
        // Load all PDFs for this group
        var pdfDocs = new List<PdfDocument>();
        foreach (string filePath in filesToMerge)
        {
            pdfDocs.Add(PdfDocument.FromFile(filePath));
        }

        // Merge all documents
        using var merged = PdfDocument.Merge(pdfDocs);
        merged.SaveAs(Path.Combine(outputFolder, $"{groupName}-merged.pdf"));

        // Dispose source documents
        foreach (var doc in pdfDocs)
        {
            doc.Dispose();
        }

        Console.WriteLine($"  [OK] Created {groupName}-merged.pdf ({merged.PageCount} pages)");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"  [ERROR] {groupName}: {ex.Message}");
    }
}

Console.WriteLine("\nMerge complete");

合併大量文件時,請留意記憶體用量:PdfDocument.Merge 方法會同時將所有來源文件載入記憶體。若要合併數百個大型 PDF,請考慮分階段合併,先將每 10–20 份文件合併為中間文件,再合併這些中間文件。

批次拆分 PDF

將多頁 PDF 檔案拆分成單一頁面(或頁面範圍)是合併的反向過程。 在郵件處理中,需要將一批掃描的文件分割成單獨的記錄;在列印工作流程中,需要將複合文件拆分成多個部分。

輸入

下面的程式碼示範了如何在平行迴圈中使用 CopyPage 提取個別頁面,為每個頁面建立單獨的 PDF 文件。 另外一個 SplitByRange 輔助函式示範如何提取頁面範圍而不是單個頁面,這對於將大文件分塊為較小段落很有用。

using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;

string inputFolder = "multipage/";
string outputFolder = "split/";

Directory.CreateDirectory(outputFolder);

string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");
Console.WriteLine($"Found {pdfFiles.Length} PDFs to split");

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount / 2
};

Parallel.ForEach(pdfFiles, options, pdfFile =>
{
    string baseName = Path.GetFileNameWithoutExtension(pdfFile);

    try
    {
        using var pdf = PdfDocument.FromFile(pdfFile);
        int pageCount = pdf.PageCount;

        Console.WriteLine($"Splitting {baseName}.pdf ({pageCount} pages)");

        // Extract each page as a separate PDF
        for (int i = 0; i < pageCount; i++)
        {
            using var singlePage = pdf.CopyPage(i);
            string outputPath = Path.Combine(outputFolder, $"{baseName}-page-{i + 1:D3}.pdf");
            singlePage.SaveAs(outputPath);
        }

        Console.WriteLine($"  [OK] Created {pageCount} files from {baseName}.pdf");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"  [ERROR] {baseName}: {ex.Message}");
    }
});

// Alternative: Extract page ranges instead of individual pages
void SplitByRange(string inputFile, string outputFolder, int pagesPerChunk)
{
    using var pdf = PdfDocument.FromFile(inputFile);
    string baseName = Path.GetFileNameWithoutExtension(inputFile);
    int totalPages = pdf.PageCount;
    int chunkNumber = 1;

    for (int startPage = 0; startPage < totalPages; startPage += pagesPerChunk)
    {
        int endPage = Math.Min(startPage + pagesPerChunk - 1, totalPages - 1);
        using var chunk = pdf.CopyPages(startPage, endPage);
        chunk.SaveAs(Path.Combine(outputFolder, $"{baseName}-chunk-{chunkNumber:D3}.pdf"));
        chunkNumber++;
    }
}

Console.WriteLine("\nSplit complete");

輸出


第 2 頁已擷取為獨立 PDF 檔案 (annual-report-page-2.pdf)

IronPDF 的 CopyPage 和 CopyPages 方法會建立包含指定頁面的新 PdfDocument 物件。儲存後,請務必釋放來源文件物件及每個擷取頁面的文件物件。


批次壓縮

當儲存成本很重要,或者當您需要透過頻寬受限的連線傳輸 PDF 檔案時,批次壓縮可以顯著減少您的存檔佔用空間。 IronPDF 提供兩種壓縮方法:CompressImages 用於減少影像品質/大小,和 CompressStructTree 用於移除結構中繼資料。 新版 CompressAndSaveAs API(2025.12版引入)通過結合多種優化技術提供更好的壓縮效果。

using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Threading;

string inputFolder = "originals/";
string outputFolder = "compressed/";

Directory.CreateDirectory(outputFolder);

string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");
Console.WriteLine($"Found {pdfFiles.Length} PDFs to compress");

long totalOriginalSize = 0;
long totalCompressedSize = 0;
int processed = 0;

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount / 2
};

Parallel.ForEach(pdfFiles, options, pdfFile =>
{
    string fileName = Path.GetFileName(pdfFile);
    string outputPath = Path.Combine(outputFolder, fileName);

    try
    {
        long originalSize = new FileInfo(pdfFile).Length;
        Interlocked.Add(ref totalOriginalSize, originalSize);

        using var pdf = PdfDocument.FromFile(pdfFile);

        // Apply compression with JPEG quality setting (0-100, lower = more compression)
        pdf.CompressAndSaveAs(outputPath, 60);

        long compressedSize = new FileInfo(outputPath).Length;
        Interlocked.Add(ref totalCompressedSize, compressedSize);
        Interlocked.Increment(ref processed);

        double reduction = (1 - (double)compressedSize / originalSize) * 100;
        Console.WriteLine($"[OK] {fileName}: {originalSize / 1024}KB → {compressedSize / 1024}KB ({reduction:F1}% reduction)");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"[ERROR] {fileName}: {ex.Message}");
    }
});

double totalReduction = (1 - (double)totalCompressedSize / totalOriginalSize) * 100;
Console.WriteLine($"\nCompression complete:");
Console.WriteLine($"  Files processed: {processed}");
Console.WriteLine($"  Total original: {totalOriginalSize / 1024 / 1024}MB");
Console.WriteLine($"  Total compressed: {totalCompressedSize / 1024 / 1024}MB");
Console.WriteLine($"  Overall reduction: {totalReduction:F1}%");

關於壓縮,需要記住以下幾點:JPEG 品質設定低於 60 時,大多數影像都會出現可見的瑕疵。 ShrinkImage 選項在某些配置中可能會導致失真 - 在執行完整批次之前用代表性的樣本進行測試。 並且移除結構樹(CompressStructTree)將影響壓縮 PDF 中的文字選擇和搜尋,因此只有在不需要這些功能時才使用它。


大量格式轉換(PDF/A、PDF/UA)

將現有檔案轉換為符合標準的格式 - PDF/A 用於長期存檔或 PDF/UA 用於無障礙 - 是最有價值的批次操作之一。 IronPDF 支援所有 PDF/A 版本(包括 2025.11 版本新增的 PDF/A-4)和 PDF/UA 相容性(包括 2025.12 版本新增的 PDF/UA-2)。

輸入

範例使用 PdfDocument.FromFile 載入每個 PDF,然後使用 SaveAsPdfA 和參數 PdfAVersions.PdfA3b 將其轉換為 PDF/A-3b。 一個 ConvertToPdfUA 替代函式示範了使用 SaveAsPdfUA 的無障礙合規轉換,雖然 PDF/UA 需要具有正確結構標記的原始文件。

using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Threading;

string inputFolder = "originals/";
string outputFolder = "pdfa-archive/";

Directory.CreateDirectory(outputFolder);

string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");
Console.WriteLine($"Found {pdfFiles.Length} PDFs to convert to PDF/A-3b");

int converted = 0;
int failed = 0;

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount / 2
};

Parallel.ForEach(pdfFiles, options, pdfFile =>
{
    string fileName = Path.GetFileName(pdfFile);
    string outputPath = Path.Combine(outputFolder, fileName);

    try
    {
        using var pdf = PdfDocument.FromFile(pdfFile);

        // Convert to PDF/A-3b for long-term archival
        pdf.SaveAsPdfA(outputPath, PdfAVersions.PdfA3b);

        Interlocked.Increment(ref converted);
        Console.WriteLine($"[OK] {fileName} → PDF/A-3b");
    }
    catch (Exception ex)
    {
        Interlocked.Increment(ref failed);
        Console.WriteLine($"[ERROR] {fileName}: {ex.Message}");
    }
});

Console.WriteLine($"\nConversion complete: {converted} succeeded, {failed} failed");

// Alternative: Convert to PDF/UA for accessibility compliance
void ConvertToPdfUA(string inputFolder, string outputFolder)
{
    Directory.CreateDirectory(outputFolder);
    string[] files = Directory.GetFiles(inputFolder, "*.pdf");

    Parallel.ForEach(files, pdfFile =>
    {
        string fileName = Path.GetFileName(pdfFile);
        try
        {
            using var pdf = PdfDocument.FromFile(pdfFile);

            // PDF/UA requires proper tagging - ensure source is well-structured
            pdf.SaveAsPdfUA(Path.Combine(outputFolder, fileName));
            Console.WriteLine($"[OK] {fileName} → PDF/UA");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[ERROR] {fileName}: {ex.Message}");
        }
    });
}

輸出

PDF/A轉換輸出比較顯示合規性中繼資料

輸出的 PDF 檔案在外觀上與原始文件完全相同,但現在包含 PDF/A-3b 合規中繼資料,可用於歸檔系統。

格式轉換對於合規性整改計畫尤其重要,因為組織會發現其現有檔案不符合監管標準。 批次模式是簡單的,但驗證步驟至關重要 - 總是驗證每個轉換後的文件實際通過合規檢查後再考慮它完成。 我們將在下面的復原能力一節詳細介紹驗證。


建置具備復原能力的批次管線

一個批次管線,如果處理 100 個文件時執行完美,但在處理 50,000 個文件中的第 4,327 個文件時當機,那麼這個管線就毫無用處。 復原能力 - 能夠優雅地處理錯誤,重試短暫失敗,並在當機後恢復 - 是將生產等級的管線與原型分開的關鍵。

錯誤處理和失敗時跳過

最基本的彈性模式是失敗時跳過:如果單一文件處理失敗,則記錄錯誤並繼續處理下一個文件,而不是中止整個批次。 這聽起來很明顯,但當您使用 Parallel.ForEach 時,卻很容易被忽略 - 在任何並行任務中的未處理例外將作為 AggregateException 傳播並終止迴圈。

以下範例同時示範失敗時跳過和重試邏輯 - 將每個文件包裹在try-catch中 以便優雅地錯誤處理,並使用指數退避內部重試迴圈來處理 IOException 和 OutOfMemoryException 等短暫異常:

using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;

string inputFolder = "input/";
string outputFolder = "output/";
string errorLogPath = "error-log.txt";

Directory.CreateDirectory(outputFolder);

string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html");
var renderer = new ChromePdfRenderer();
var errorLog = new ConcurrentBag<string>();

int processed = 0;
int failed = 0;
int retried = 0;

const int maxRetries = 3;

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount / 2
};

Parallel.ForEach(htmlFiles, options, htmlFile =>
{
    string fileName = Path.GetFileNameWithoutExtension(htmlFile);
    string outputPath = Path.Combine(outputFolder, $"{fileName}.pdf");
    int attempt = 0;
    bool success = false;

    while (attempt < maxRetries && !success)
    {
        attempt++;
        try
        {
            using var pdf = renderer.RenderHtmlFileAsPdf(htmlFile);
            pdf.SaveAs(outputPath);
            success = true;
            Interlocked.Increment(ref processed);

            if (attempt > 1)
            {
                Interlocked.Increment(ref retried);
                Console.WriteLine($"[OK] {fileName}.pdf (succeeded on attempt {attempt})");
            }
            else
            {
                Console.WriteLine($"[OK] {fileName}.pdf");
            }
        }
        catch (Exception ex) when (IsTransientException(ex) && attempt < maxRetries)
        {
            // Transient error - wait and retry with exponential backoff
            int delayMs = (int)Math.Pow(2, attempt) * 500;
            Console.WriteLine($"[RETRY] {fileName}: {ex.Message} (attempt {attempt}, waiting {delayMs}ms)");
            Thread.Sleep(delayMs);
        }
        catch (Exception ex)
        {
            // Non-transient error or max retries exceeded
            Interlocked.Increment(ref failed);
            string errorMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | {fileName} | {ex.GetType().Name} | {ex.Message}";
            errorLog.Add(errorMessage);
            Console.WriteLine($"[ERROR] {fileName}: {ex.Message}");
        }
    }
});

// Write error log
if (errorLog.Count > 0)
{
    File.WriteAllLines(errorLogPath, errorLog);
}

Console.WriteLine($"\nBatch complete:");
Console.WriteLine($"  Processed: {processed}");
Console.WriteLine($"  Failed: {failed}");
Console.WriteLine($"  Retried: {retried}");
if (failed > 0)
{
    Console.WriteLine($"  Error log: {errorLogPath}");
}

// Helper to identify transient exceptions worth retrying
bool IsTransientException(Exception ex)
{
    return ex is IOException ||
           ex is OutOfMemoryException ||
           ex.Message.Contains("timeout", StringComparison.OrdinalIgnoreCase) ||
           ex.Message.Contains("locked", StringComparison.OrdinalIgnoreCase);
}

批次完成後,查看錯誤日誌,以了解哪些檔案失敗以及失敗的原因。 常見故障原因包括來源檔案損壞、受密碼保護的 PDF、來源內容中不支援的功能以及處理非常大的文件時記憶體不足。

針對暫時性故障的重試邏輯

有些失敗是短暫的 - 如果您再試一次,它們會成功。 這些包括檔案系統爭用(另一個處理程序鎖定了檔案)、臨時記憶體壓力(垃圾回收器尚未跟上)以及在 HTML 內容中載入外部資源時的網路逾時。 上面的程式碼範例使用指數退避來處理這些問題 - 從短暫延遲開始,然後在每次重試嘗試時將其加倍,在重試次數達到最大(通常為 3)時封頂。

關鍵在於區分可重試的失敗和不可重試的失敗。 當 IOException(文件被鎖定)或 OutOfMemoryException(臨時壓力)出現時,值得重試。 而 ArgumentException(無效輸入)或持續發生的轉譯錯誤則不值得重試 - 重試不會有幫助,這只會浪費時間和資源。


當機後恢復的檢查點

當一個批次作業在幾個小時內處理 50,000 個文件時,在處理第 35,000 個文件時當機不應該意味著要從頭開始。 檢查點 - 記錄哪些文件已成功處理 - 允許您從上次中止的地方繼續。

using IronPdf;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;

string inputFolder = "input/";
string outputFolder = "output/";
string checkpointPath = "checkpoint.txt";
string errorLogPath = "errors.txt";

Directory.CreateDirectory(outputFolder);

// Load checkpoint - files already processed successfully
var completedFiles = new HashSet<string>();
if (File.Exists(checkpointPath))
{
    completedFiles = new HashSet<string>(File.ReadAllLines(checkpointPath));
    Console.WriteLine($"Resuming from checkpoint: {completedFiles.Count} files already processed");
}

// Get files to process (excluding already completed)
string[] allFiles = Directory.GetFiles(inputFolder, "*.html");
string[] filesToProcess = allFiles
    .Where(f => !completedFiles.Contains(Path.GetFileName(f)))
    .ToArray();

Console.WriteLine($"Files to process: {filesToProcess.Length} (skipping {completedFiles.Count} already done)");

var renderer = new ChromePdfRenderer();
var checkpointLock = new object();
int processed = 0;
int failed = 0;

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount / 2
};

Parallel.ForEach(filesToProcess, options, htmlFile =>
{
    string fileName = Path.GetFileName(htmlFile);
    string baseName = Path.GetFileNameWithoutExtension(htmlFile);
    string outputPath = Path.Combine(outputFolder, $"{baseName}.pdf");

    try
    {
        using var pdf = renderer.RenderHtmlFileAsPdf(htmlFile);
        pdf.SaveAs(outputPath);

        // Record success in checkpoint (thread-safe)
        lock (checkpointLock)
        {
            File.AppendAllText(checkpointPath, fileName + Environment.NewLine);
        }

        Interlocked.Increment(ref processed);
        Console.WriteLine($"[OK] {baseName}.pdf");
    }
    catch (Exception ex)
    {
        Interlocked.Increment(ref failed);

        // Log error for review
        lock (checkpointLock)
        {
            File.AppendAllText(errorLogPath,
                $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | {fileName} | {ex.Message}{Environment.NewLine}");
        }

        Console.WriteLine($"[ERROR] {fileName}: {ex.Message}");
    }
});

Console.WriteLine($"\nBatch complete:");
Console.WriteLine($"  Newly processed: {processed}");
Console.WriteLine($"  Failed: {failed}");
Console.WriteLine($"  Total completed: {completedFiles.Count + processed}");
Console.WriteLine($"  Checkpoint saved to: {checkpointPath}");

檢查點文件作為已完成工作的持久記錄。 當管線啟動時,它會讀取檢查點檔案並跳過任何已經成功處理的檔案。 文件處理完成後,其路徑會被追加到檢查點檔中。這種方法簡單易行,基於文件,且不需要任何外部依賴。

對於更複雜的場景,可以考慮使用資料庫表或分散式快取(如 Redis)作為檢查點儲存,尤其是在多個工作處理程序在不同的機器上並行處理文件的情況下。


處理前後的驗證

驗證是建構穩健流程的關鍵環節。預處理驗證可在問題輸入浪費處理時間之前將其捕獲;後處理驗證則確保輸出符合品質和合規性要求。

輸入

此實作透過 PreValidate 和 PostValidate 輔助函式,在處理迴圈前後執行驗證。處理前驗證會檢查檔案大小、內容類型及基本 HTML 結構。處理後驗證則確認輸出的 PDF 頁數有效且檔案大小合理,將通過驗證的檔案移至獨立資料夾,並將未通過的檔案送至拒收資料夾供人工審查。

using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;

string inputFolder = "input/";
string outputFolder = "output/";
string validatedFolder = "validated/";
string rejectedFolder = "rejected/";

Directory.CreateDirectory(outputFolder);
Directory.CreateDirectory(validatedFolder);
Directory.CreateDirectory(rejectedFolder);

string[] inputFiles = Directory.GetFiles(inputFolder, "*.html");
var renderer = new ChromePdfRenderer();

int preValidationFailed = 0;
int processingFailed = 0;
int postValidationFailed = 0;
int succeeded = 0;

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount / 2
};

Parallel.ForEach(inputFiles, options, inputFile =>
{
    string fileName = Path.GetFileNameWithoutExtension(inputFile);
    string outputPath = Path.Combine(outputFolder, $"{fileName}.pdf");

    // Pre-validation: Check input file
    if (!PreValidate(inputFile))
    {
        Interlocked.Increment(ref preValidationFailed);
        Console.WriteLine($"[SKIP] {fileName}: Failed pre-validation");
        return;
    }

    try
    {
        // Process
        using var pdf = renderer.RenderHtmlFileAsPdf(inputFile);
        pdf.SaveAs(outputPath);

        // Post-validation: Check output file
        if (PostValidate(outputPath))
        {
            // Move to validated folder
            string validatedPath = Path.Combine(validatedFolder, $"{fileName}.pdf");
            File.Move(outputPath, validatedPath, overwrite: true);
            Interlocked.Increment(ref succeeded);
            Console.WriteLine($"[OK] {fileName}.pdf (validated)");
        }
        else
        {
            // Move to rejected folder for manual review
            string rejectedPath = Path.Combine(rejectedFolder, $"{fileName}.pdf");
            File.Move(outputPath, rejectedPath, overwrite: true);
            Interlocked.Increment(ref postValidationFailed);
            Console.WriteLine($"[REJECT] {fileName}.pdf: Failed post-validation");
        }
    }
    catch (Exception ex)
    {
        Interlocked.Increment(ref processingFailed);
        Console.WriteLine($"[ERROR] {fileName}: {ex.Message}");
    }
});

Console.WriteLine($"\nValidation summary:");
Console.WriteLine($"  Succeeded: {succeeded}");
Console.WriteLine($"  Pre-validation failed: {preValidationFailed}");
Console.WriteLine($"  Processing failed: {processingFailed}");
Console.WriteLine($"  Post-validation failed: {postValidationFailed}");

// Pre-validation: Quick checks on input file
bool PreValidate(string filePath)
{
    try
    {
        var fileInfo = new FileInfo(filePath);

        // Check file exists and is readable
        if (!fileInfo.Exists) return false;

        // Check file is not empty
        if (fileInfo.Length == 0) return false;

        // Check file is not too large (e.g., 50MB limit)
        if (fileInfo.Length > 50 * 1024 * 1024) return false;

        // Quick content check - must be valid HTML
        string content = File.ReadAllText(filePath);
        if (string.IsNullOrWhiteSpace(content)) return false;
        if (!content.Contains("<html", StringComparison.OrdinalIgnoreCase) &&
            !content.Contains("<!DOCTYPE", StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }

        return true;
    }
    catch
    {
        return false;
    }
}

// Post-validation: Verify output PDF meets requirements
bool PostValidate(string pdfPath)
{
    try
    {
        using var pdf = PdfDocument.FromFile(pdfPath);

        // Check PDF has at least one page
        if (pdf.PageCount < 1) return false;

        // Check file size is reasonable (not just header, not corrupted)
        var fileInfo = new FileInfo(pdfPath);
        if (fileInfo.Length < 1024) return false;

        return true;
    }
    catch
    {
        return false;
    }
}

輸出

驗證輸入處理螢幕截圖

資料夾結構顯示驗證的目錄包含5個檔案及空的錯誤目錄

全部 5 個檔案均經過驗證並移至已驗證資料夾。

預處理驗證應該很快 - 您只是在檢查明顯損壞的輸入,而不是進行完整處理。 後處理驗證可以更徹底,特別是對於合規性轉換,輸出必須符合特定標準(PDF/A、PDF/UA)。 任何未通過後處理驗證的文件都應該標記為需要人工審核,而不是默默接受。


我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic

Microsoft MVP

查看案例研究

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle

首席技術官,OPYN

查看案例研究

非同步和平行處理模式

IronPDF 支援 Parallel.ForEach(基於執行緒的並行)和 async/await(非同步 I/O)。 了解何時使用哪種方法 - 以及如何有效地組合它們 - 是最大限度提高吞吐量的關鍵。

工作平行程式庫整合

Parallel.ForEach 是 CPU 密集型批次操作的最簡單和最有效的方法。 IronPDF 的轉譯引擎是 CPU 密集型的(HTML 解析、CSS 佈局、影像光柵化),並且 Parallel.ForEach 自動將此工作分配到所有可用的核心。

using IronPdf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

string inputFolder = "input/";
string outputFolder = "output/";

Directory.CreateDirectory(outputFolder);

string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html");
var renderer = new ChromePdfRenderer();

Console.WriteLine($"Processing {htmlFiles.Length} files with {Environment.ProcessorCount} CPU cores");

int processed = 0;
var stopwatch = Stopwatch.StartNew();

// Configure parallelism based on system resources
// Rule of thumb: ProcessorCount / 2 for memory-intensive operations
var options = new ParallelOptions
{
    MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount / 2)
};

Console.WriteLine($"Max parallelism: {options.MaxDegreeOfParallelism}");

// Use Parallel.ForEach for CPU-bound batch operations
Parallel.ForEach(htmlFiles, options, htmlFile =>
{
    string fileName = Path.GetFileNameWithoutExtension(htmlFile);
    string outputPath = Path.Combine(outputFolder, $"{fileName}.pdf");

    try
    {
        // Render HTML to PDF
        using var pdf = renderer.RenderHtmlFileAsPdf(htmlFile);
        pdf.SaveAs(outputPath);

        int current = Interlocked.Increment(ref processed);

        // Progress reporting every 10 files
        if (current % 10 == 0)
        {
            double elapsed = stopwatch.Elapsed.TotalSeconds;
            double rate = current / elapsed;
            double remaining = (htmlFiles.Length - current) / rate;
            Console.WriteLine($"Progress: {current}/{htmlFiles.Length} ({rate:F1} files/sec, ~{remaining:F0}s remaining)");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"[ERROR] {fileName}: {ex.Message}");
    }
});

stopwatch.Stop();
double totalRate = processed / stopwatch.Elapsed.TotalSeconds;

Console.WriteLine($"\nComplete:");
Console.WriteLine($"  Files processed: {processed}/{htmlFiles.Length}");
Console.WriteLine($"  Total time: {stopwatch.Elapsed.TotalSeconds:F1}s");
Console.WriteLine($"  Average rate: {totalRate:F1} files/sec");
Console.WriteLine($"  Time per file: {stopwatch.Elapsed.TotalMilliseconds / processed:F0}ms");

// Memory monitoring helper (call between chunks for large batches)
void CheckMemoryPressure()
{
    const long memoryThreshold = 4L * 1024 * 1024 * 1024; // 4 GB
    long currentMemory = GC.GetTotalMemory(forceFullCollection: false);

    if (currentMemory > memoryThreshold)
    {
        Console.WriteLine($"Memory pressure detected ({currentMemory / 1024 / 1024}MB), forcing GC...");
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }
}

MaxDegreeOfParallelism 選項至關重要。若未設定,TPL 會嘗試使用所有可用核心;若每次轉譯都需要大量資源,可能使記憶體不堪負荷。請以系統可用 RAM 除以每次轉譯的典型記憶體用量來設定此值(複雜 HTML 每次並行轉譯通常需要 100–300 MB)。

控制並行(SemaphoreSlim)

當您需要比 Parallel.ForEach 更精細的並行控制時,例如將非同步 I/O 與 CPU 密集型轉譯結合,SemaphoreSlim 可讓您明確控制同時執行的操作數量。做法很簡單:以所需的並行上限(例如同時轉譯 4 份文件)建立 SemaphoreSlim,在每次轉譯前呼叫 WaitAsync,並在轉譯後的 finally 區塊內呼叫 Release。接著使用 Task.WhenAll 啟動所有工作。

當您的管線同時包含 I/O 密集型步驟(從 blob 儲存讀取檔案、將結果寫入資料庫)和 CPU 密集型步驟(轉譯 PDF)時,這種模式尤其有用。 號誌限制了 CPU 密集型轉譯並行,同時允許 I/O 密集型步驟繼續進行而不會受到限制。

Async/Await 最佳做法

IronPDF 提供其轉譯方法的非同步變體,包括 RenderHtmlAsPdfAsync、RenderUrlAsPdfAsync 和 RenderHtmlFileAsPdfAsync。 這些非常適合 Web 應用程式(阻塞請求執行緒是不可接受的)以及將 PDF 轉譯與非同步 I/O 操作混合的管線。

以下是一些重要的非同步批次最佳做法:

不要使用 Task.Run 將同步 IronPDF 方法包裹起來 - 請改用原生的非同步變體。 在 Task.Run 中包裹同步方法浪費執行緒池執行緒,並增加了開銷而沒有任何好處。

不要在非同步任務上使用 .Result 或 .Wait() - 這會阻塞呼叫執行緒,並可能在 UI 或 ASP.NET 內容環境中造成死結。 始終使用 await。

將您的 Task.WhenAll 呼叫批次化,而不是一次等待所有任務。 如果您有 10,000 個任務並對它們同時呼叫 Task.WhenAll,將會啟動 10,000 個並行操作。 相反,使用 .Chunk(10) 或類似方法將其分組處理,依次等待每個組。

避免記憶體耗盡

記憶體耗盡是批次 PDF 處理中最常見的故障模式。 防禦性的方法是用 GC.GetTotalMemory() 監視每次轉譯前的記憶體使用情況,並在用量超過門檻(例如,4 GB 或 80% 可用 RAM)時觸發收集。 呼叫 GC.Collect(),然後呼叫 GC.WaitForPendingFinalizers(),再接著進行第二次 GC.Collect() 以在繼續之前回收盡可能多的記憶體。 這增加了一個小的暫停,但防止了 OutOfMemoryException 在第 30,000 個文件當機並摧毀整個批次的災難性情況。

結合 TPL 一節中的 MaxDegreeOfParallelism 節流控制,以及記憶體管理一節中的 using 釋放模式,即可建立三層記憶體防護:限制並行數量、及時釋放物件,以及透過監控機制在必要時採取保護措施。


批次作業的雲端部署

現代批次處理越來越常在雲端執行,可依工作負載需求擴充運算資源,並僅為實際使用的資源付費。IronPDF 可在所有主要雲端平台上執行,以下說明如何在各平台設計批次管線。

Azure Functions 與 Durable Functions

Azure Durable Functions 內建扇出/扇入模式的協調功能,非常適合批次 PDF 處理。協調器函式會將工作分配給多個活動函式執行個體,各自處理一部分檔案。協調器在扇出迴圈中呼叫 CallActivityAsync,每個活動函式會建立 ChromePdfRenderer 執行個體並處理分配到的檔案,最後由協調器收集結果。

Azure Functions 的重要考量:預設的使用量方案每次函式呼叫有 5 分鐘的逾時限制,且記憶體有限。批次處理請使用 Premium 或 Dedicated 方案,以支援更長的逾時時間和更大的記憶體。IronPDF 需要完整且未裁剪的 .NET 執行階段,因此請確保函式應用程式已設定為 .NET 8+,並使用適當的執行階段識別碼。

AWS Lambda 與 Step Functions

AWS Step Functions 提供的編排功能與 Azure Durable Functions 類似。 狀態機中的每一步都會呼叫一個 Lambda 函式來處理一部分檔案。 您的 Lambda handler 接收一批 S3 物件鍵,用 PdfDocument.FromFile 載入每個 PDF,應用處理管線(壓縮、格式轉換等),並將結果寫回到輸出 S3 儲存桶。

AWS Lambda 的執行時間最大為 15 分鐘,並且限制 /tmp 儲存(預設為 512 MB,可配置到 10 GB)。 對於大型批次作業,使用 Step Functions 將工作負載分塊,並在單獨的 Lambda 呼叫中處理每個區塊。 將中間結果儲存在 S3 中,而不是本機儲存中。

Kubernetes 作業排程

對於執行自己的 Kubernetes 叢集的組織而言,批次 PDF 處理與 Kubernetes Jobs 和 CronJobs 非常契合。 每個 pod 執行一個批次工作處理程序,該處理程序從佇列(Azure Service Bus、RabbitMQ 或 SQS)中提取文件,使用 IronPDF 處理它們,並將結果寫入物件儲存。 工作循環遵循早些部分中涵蓋的相同模式:佇列中取出訊息,使用 ChromePdfRenderer.RenderHtmlAsPdf() 或 PdfDocument.FromFile() 處理文件,上傳結果,並確認訊息。 用復原模式中的重試邏輯的 try-catch 包裹處理,並使用 SemaphoreSlim 控制每個 pod 的並行性。

IronPDF 提供官方 Docker 支援,並可在 Linux 容器上執行。 使用 IronPdf NuGet 套件與適合您的容器 OS 的原生執行階段套件(例如 IronPdf.Linux 用於基於 Linux 的映像)。 對於 Kubernetes,定義匹配 IronPDF 的記憶體需求的資源請求和限制(通常每個 pod 512 MB-2 GB,根據並行性而定)。 Horizontal Pod Autoscaler 可根據佇列深度擴充背景工作處理程序,且檢查點模式可確保在 Pod 被驅逐時不會遺失任何工作。

架構圖顯示雲端原生批次處理管線,包括工作佇列、運算層、物件儲存和監控儀表板


成本優化策略

如果資源分配不合理,雲端批次處理的成本可能會很高。 以下是一些影響最大的策略:

適當配置運算資源。PDF 轉譯需要大量 CPU 和記憶體資源,而非 GPU 資源。請使用運算最佳化執行個體(Azure 的 C 系列、AWS 的 C 類型),而非一般用途或記憶體最佳化執行個體,以取得更好的單次轉譯成本效益。

對於可以容忍中斷的大量工作負載,請使用競價型/搶佔型執行個體。 批次 PDF 處理本質上是可繼續的(得益於檢查點),使其成為競價型定價的理想候選,這通常提供比隨用隨取降低 60-90% 的折扣。

若時程允許,請在離峰時段處理。許多雲端供應商在夜間和週末提供較低的價格,或有更多可用的競價型執行個體。

儘早壓縮,一次儲存。將壓縮作為處理流程的一部分,而不是單獨執行一個步驟。從一開始就儲存壓縮後的 PDF 文件,可以降低整個存檔生命週期內的持續儲存成本。

對儲存進行分層。經常存取的已處理 PDF 文件應放在熱儲存中; 很少存取的歸檔 PDF 檔案應移至冷儲存層或歸檔層(Azure 冷儲存/歸檔,AWS S3 Glacier)。 僅此一項就可將儲存成本降低 50-80%。


實際管線範例

讓我們用一個完整的、生產級的批次管線將所有內容連結起來,以示範完整的工作流程:攝取 → 驗證 → 處理 → 歸檔 → 報告。

本範例處理 HTML 發票範本目錄,將其轉譯為 PDF,壓縮輸出,轉換為 PDF/A-3b 格式以符合存檔要求,驗證結果,並在最後產生摘要報告。

使用上面批次轉換範例中的相同的 5 個 HTML 發票…

using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.Json;

// Configuration
var config = new PipelineConfig
{
    InputFolder = "input/",
    OutputFolder = "output/",
    ArchiveFolder = "archive/",
    ErrorFolder = "errors/",
    CheckpointPath = "pipeline-checkpoint.json",
    ReportPath = "pipeline-report.json",
    MaxConcurrency = Math.Max(1, Environment.ProcessorCount / 2),
    MaxRetries = 3,
    JpegQuality = 70
};

// Initialize folders
Directory.CreateDirectory(config.OutputFolder);
Directory.CreateDirectory(config.ArchiveFolder);
Directory.CreateDirectory(config.ErrorFolder);

// Load checkpoint for resume capability
var checkpoint = LoadCheckpoint(config.CheckpointPath);
var results = new ConcurrentBag<ProcessingResult>();
var stopwatch = Stopwatch.StartNew();

// Get files to process
string[] allFiles = Directory.GetFiles(config.InputFolder, "*.html");
string[] filesToProcess = allFiles
    .Where(f => !checkpoint.CompletedFiles.Contains(Path.GetFileName(f)))
    .ToArray();

Console.WriteLine($"Pipeline starting:");
Console.WriteLine($"  Total files: {allFiles.Length}");
Console.WriteLine($"  Already processed: {checkpoint.CompletedFiles.Count}");
Console.WriteLine($"  To process: {filesToProcess.Length}");
Console.WriteLine($"  Concurrency: {config.MaxConcurrency}");

var renderer = new ChromePdfRenderer();
var checkpointLock = new object();

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = config.MaxConcurrency
};

Parallel.ForEach(filesToProcess, options, inputFile =>
{
    var result = new ProcessingResult
    {
        FileName = Path.GetFileName(inputFile),
        StartTime = DateTime.UtcNow
    };

    try
    {
        // Stage: Pre-validation
        if (!ValidateInput(inputFile))
        {
            result.Status = "PreValidationFailed";
            result.Error = "Input file failed validation";
            results.Add(result);
            return;
        }

        string baseName = Path.GetFileNameWithoutExtension(inputFile);
        string tempPath = Path.Combine(config.OutputFolder, $"{baseName}.pdf");
        string archivePath = Path.Combine(config.ArchiveFolder, $"{baseName}.pdf");

        // Stage: Process with retry
        PdfDocument pdf = null;
        int attempt = 0;
        bool success = false;

        while (attempt < config.MaxRetries && !success)
        {
            attempt++;
            try
            {
                pdf = renderer.RenderHtmlFileAsPdf(inputFile);
                success = true;
            }
            catch (Exception ex) when (IsTransient(ex) && attempt < config.MaxRetries)
            {
                Thread.Sleep((int)Math.Pow(2, attempt) * 500);
            }
        }

        if (!success || pdf == null)
        {
            result.Status = "ProcessingFailed";
            result.Error = "Max retries exceeded";
            results.Add(result);
            return;
        }

        using (pdf)
        {
            // Stage: Compress and convert to PDF/A-3b for archival
            pdf.SaveAsPdfA(tempPath, PdfAVersions.PdfA3b);
        }

        // Stage: Post-validation
        if (!ValidateOutput(tempPath))
        {
            File.Move(tempPath, Path.Combine(config.ErrorFolder, $"{baseName}.pdf"), overwrite: true);
            result.Status = "PostValidationFailed";
            result.Error = "Output file failed validation";
            results.Add(result);
            return;
        }

        // Stage: Archive
        File.Move(tempPath, archivePath, overwrite: true);

        // Update checkpoint
        lock (checkpointLock)
        {
            checkpoint.CompletedFiles.Add(result.FileName);
            SaveCheckpoint(config.CheckpointPath, checkpoint);
        }

        result.Status = "Success";
        result.OutputSize = new FileInfo(archivePath).Length;
        result.EndTime = DateTime.UtcNow;
        results.Add(result);

        Console.WriteLine($"[OK] {baseName}.pdf ({result.OutputSize / 1024}KB)");
    }
    catch (Exception ex)
    {
        result.Status = "Error";
        result.Error = ex.Message;
        result.EndTime = DateTime.UtcNow;
        results.Add(result);
        Console.WriteLine($"[ERROR] {result.FileName}: {ex.Message}");
    }
});

stopwatch.Stop();

// Generate report
var report = new PipelineReport
{
    TotalFiles = allFiles.Length,
    ProcessedThisRun = results.Count,
    Succeeded = results.Count(r => r.Status == "Success"),
    PreValidationFailed = results.Count(r => r.Status == "PreValidationFailed"),
    ProcessingFailed = results.Count(r => r.Status == "ProcessingFailed"),
    PostValidationFailed = results.Count(r => r.Status == "PostValidationFailed"),
    Errors = results.Count(r => r.Status == "Error"),
    TotalDuration = stopwatch.Elapsed,
    AverageFileTime = results.Any() ? TimeSpan.FromMilliseconds(stopwatch.Elapsed.TotalMilliseconds / results.Count) : TimeSpan.Zero
};

string reportJson = JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(config.ReportPath, reportJson);

Console.WriteLine($"\n=== Pipeline Complete ===");
Console.WriteLine($"Succeeded: {report.Succeeded}");
Console.WriteLine($"Failed: {report.PreValidationFailed + report.ProcessingFailed + report.PostValidationFailed + report.Errors}");
Console.WriteLine($"Duration: {report.TotalDuration.TotalMinutes:F1} minutes");
Console.WriteLine($"Report: {config.ReportPath}");

// Helper methods
bool ValidateInput(string path)
{
    try
    {
        var info = new FileInfo(path);
        if (!info.Exists || info.Length == 0 || info.Length > 50 * 1024 * 1024) return false;
        string content = File.ReadAllText(path);
        return content.Contains("<html", StringComparison.OrdinalIgnoreCase) ||
               content.Contains("<!DOCTYPE", StringComparison.OrdinalIgnoreCase);
    }
    catch { return false; }
}

bool ValidateOutput(string path)
{
    try
    {
        using var pdf = PdfDocument.FromFile(path);
        return pdf.PageCount > 0 && new FileInfo(path).Length > 1024;
    }
    catch { return false; }
}

bool IsTransient(Exception ex) =>
    ex is IOException || ex is OutOfMemoryException ||
    ex.Message.Contains("timeout", StringComparison.OrdinalIgnoreCase);

Checkpoint LoadCheckpoint(string path)
{
    if (File.Exists(path))
    {
        string json = File.ReadAllText(path);
        return JsonSerializer.Deserialize<Checkpoint>(json) ?? new Checkpoint();
    }
    return new Checkpoint();
}

void SaveCheckpoint(string path, Checkpoint cp) =>
    File.WriteAllText(path, JsonSerializer.Serialize(cp));


// Data classes
public class PipelineConfig
{
    public string InputFolder { get; set; } = "";
    public string OutputFolder { get; set; } = "";
    public string ArchiveFolder { get; set; } = "";
    public string ErrorFolder { get; set; } = "";
    public string CheckpointPath { get; set; } = "";
    public string ReportPath { get; set; } = "";
    public int MaxConcurrency { get; set; }
    public int MaxRetries { get; set; }
    public int JpegQuality { get; set; }
}

public class Checkpoint
{
    public HashSet<string> CompletedFiles { get; set; } = new();
}

public class ProcessingResult
{
    public string FileName { get; set; } = "";
    public string Status { get; set; } = "";
    public string Error { get; set; } = "";
    public long OutputSize { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
}

public class PipelineReport
{
    public int TotalFiles { get; set; }
    public int ProcessedThisRun { get; set; }
    public int Succeeded { get; set; }
    public int PreValidationFailed { get; set; }
    public int ProcessingFailed { get; set; }
    public int PostValidationFailed { get; set; }
    public int Errors { get; set; }
    public TimeSpan TotalDuration { get; set; }
    public TimeSpan AverageFileTime { get; set; }
}

輸出

管線報告JSON顯示批次處理結果,包括成功計數、失敗計數和總持續時間

管線報告顯示批次處理結果。

此管線整合了本教學介紹的所有模式:控制並行數量的平行處理、逐檔處理並在失敗時略過的錯誤處理、暫時性錯誤的重試邏輯、當機後接續處理的檢查點、處理前後驗證、明確釋放物件的記憶體管理,以及含最終摘要報告的完整記錄。

此管線的輸出是一個包含壓縮的、符合 PDF/A-3b 標準的歸檔檔案的目錄、一個用於復原功能的檢查點檔案、一個用於記錄無法處理的檔案的錯誤日誌,以及一個包含處理統計資訊的摘要報告。 這是任何正式的批次 PDF 處理工作負載所需的模式。


後續步驟

大規模批次 PDF 處理不只是循環中呼叫轉譯方法。它需要圍繞並行性、記憶體管理、錯誤處理和部署進行深思熟慮的架構 - 和合適的程式庫來讓一切正常執行。 IronPDF 提供執行緒安全的轉譯引擎,非同步 API 介面,壓縮工具,和 格式轉換能力,這些構成了任何 .NET 批次 PDF 管線的基礎。

無論您要建立在黎明前產生數千份 PDF 的夜間報告產生器、將舊有文件檔案移轉為符合 PDF/A 標準,或在 Kubernetes 上建置雲端原生處理服務,本教學的模式都能提供經過驗證的開發架構。透過控制並行數量進行平行處理,可維持高吞吐量。當個別檔案發生問題時,失敗時略過及重試邏輯能讓管線繼續運作。檢查點可確保處理進度不會遺失。雲端部署模式則讓您依工作負載擴充運算資源。

準備開始開發了嗎?下載 IronPDF 並免費試用,同一套程式庫即可處理單一檔案轉譯到十萬份檔案的批次管線。若您對特定使用情境的擴充、部署或架構有疑問,請聯絡我們的工程支援團隊。我們已協助團隊建立各種規模的批次管線,也很樂意協助您妥善設計。

常見問題

C# 中的批次 PDF 處理是什麼?

在C#中進行批次PDF處理指的是自動化文件工作流程,例如HTML到PDF的轉換、合併、拆分,並使用IronPDF實現具彈性的管道模式。它允許大規模處理PDF,具有可靠的錯誤處理和雲端部署能力。

我如何設置IronPDF進行批次處理?

您可以通過NuGet或.NET CLI安裝IronPDF來設置批次處理。確保您的應用使用.NET 6以上版本,並配置IronPDF的有效授權金鑰以解鎖其全部功能以進行高吞吐量操作。

IronPDF能處理批次工作的雲端部署嗎?

可以,IronPDF支持在Azure Functions、AWS Lambda和Kubernetes等平台上進行批次工作的雲端部署。它設計用於整合雲端原生架構,提供可擴展性和高效資源使用。

IronPDF支持的常見批次操作有哪些?

IronPDF支持的常見批次操作包括HTML到PDF的轉換、PDF的合併和拆分、批次壓縮,以及轉換格式為如PDF/A和PDF/UA等標準。

為什麼錯誤處理在批次PDF處理中很重要?

錯誤處理在批次PDF處理中至關重要以確保彈性。它允許自動化過程優雅地略過錯誤,重試臨時失敗,防止因單個文件失敗而導致系統崩潰,從而保持穩定的工作流程。

IronPDF在批次處理期間如何管理記憶體?

IronPDF在批次處理期間通過對PdfDocument實施IDisposable和支持最大化CPU使用的平行處理來管理記憶體。使用後處理PdfDocument物件對象以防止記憶體洩漏是很重要的。

有哪些策略可以優化基於雲端的批次PDF處理成本?

成本優化策略包括使用計算優化的實例、點價、在非高峰時段處理、壓縮和有效地存儲PDF,以及使用分層存儲選項對存檔文件進行存儲。

如何在IronPDF批次工作中實現併發控制?

在IronPDF批次工作中實現併發控制可以使用.NET的Parallel.ForEach進行CPU密集型操作或使用SemaphoreSlim進行更細緻的控制,特別是在將異步I/O與密集的渲染任務混合時。

檢查點在批次PDF處理中的角色是什麼?

檢查點記錄成功處理的文件,允許您的批次PDF處理在崩潰後從最後一次成功的位置恢復,而無需從頭重新開始。

IronPDF可以將文件轉換成PDF/A以符合檔案存檔規範嗎?

可以,IronPDF可將文件轉換成各種PDF/A標準,包括PDF/A-3b,確保長期存檔相容性並符合行業法規。

Ahmad 是一位全端開發人員,精通 C#、Python 和 Web 技術。他對建立可擴展的軟體解決方案有著濃厚的興趣,並樂於探索如何在實際應用中實現設計與功能的完美結合。

閱讀更多

準備好開始了嗎?

NuGet 下載次數 22,321,142版本:2026.11剛剛發布