跳過到頁腳內容
使用IRONPDF
如何在 .NET 6 中生成 PDF 文件

在 C# 14 中建立 PDF:2025 年使用 Visual Studio Code 的進階指南

對於現代 .NET 開發人員來說,使用 C# 建立 PDF 是一項必備技能,無論您是建立財務報告、產生醫療文件還是製作電子商務收據。借助合適的 .NET PDF 庫,您只需幾行程式碼即可將 HTML 內容轉換為專業的 PDF 文檔,從而完全掌控文檔的結構和外觀。

IronPDF 是目前最簡單、最容易使用的 .NET PDF 建立庫,學習曲線極為平緩,只需幾分鐘就能產生 PDF ,而不是幾個小時。 本指南將全面展示如何使用 IronPDF(一款功能強大的C# PDF 產生器)在 C# 中建立 PDF 文件。IronPdf能夠產生像素級精準的 PDF 文件,並支援所有現代 .NET 平台,包括即將於 2025 年 11 月發布的 .NET 10。本教程涵蓋了從最簡單的用例到最高級的PDF 生成場景的所有內容,但請不要被嚇到——從頭開始,循序漸進地學習即可。 您將學習產生 PDF 的多種方法,從簡單的 HTML 字串到複雜的多頁報告,以及如何解決常見問題並優化各種PDF 生成任務的效能。

快速入門:用 C# 建立你的第一個 PDF(不到 2 分鐘)

想立即產生 PDF 檔案嗎? 讓我們建立一個簡單但功能齊全的 PDF 文檔,以展示 .NET 中現代 PDF 生成功能的強大之處。 首先,透過 NuGet 套件管理器安裝 IronPDF - 這個單獨的套件包含了立即開始建立 PDF 所需的一切。 IronPDF對開發用戶免費,因此您可以在決定購買許可證之前試用所有功能。

Install-Package IronPdf

現在讓我們使用 C# 建立 PDF 內容:

using IronPdf;

// Instantiate the PDF generator - this is your gateway to PDF creation
var renderer = new ChromePdfRenderer();

// Create a PDF from HTML string - yes, it's really this simple!
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>");

// Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf");

Console.WriteLine("PDF generated successfully!");
using IronPdf;

// Instantiate the PDF generator - this is your gateway to PDF creation
var renderer = new ChromePdfRenderer();

// Create a PDF from HTML string - yes, it's really this simple!
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>");

// Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf");

Console.WriteLine("PDF generated successfully!");
Imports IronPdf

' Instantiate the PDF generator - this is your gateway to PDF creation
Private renderer = New ChromePdfRenderer()

' Create a PDF from HTML string - yes, it's really this simple!
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>")

' Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf")

Console.WriteLine("PDF generated successfully!")
$vbLabelText   $csharpLabel

就這樣!你剛剛用 C# 創建了你的第一個 PDF 文件。 無需學習複雜的 PDF API,無需安裝伺服器依賴項,無需掌握底層 PDF 命令。 輸入HTML,輸出PDF-這就是PDF產生應有的方式。 但這只是個開始——讓我們來探討為什麼這種方法如此強大,以及如何建立更複雜的 PDF 文件。

如何使用 C# 建立 PDF:快速概述

若要在 C# 中建立 PDF,您可以使用 IronPDF、QuestPDF 或 PDFsharp 等第三方程式庫。這些庫提供各種功能,包括從頭開始建立 PDF、將 HTML 轉換為 PDF 等等。

以下是流程概述:

  1. 安裝 PDF 函式庫:使用 Visual Studio 中的 NuGet 套件管理器安裝適當的函式庫。
  2. 建立新的 PDF 文件:實例化一個 PDF 文件物件。
  3. 新增內容:新增頁面、文字、圖像和其他元素。
  4. 儲存文件:指定文件路徑並儲存 PDF。

以下是使用IronPdf的範例:

using IronPdf;

public class Example
{
    public static void CreatePdf()
    {
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();

        // Add some text
        string htmlContent = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>";

        // Render HTML to PDF
        var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);

        // Save the PDF
        pdfDocument.SaveAs("MyDynamicPdf.pdf");
    }
}
using IronPdf;

public class Example
{
    public static void CreatePdf()
    {
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();

        // Add some text
        string htmlContent = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>";

        // Render HTML to PDF
        var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);

        // Save the PDF
        pdfDocument.SaveAs("MyDynamicPdf.pdf");
    }
}
Imports IronPdf

Public Class Example
	Public Shared Sub CreatePdf()
		' Create a new PDF document
		Dim pdf = New ChromePdfRenderer()

		' Add some text
		Dim htmlContent As String = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>"

		' Render HTML to PDF
		Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)

		' Save the PDF
		pdfDocument.SaveAs("MyDynamicPdf.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

現在,讓我們深入了解為什麼開發人員需要建立 PDF,並探索IronPdf如何讓這個過程變得簡單且強大。

為什麼開發人員需要使用 C# 建立 PDF 檔案?

使用 C#以程式設計方式建立 PDF自動化文件產生和簡化業務流程開闢了無限可能。IronPdf已獲得全球超過 1400 萬安裝開發人員的信賴,用於完成這些任務,因為它為在 .NET 中建立 PDF提供了無與倫比的可靠性和易用性。 在金融領域,開發人員使用 C#建立 PDF 發票、報表和監管報告,這些都需要精確的格式和安全功能。 醫療機構**將病患記錄、化驗結果和保險表格產生為 PDF 文件,以確保文件完整性和符合 HIPAA 法規。 電子商務平台產生帶有二維碼(使用IronQR等工具)的PDF 收據、出貨標籤和票據,二維碼直接嵌入到 PDF 中。 透過程式操作 PDF 文件**意味著您可以大規模地建立、修改和保護文檔,而無需人工幹預。

使用像IronPdf這樣的現代.NET PDF 庫的好處在於,它可以無縫整合到您組織現有的工作流程中。 無論您是轉換業務使用者的 Word 文件、轉換開發團隊的Markdown 文檔,還是從基於 Web 的報告產生 PDF ,IronPDF 都能輕鬆應對。 正是這種組織上的靈活性,使得企業選擇在 .NET 中以程序化方式生成 PDF——它無需手動創建文檔,減少錯誤,確保所有生成的 PDF 文檔的一致性,並節省員工大量時間。您無需學習專有的 PDF 語法或手動定位每個元素,即可使用HTML 和 CSS來設計文件。 這種方法可以顯著縮短開發時間,並輕鬆保持所有生成的 PDF 文件中品牌形象的一致性。 無論您是建立單頁發票還是複雜的多章節報告,原則都是一樣的——使用 HTML 進行設計,使用 C# 產生 PDF

在 C# 項目中設定 IronPDF

在開始建立 PDF 之前,讓我們確保您的開發環境已正確配置,以獲得最佳的 PDF 產生效果。IronPdf支援所有現代 .NET 版本,包括 .NET 8、.NET 9,並且符合計劃於 2025 年 11 月發布的.NET 10 版本(Iron Software 與 .NET 基金會和微軟密切合作,以確保第一天的兼容性)。 設定過程很簡單,但了解您的選項有助於您根據自身需求選擇最佳方案

安裝方法

方法一:Visual Studio 套件管理器(推薦給初學者)

使用 IronPDF最簡單的方法是透過 Visual Studio 內建的 NuGet 套件管理器。 此圖形介面使瀏覽、安裝和管理 PDF 生成依賴項變得簡單:

1.在"解決方案總管"中右鍵按一下專案 2.選擇"管理 NuGet 套件"。 3.按一下"瀏覽"並搜尋"IronPDF"。

  1. 選擇 Iron Software 提供的 IronPdf 軟體包
  2. 點選"安裝"並接受授權協議
套件管理控制台

方法 2:套件管理員控制台

對於喜歡使用命令列工具的開發人員,軟體包管理器控制台提供了一種快速安裝IronPdf的方法:

Install-Package IronPdf

方法三:.NET CLI(用於跨平台開發)

如果您使用的是 macOS、Linux 或更喜歡使用 .NET CLI,請在專案目錄中使用以下命令:

dotnet add package IronPdf

選擇合適的套餐

IronPDF 提供針對各種部署場景最佳化的不同 NuGet 套件。 了解這些選項有助於您最大限度地縮小部署規模優化效能

  • IronPdf :包含 Windows、macOS 和 Linux 所需一切的標準軟體包。 適用於大多數應用場景。 IronPdf.Slim :一個輕量級的基礎包,會在運行時下載特定於平台的組件。非常適合對套件大小有要求的雲端部署
  • IronPdf.Linux :專為 Linux 部署而最佳化,所有必要的依賴項已預先包裝。
  • IronPdf.MacOs :專為 macOS 環境量身定制,原生支援 Apple Silicon。

對於 Azure、AWS 或 Docker 等雲端部署環境,建議使用 IronPdf.Slim 來減少容器大小。首次使用時,所需元件將自動下載。

驗證您的安裝

安裝完成後,請使用以下簡單的測試(此測試會建立新文件)來驗證一切是否正常運作

using IronPdf;
using System.IO;

// Test yourIronPdfinstallation
var renderer = new ChromePdfRenderer();
var testPdf = renderer.RenderHtmlAsPdf("<p>Installation test successful!</p>");
testPdf.SaveAs("test.pdf");

if (File.Exists("test.pdf"))
{
    Console.WriteLine("IronPDF installed and working correctly!");
}
using IronPdf;
using System.IO;

// Test yourIronPdfinstallation
var renderer = new ChromePdfRenderer();
var testPdf = renderer.RenderHtmlAsPdf("<p>Installation test successful!</p>");
testPdf.SaveAs("test.pdf");

if (File.Exists("test.pdf"))
{
    Console.WriteLine("IronPDF installed and working correctly!");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

C#中產生PDF的不同方法有哪些?

IronPDF 提供多種****建立 PDF 文件的方法,每種方法都適用於不同的場景和要求。 了解這些方法有助於您在 .NET 中產生 PDF時,為您的特定用例選擇最有效的方法。 無論您是使用 HTML 字串從頭開始建立 PDF 、轉換現有文件,還是擷取即時 Web 內容,IronPDF 都能滿足您的需求,因為它是一款全面的C# PDF 產生器。 讓我們透過實際範例詳細探討每種方法,這些範例展示了C# 中 PDF 所建立的實際應用。

1. 從 HTML 字串建立 PDF(最靈活)

當您需要將 HTML 內容轉換為 PDF 格式時,使用 HTML 字串建立 PDF 可讓您完全控制最終文件的內容和樣式。 這種方法非常適合產生動態報告、發票或任何內容會根據資料而變化的文件。 您可以使用現代 HTML5 和 CSS3 功能(包括 flexbox 和網格佈局)將 HTML 內容轉換為專業的 PDF。 動態轉換 HTML 內容的能力使其成為C# 中最通用的 PDF 創建方法:

using IronPdf;
using System;
using System.Linq;

var renderer = new ChromePdfRenderer();

// Build dynamic content with data
var customerName = "Acme Corporation";
var orderDate = DateTime.Now;
var items = new[] { 
    new { Name = "Widget Pro", Price = 99.99m },
    new { Name = "Gadget Plus", Price = 149.99m }
};

// Create HTML with embedded data and modern CSS
var html = $@"
    <html>
    <head>
        <style>
            body {{ 
                font-family: 'Segoe UI', Arial, sans-serif; 
                margin: 40px;
                color: #333;
            }}
            .invoice-header {{
                display: flex;
                justify-content: space-between;
                border-bottom: 2px solid #0066cc;
                padding-bottom: 20px;
            }}
            .items-table {{
                width: 100%;
                margin-top: 30px;
                border-collapse: collapse;
            }}
            .items-table th {{
                background: #f0f0f0;
                padding: 10px;
                text-align: left;
            }}
        </style>
    </head>
    <body>
        <div class='invoice-header'>
            <div>
                <h1>Invoice</h1>
                <p>Customer: {customerName}</p>
            </div>
            <div>
                <p>Date: {orderDate:yyyy-MM-dd}</p>
                <p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
            </div>
        </div>

        <table class='items-table'>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>";

foreach (var item in items)
{
    html += $@"
                <tr>
                    <td>{item.Name}</td>
                    <td>${item.Price:F2}</td>
                </tr>";
}

html += @"
            </tbody>
        </table>
    </body>
    </html>";

// Generate the PDF document
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf");
using IronPdf;
using System;
using System.Linq;

var renderer = new ChromePdfRenderer();

// Build dynamic content with data
var customerName = "Acme Corporation";
var orderDate = DateTime.Now;
var items = new[] { 
    new { Name = "Widget Pro", Price = 99.99m },
    new { Name = "Gadget Plus", Price = 149.99m }
};

// Create HTML with embedded data and modern CSS
var html = $@"
    <html>
    <head>
        <style>
            body {{ 
                font-family: 'Segoe UI', Arial, sans-serif; 
                margin: 40px;
                color: #333;
            }}
            .invoice-header {{
                display: flex;
                justify-content: space-between;
                border-bottom: 2px solid #0066cc;
                padding-bottom: 20px;
            }}
            .items-table {{
                width: 100%;
                margin-top: 30px;
                border-collapse: collapse;
            }}
            .items-table th {{
                background: #f0f0f0;
                padding: 10px;
                text-align: left;
            }}
        </style>
    </head>
    <body>
        <div class='invoice-header'>
            <div>
                <h1>Invoice</h1>
                <p>Customer: {customerName}</p>
            </div>
            <div>
                <p>Date: {orderDate:yyyy-MM-dd}</p>
                <p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
            </div>
        </div>

        <table class='items-table'>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>";

foreach (var item in items)
{
    html += $@"
                <tr>
                    <td>{item.Name}</td>
                    <td>${item.Price:F2}</td>
                </tr>";
}

html += @"
            </tbody>
        </table>
    </body>
    </html>";

// Generate the PDF document
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf");
Imports IronPdf
Imports System
Imports System.Linq

Private renderer = New ChromePdfRenderer()

' Build dynamic content with data
Private customerName = "Acme Corporation"
Private orderDate = DateTime.Now
Private items = {
	New With {
		Key .Name = "Widget Pro",
		Key .Price = 99.99D
	},
	New With {
		Key .Name = "Gadget Plus",
		Key .Price = 149.99D
	}
}

' Create HTML with embedded data and modern CSS
Private html = $"
    <html>
    <head>
        <style>
            body {{ 
                font-family: 'Segoe UI', Arial, sans-serif; 
                margin: 40px;
                color: #333;
            }}
            .invoice-header {{
                display: flex;
                justify-content: space-between;
                border-bottom: 2px solid #0066cc;
                padding-bottom: 20px;
            }}
            .items-table {{
                width: 100%;
                margin-top: 30px;
                border-collapse: collapse;
            }}
            .items-table th {{
                background: #f0f0f0;
                padding: 10px;
                text-align: left;
            }}
        </style>
    </head>
    <body>
        <div class='invoice-header'>
            <div>
                <h1>Invoice</h1>
                <p>Customer: {customerName}</p>
            </div>
            <div>
                <p>Date: {orderDate:yyyy-MM-dd}</p>
                <p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
            </div>
        </div>

        <table class='items-table'>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>"

For Each item In items
	html += $"
                <tr>
                    <td>{item.Name}</td>
                    <td>${item.Price:F2}</td>
                </tr>"
Next item

html &= "
            </tbody>
        </table>
    </body>
    </html>"

' Generate the PDF document
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf")
$vbLabelText   $csharpLabel

2. 從 URL 產生 PDF(網頁擷取)

有時您需要將現有網頁轉換為 PDF 文件—非常適合存檔、報告或建立線上內容的離線版本。IronPdf的 URL 轉 PDF 功能使用真正的 Chromium 引擎,確保複雜的、JavaScript 密集型網站能夠正確渲染。 這種方法對於建立儀錶板快照、保存線上收據或記錄基於 Web 的報告非常有價值:

PDF 範例 URL
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;

// Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000; // 2 seconds

// Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = true;

// Capture a web page as PDF
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard-capture.pdf");

// For authenticated pages, you can set cookies
var cookieManager = renderer.RenderingOptions.CustomCookies;
cookieManager["session_id"] = "your-session-token";

// Capture authenticated content
var securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report");
securePdf.SaveAs("private-report.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;

// Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000; // 2 seconds

// Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = true;

// Capture a web page as PDF
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard-capture.pdf");

// For authenticated pages, you can set cookies
var cookieManager = renderer.RenderingOptions.CustomCookies;
cookieManager["session_id"] = "your-session-token";

// Capture authenticated content
var securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report");
securePdf.SaveAs("private-report.pdf");
Imports IronPdf

Private renderer = New ChromePdfRenderer()

' Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25

' Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000 ' 2 seconds

' Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = True

' Capture a web page as PDF
Dim pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard")
pdf.SaveAs("dashboard-capture.pdf")

' For authenticated pages, you can set cookies
Dim cookieManager = renderer.RenderingOptions.CustomCookies
cookieManager("session_id") = "your-session-token"

' Capture authenticated content
Dim securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report")
securePdf.SaveAs("private-report.pdf")
$vbLabelText   $csharpLabel

3. 從 HTML 檔案建立 PDF(基於模板的生成)

當您有複雜的佈局,並且設計人員可以將其與應用程式程式碼分開維護時,基於模板的 PDF 生成是理想的選擇。 透過將 HTML 模板儲存為文件,可以實現設計與邏輯的清晰分離。 這種方法在產生證書、合約或標準化報告等一致性文件方面效果非常好:

HTML 檔案到 PDF
using IronPdf;
using System.IO;
using System;

var renderer = new ChromePdfRenderer();

// Basic file conversion
var pdf = renderer.RenderHtmlFileAsPdf("Templates/certificate-template.html");
pdf.SaveAs("certificate.pdf");

// Advanced: Using templates with asset directories
// Perfect when your HTML references images, CSS, or JavaScript files
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", "Assets");
var pdfWithAssets = renderer.RenderHtmlFileAsPdf(
    "Templates/report-template.html", 
    basePath  //IronPdfwill resolve relative paths from here
);

// Even better: Template with placeholders
var templateHtml = File.ReadAllText("Templates/contract-template.html");
templateHtml = templateHtml
    .Replace("{{ClientName}}", "Tech Innovations Inc.")
    .Replace("{{ContractDate}}", DateTime.Now.ToString("MMMM dd, yyyy"))
    .Replace("{{ContractValue}}", "$50,000");

var contractPdf = renderer.RenderHtmlAsPdf(templateHtml);
contractPdf.SaveAs("contract-final.pdf");
using IronPdf;
using System.IO;
using System;

var renderer = new ChromePdfRenderer();

// Basic file conversion
var pdf = renderer.RenderHtmlFileAsPdf("Templates/certificate-template.html");
pdf.SaveAs("certificate.pdf");

// Advanced: Using templates with asset directories
// Perfect when your HTML references images, CSS, or JavaScript files
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", "Assets");
var pdfWithAssets = renderer.RenderHtmlFileAsPdf(
    "Templates/report-template.html", 
    basePath  //IronPdfwill resolve relative paths from here
);

// Even better: Template with placeholders
var templateHtml = File.ReadAllText("Templates/contract-template.html");
templateHtml = templateHtml
    .Replace("{{ClientName}}", "Tech Innovations Inc.")
    .Replace("{{ContractDate}}", DateTime.Now.ToString("MMMM dd, yyyy"))
    .Replace("{{ContractValue}}", "$50,000");

var contractPdf = renderer.RenderHtmlAsPdf(templateHtml);
contractPdf.SaveAs("contract-final.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

4. 將 Markdown 轉換為 PDF

Markdown 已成為技術文件、README 文件和內容管理系統的標準。IronPdf可以輕鬆地將 Markdown 內容直接轉換為 PDF ,在保留格式的同時建立專業外觀的文件。 對於使用 Markdown 格式維護文檔的組織來說,此功能尤其有價值——開發人員可以使用他們喜歡的格式編寫文檔,系統可以自動生成 PDF 文件,以便分發給客戶或利害關係人。

using IronPdf;

var renderer = new ChromePdfRenderer();

// Convert Markdown string to PDF
string markdownContent = @"
# Project Documentation

## Overview
This project demonstrates **PDF generation** from _Markdown_ content.

### Features
- Easy conversion
- Preserves formatting
- Supports lists and tables

|特點| Status |
|---------|--------|
| Markdown Support |  |
| Table Rendering |  |
| Code Blocks |  |

```csharp
// Code blocks are preserved
var pdf = RenderMarkdownAsPdf(markdown);
\`\`\`
";

// Render Markdown as PDF
var pdfFromMarkdown = renderer.RenderMarkdownStringAsPdf(markdownContent);
pdfFromMarkdown.SaveAs("documentation.pdf");

// Convert Markdown file to PDF
var pdfFromFile = renderer.RenderMarkdownFileAsPdf("README.md");
pdfFromFile.SaveAs("readme-pdf.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Convert Markdown string to PDF
string markdownContent = @"
# Project Documentation

## Overview
This project demonstrates **PDF generation** from _Markdown_ content.

### Features
- Easy conversion
- Preserves formatting
- Supports lists and tables

|特點| Status |
|---------|--------|
| Markdown Support |  |
| Table Rendering |  |
| Code Blocks |  |

```csharp
// Code blocks are preserved
var pdf = RenderMarkdownAsPdf(markdown);
\`\`\`
";

// Render Markdown as PDF
var pdfFromMarkdown = renderer.RenderMarkdownStringAsPdf(markdownContent);
pdfFromMarkdown.SaveAs("documentation.pdf");

// Convert Markdown file to PDF
var pdfFromFile = renderer.RenderMarkdownFileAsPdf("README.md");
pdfFromFile.SaveAs("readme-pdf.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Markdown 轉換 PDF 功能對於使用 Git 等版本控制系統的組織來說尤其有用。 您的整個文檔工作流程都可以自動化—開發人員更新 Markdown 文件,CI/CD 管道可自動產生 PDF 文檔,利害關係人無需任何人工幹預即可收到專業格式的文檔。IronPdf能與現有工作流程無縫集成,這正是許多開發團隊選擇它來滿足文件需求的原因。

5. 將 Word 文件 (DOCX) 轉換為 PDF

許多企業都有需要轉換為PDF格式的Word文檔,以便分發或存檔。IronPdf提供無縫的 DOCX 到 PDF 轉換,保留格式、影像,甚至郵件合併等複雜功能。 這項功能對企業來說具有變革性意義——業務用戶可以繼續在熟悉的 Microsoft Word 中工作,而係統會自動產生 PDF 文件以供外部分發。 DOCX 轉 PDF功能彌合了喜歡使用 Word 的商務使用者與需要安全、不可編輯的 PDF 文件之間的差距。

using IronPdf;
using System.Collections.Generic;

// Simple DOCX to PDF conversion
var docxRenderer = new DocxToPdfRenderer();
var pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx");
pdfFromDocx.SaveAs("proposal.pdf");

// Advanced: Mail merge functionality for mass document generation
var recipients = new List<Dictionary<string, string>>
{
    new() { ["Name"] = "John Smith", ["Company"] = "Tech Corp", ["Date"] = "March 15, 2024" },
    new() { ["Name"] = "Jane Doe", ["Company"] = "Innovation Inc", ["Date"] = "March 15, 2024" }
};

// Configure mail merge options
var options = new DocxPdfRenderOptions
{
    MailMergeDataSource = recipients,
    MailMergePrintAllInOnePdfDocument = false // Creates separate PDFs
};

// Generate personalized PDFs from template
foreach (var recipient in recipients)
{
    var personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options);
    personalizedPdf.SaveAs($"letter-{recipient["Name"].Replace(" ", "-")}.pdf");
}
using IronPdf;
using System.Collections.Generic;

// Simple DOCX to PDF conversion
var docxRenderer = new DocxToPdfRenderer();
var pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx");
pdfFromDocx.SaveAs("proposal.pdf");

// Advanced: Mail merge functionality for mass document generation
var recipients = new List<Dictionary<string, string>>
{
    new() { ["Name"] = "John Smith", ["Company"] = "Tech Corp", ["Date"] = "March 15, 2024" },
    new() { ["Name"] = "Jane Doe", ["Company"] = "Innovation Inc", ["Date"] = "March 15, 2024" }
};

// Configure mail merge options
var options = new DocxPdfRenderOptions
{
    MailMergeDataSource = recipients,
    MailMergePrintAllInOnePdfDocument = false // Creates separate PDFs
};

// Generate personalized PDFs from template
foreach (var recipient in recipients)
{
    var personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options);
    personalizedPdf.SaveAs($"letter-{recipient["Name"].Replace(" ", "-")}.pdf");
}
Imports IronPdf
Imports System.Collections.Generic

' Simple DOCX to PDF conversion
Private docxRenderer = New DocxToPdfRenderer()
Private pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx")
pdfFromDocx.SaveAs("proposal.pdf")

' Advanced: Mail merge functionality for mass document generation
Dim recipients = New List(Of Dictionary(Of String, String)) From {
	New() {
		("Name") = "John Smith",
		("Company") = "Tech Corp",
		("Date") = "March 15, 2024"
	},
	New() {
		("Name") = "Jane Doe",
		("Company") = "Innovation Inc",
		("Date") = "March 15, 2024"
	}
}

' Configure mail merge options
Dim options = New DocxPdfRenderOptions With {
	.MailMergeDataSource = recipients,
	.MailMergePrintAllInOnePdfDocument = False
}

' Generate personalized PDFs from template
For Each recipient In recipients
	Dim personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options)
	personalizedPdf.SaveAs($"letter-{recipient("Name").Replace(" ", "-")}.pdf")
Next recipient
$vbLabelText   $csharpLabel

DOCX轉換功能對於實現組織內部文件工作流程的自動化至關重要。 假設一個銷售團隊使用 Word 建立提案——借助 IronPDF,這些提案可以自動轉換為 PDF,並以程式設計方式套用浮水印、安全設定和數位簽章。 郵件合併功能可以批量生成個人化 PDF 文件——非常適合創建數千封客製化信件、證書或合同,無需人工幹預。 正是這種整合能力,使得IronPdf受到全球企業的信賴,能夠滿足其文件自動化需求。

6. 將影像轉換為 PDF

將影像轉換為 PDF 對於建立相簿、掃描文件彙編或基於影像的報告至關重要。IronPdf支援所有主流影像格式,並提供控制佈局和品質的選項:

using IronPdf;
using IronPdf.Imaging; // Install-Package IronPdf
using System.IO;

var renderer = new ChromePdfRenderer();

// Convert single image to PDF
var imagePath = "product-photo.jpg";
var imageHtml = $@"
    <html>
    <body style='margin: 0; padding: 0;'>
        <img src='{imagePath}' style='width: 100%; height: auto;' />
    </body>
    </html>";

var imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath));
imagePdf.SaveAs("product-catalog-page.pdf");

// Create multi-page PDF from multiple images
var imageFiles = Directory.GetFiles("ProductImages", "*.jpg");
var catalogHtml = "<html><body style='margin: 0;'>";

foreach (var image in imageFiles)
{
    catalogHtml += $@"
        <div style='page-break-after: always;'>
            <img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
            <p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
        </div>";
}

catalogHtml += "</body></html>";

var catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages");
catalogPdf.SaveAs("product-catalog.pdf");
using IronPdf;
using IronPdf.Imaging; // Install-Package IronPdf
using System.IO;

var renderer = new ChromePdfRenderer();

// Convert single image to PDF
var imagePath = "product-photo.jpg";
var imageHtml = $@"
    <html>
    <body style='margin: 0; padding: 0;'>
        <img src='{imagePath}' style='width: 100%; height: auto;' />
    </body>
    </html>";

var imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath));
imagePdf.SaveAs("product-catalog-page.pdf");

// Create multi-page PDF from multiple images
var imageFiles = Directory.GetFiles("ProductImages", "*.jpg");
var catalogHtml = "<html><body style='margin: 0;'>";

foreach (var image in imageFiles)
{
    catalogHtml += $@"
        <div style='page-break-after: always;'>
            <img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
            <p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
        </div>";
}

catalogHtml += "</body></html>";

var catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages");
catalogPdf.SaveAs("product-catalog.pdf");
Imports IronPdf
Imports IronPdf.Imaging ' Install-Package IronPdf
Imports System.IO

Private renderer = New ChromePdfRenderer()

' Convert single image to PDF
Private imagePath = "product-photo.jpg"
Private imageHtml = $"
    <html>
    <body style='margin: 0; padding: 0;'>
        <img src='{imagePath}' style='width: 100%; height: auto;' />
    </body>
    </html>"

Private imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath))
imagePdf.SaveAs("product-catalog-page.pdf")

' Create multi-page PDF from multiple images
Dim imageFiles = Directory.GetFiles("ProductImages", "*.jpg")
Dim catalogHtml = "<html><body style='margin: 0;'>"

For Each image In imageFiles
	catalogHtml &= $"
        <div style='page-break-after: always;'>
            <img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
            <p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
        </div>"
Next image

catalogHtml &= "</body></html>"

Dim catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages")
catalogPdf.SaveAs("product-catalog.pdf")
$vbLabelText   $csharpLabel

7. 從 ASP.NET 頁面產生 PDF

對於 Web 應用程式而言,從現有視圖產生 PDF提供了一種無縫的方式來建立 Web 內容的可下載版本。 對於需要從其 Web 應用程式建立 PDF 的組織而言,這種整合功能至關重要——無論是客戶入口網站產生報表、管理儀表板產生報告,還是電子學習平台建立憑證。IronPdf可與所有 ASP.NET 技術搭配使用,包括 MVC、Razor Pages 和 Blazor,因此對於已投資 Microsoft 生態系統的組織而言,它是完美的選擇:

// Namespace: Microsoft.AspNetCore.Mvc
using Microsoft.AspNetCore.Mvc;
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;

// ASP.NET Core MVC Controller
public class ReportController : Controller
{
    private readonly ChromePdfRenderer _pdfRenderer;

    public ReportController()
    {
        _pdfRenderer = new ChromePdfRenderer();
    }

    public async Task<IActionResult> DownloadReport(int reportId)
    {
        // Get your report data
        var reportData = await GetReportData(reportId);

        // Render view to HTML string
        var html = await RenderViewToStringAsync("Reports/MonthlyReport", reportData);

        // Convert HTML content to PDF
        var pdf = _pdfRenderer.RenderHtmlAsPdf(html);

        // Return as file download
        return File(
            pdf.BinaryData, 
            "application/pdf", 
            $"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf"
        );
    }

    private async Task<string> RenderViewToStringAsync(string viewName, object model)
    {
        ViewData.Model = model;
        using var sw = new StringWriter();
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(
            ControllerContext, 
            viewResult.View, 
            ViewData, 
            TempData, 
            sw, 
            new HtmlHelperOptions()
        );
        viewResult.View.Render(viewContext, sw);
        return sw.GetStringBuilder().ToString();
    }
}
// Namespace: Microsoft.AspNetCore.Mvc
using Microsoft.AspNetCore.Mvc;
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;

// ASP.NET Core MVC Controller
public class ReportController : Controller
{
    private readonly ChromePdfRenderer _pdfRenderer;

    public ReportController()
    {
        _pdfRenderer = new ChromePdfRenderer();
    }

    public async Task<IActionResult> DownloadReport(int reportId)
    {
        // Get your report data
        var reportData = await GetReportData(reportId);

        // Render view to HTML string
        var html = await RenderViewToStringAsync("Reports/MonthlyReport", reportData);

        // Convert HTML content to PDF
        var pdf = _pdfRenderer.RenderHtmlAsPdf(html);

        // Return as file download
        return File(
            pdf.BinaryData, 
            "application/pdf", 
            $"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf"
        );
    }

    private async Task<string> RenderViewToStringAsync(string viewName, object model)
    {
        ViewData.Model = model;
        using var sw = new StringWriter();
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(
            ControllerContext, 
            viewResult.View, 
            ViewData, 
            TempData, 
            sw, 
            new HtmlHelperOptions()
        );
        viewResult.View.Render(viewContext, sw);
        return sw.GetStringBuilder().ToString();
    }
}
' Namespace: Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc
' Namespace: IronPdf
Imports IronPdf
' Namespace: System.Threading.Tasks
Imports System.Threading.Tasks
' Namespace: System.IO
Imports System.IO
' Namespace: System
Imports System

' ASP.NET Core MVC Controller
Public Class ReportController
	Inherits Controller

	Private ReadOnly _pdfRenderer As ChromePdfRenderer

	Public Sub New()
		_pdfRenderer = New ChromePdfRenderer()
	End Sub

	Public Async Function DownloadReport(ByVal reportId As Integer) As Task(Of IActionResult)
		' Get your report data
		Dim reportData = Await GetReportData(reportId)

		' Render view to HTML string
		Dim html = Await RenderViewToStringAsync("Reports/MonthlyReport", reportData)

		' Convert HTML content to PDF
		Dim pdf = _pdfRenderer.RenderHtmlAsPdf(html)

		' Return as file download
		Return File(pdf.BinaryData, "application/pdf", $"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf")
	End Function

	Private Async Function RenderViewToStringAsync(ByVal viewName As String, ByVal model As Object) As Task(Of String)
		ViewData.Model = model
		Dim sw = New StringWriter()
		Dim viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName)
		Dim viewContext As New ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw, New HtmlHelperOptions())
		viewResult.View.Render(viewContext, sw)
		Return sw.GetStringBuilder().ToString()
	End Function
End Class
$vbLabelText   $csharpLabel

如何讓我的PDF看起來更專業?

建立 PDF 是一回事,而讓它們看起來專業才是.NET 中產生 PDF時,真正讓你的應用程式脫穎而出的關鍵。 專業的 PDF 文件需要注重佈局、排版和品牌一致性等細節,才能留下良好的印象。IronPdf擁有全面的樣式選項和進階 PDF 功能,您可以使用這款強大的C# PDF 產生器來建立與您的企業形象完美匹配的文件。 HTML 轉換 PDF功能可確保您設計的文件在生成為 PDF 時保持其視覺吸引力。 讓我們來探索那些可以將普通 PDF 文件轉換為精美、專業的文件的功能,這些文件能夠給客戶和利害關係人留下深刻印象。

頁首、頁尾和頁碼

專業文件需要統一的頁首和頁腳,以提供上下文和導航資訊。IronPdf為頁首和頁尾提供基於文字的簡單選項和基於 HTML 的複雜選項。 正是這種靈活性,使得企業在需要大規模創建品牌 PDF 文件時選擇 IronPDF。 您可以新增動態內容,例如頁碼、日期和文件標題,從而確保產生的每個 PDF 文件都符合專業標準:

using IronPdf;
using System;

var renderer = new ChromePdfRenderer();

// Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
    Text = "Confidential Report - {date}",
    DrawDividerLine = true,
    Font = "Arial",
    FontSize = 12
};

renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
    Text = "Page {page} of {total-pages}",
    DrawDividerLine = true,
    Font = "Arial", 
    FontSize = 10,
    CenterText = true
};

// HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    Html = @"
        <div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
            <img src='logo.png' style='height: 40px;' />
            <div style='text-align: center;'>
                <h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
                <p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
            </div>
            <div style='text-align: right; font-size: 11px; color: #666;'>
                Generated: {date}<br/>
                Department: Finance
            </div>
        </div>",
    Height = 80,
    LoadStylesAndCSSFromMainHtmlDocument = true
};

// Create your PDF with professional headers/footers
var html = @"<h1>Financial Overview</h1><p>Report content here...</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("professional-report.pdf");
using IronPdf;
using System;

var renderer = new ChromePdfRenderer();

// Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
    Text = "Confidential Report - {date}",
    DrawDividerLine = true,
    Font = "Arial",
    FontSize = 12
};

renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
    Text = "Page {page} of {total-pages}",
    DrawDividerLine = true,
    Font = "Arial", 
    FontSize = 10,
    CenterText = true
};

// HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    Html = @"
        <div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
            <img src='logo.png' style='height: 40px;' />
            <div style='text-align: center;'>
                <h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
                <p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
            </div>
            <div style='text-align: right; font-size: 11px; color: #666;'>
                Generated: {date}<br/>
                Department: Finance
            </div>
        </div>",
    Height = 80,
    LoadStylesAndCSSFromMainHtmlDocument = true
};

// Create your PDF with professional headers/footers
var html = @"<h1>Financial Overview</h1><p>Report content here...</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("professional-report.pdf");
Imports IronPdf
Imports System

Private renderer = New ChromePdfRenderer()

' Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
	.Text = "Confidential Report - {date}",
	.DrawDividerLine = True,
	.Font = "Arial",
	.FontSize = 12
}

renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
	.Text = "Page {page} of {total-pages}",
	.DrawDividerLine = True,
	.Font = "Arial",
	.FontSize = 10,
	.CenterText = True
}

' HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
	.Html = "
        <div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
            <img src='logo.png' style='height: 40px;' />
            <div style='text-align: center;'>
                <h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
                <p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
            </div>
            <div style='text-align: right; font-size: 11px; color: #666;'>
                Generated: {date}<br/>
                Department: Finance
            </div>
        </div>",
	.Height = 80,
	.LoadStylesAndCSSFromMainHtmlDocument = True
}

' Create your PDF with professional headers/footers
Dim html = "<h1>Financial Overview</h1><p>Report content here...</p>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("professional-report.pdf")
$vbLabelText   $csharpLabel

這些頁首和頁尾選項使組織能夠在所有產生的 PDF中保持品牌一致性。 無論您是建立財務報告還是技術文檔,專業的頁首和頁尾都能確保您的文檔符合公司標準。

進階頁面設定和佈局控制

控制頁面佈局對於建立能夠正確列印並在所有裝置上看起來專業的文件至關重要。IronPdf提供豐富的頁面設定選項,包括自訂尺寸、方向和邊距:

var renderer = new ChromePdfRenderer();

// Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;

// Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;

// Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

// Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;

// Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297); // A4

// Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100; // 0-100 scale
var renderer = new ChromePdfRenderer();

// Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;

// Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;

// Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

// Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;

// Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297); // A4

// Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100; // 0-100 scale
Dim renderer = New ChromePdfRenderer()

' Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait

' Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20

' Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = True

' Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen

' Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297) ' A4

' Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100 ' 0-100 scale
$vbLabelText   $csharpLabel

字體和排版的使用

排版在文件的專業性中起著至關重要的作用。IronPdf支援網頁字體、自訂字體和進階排版功能:

var renderer = new ChromePdfRenderer();

// HTML with custom fonts and typography
var html = @"
    <html>
    <head>
        <link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
        <style>
            @font-face {
                font-family: 'CustomBrand';
                src: url('BrandFont.ttf') format('truetype');
            }

            body {
                font-family: 'Roboto', Arial, sans-serif;
                font-size: 11pt;
                line-height: 1.6;
                color: #333;
            }

            h1 {
                font-family: 'CustomBrand', Georgia, serif;
                font-size: 28pt;
                color: #0066cc;
                letter-spacing: -0.5px;
            }

            .quote {
                font-style: italic;
                font-size: 14pt;
                color: #666;
                border-left: 4px solid #0066cc;
                padding-left: 20px;
                margin: 20px 0;
            }
        </style>
    </head>
    <body>
        <h1>Professional Document</h1>
        <p>This document demonstrates professional typography.</p>
        <div class='quote'>
            "Excellence in typography enhances readability and professionalism."
        </div>
    </body>
    </html>";

var pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts");
pdf.SaveAs("typography-demo.pdf");
var renderer = new ChromePdfRenderer();

// HTML with custom fonts and typography
var html = @"
    <html>
    <head>
        <link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
        <style>
            @font-face {
                font-family: 'CustomBrand';
                src: url('BrandFont.ttf') format('truetype');
            }

            body {
                font-family: 'Roboto', Arial, sans-serif;
                font-size: 11pt;
                line-height: 1.6;
                color: #333;
            }

            h1 {
                font-family: 'CustomBrand', Georgia, serif;
                font-size: 28pt;
                color: #0066cc;
                letter-spacing: -0.5px;
            }

            .quote {
                font-style: italic;
                font-size: 14pt;
                color: #666;
                border-left: 4px solid #0066cc;
                padding-left: 20px;
                margin: 20px 0;
            }
        </style>
    </head>
    <body>
        <h1>Professional Document</h1>
        <p>This document demonstrates professional typography.</p>
        <div class='quote'>
            "Excellence in typography enhances readability and professionalism."
        </div>
    </body>
    </html>";

var pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts");
pdf.SaveAs("typography-demo.pdf");
Dim renderer = New ChromePdfRenderer()

' HTML with custom fonts and typography
Dim html = "
    <html>
    <head>
        <link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
        <style>
            @font-face {
                font-family: 'CustomBrand';
                src: url('BrandFont.ttf') format('truetype');
            }

            body {
                font-family: 'Roboto', Arial, sans-serif;
                font-size: 11pt;
                line-height: 1.6;
                color: #333;
            }

            h1 {
                font-family: 'CustomBrand', Georgia, serif;
                font-size: 28pt;
                color: #0066cc;
                letter-spacing: -0.5px;
            }

            .quote {
                font-style: italic;
                font-size: 14pt;
                color: #666;
                border-left: 4px solid #0066cc;
                padding-left: 20px;
                margin: 20px 0;
            }
        </style>
    </head>
    <body>
        <h1>Professional Document</h1>
        <p>This document demonstrates professional typography.</p>
        <div class='quote'>
            "Excellence in typography enhances readability [and] professionalism." </div> </body> </html>"

Dim pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts")
pdf.SaveAs("typography-demo.pdf")
$vbLabelText   $csharpLabel

實際案例:如何產生發票 PDF?

讓我們建立一個完整的、可用於生產環境的發票產生器,以展示在實際應用中建立 PDF 文件的最佳實踐。 這個例子展示了為什麼成千上萬的企業選擇IronPdf作為其C# PDF 生成器來滿足發票生成需求——它以強大且易於維護的方式結合了數據綁定專業樣式適當的文檔結構。 電子商務平台也採用類似的實作方式,每月產生數百萬份發票,證明了.NET 中程式化 PDF 產生的可擴充性。 您可以根據自己的PDF 建立任務修改此程式碼:

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

public class InvoiceGenerator
{
    private readonly ChromePdfRenderer _renderer;

    public InvoiceGenerator()
    {
        _renderer = new ChromePdfRenderer();
        ConfigureRenderer();
    }

    private void ConfigureRenderer()
    {
        // Professional page setup
        _renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
        _renderer.RenderingOptions.MarginTop = 25;
        _renderer.RenderingOptions.MarginBottom = 25;
        _renderer.RenderingOptions.MarginLeft = 25;
        _renderer.RenderingOptions.MarginRight = 25;
        _renderer.RenderingOptions.PrintHtmlBackgrounds = true;

        // Add footer with page numbers
        _renderer.RenderingOptions.TextFooter = new TextHeaderFooter
        {
            Text = "Page {page} of {total-pages} | Invoice generated on {date}",
            FontSize = 9,
            Font = "Arial",
            CenterText = true
        };
    }

    public void CreateInvoice(Invoice invoice)
    {
        var html = GenerateInvoiceHtml(invoice);
        var pdf = _renderer.RenderHtmlAsPdf(html);

        // Add metadata to the final document
        pdf.MetaData.Title = $"Invoice {invoice.Number}";
        pdf.MetaData.Author = "Your Company Name";
        pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}";
        pdf.MetaData.Keywords = "invoice, billing, payment";
        pdf.MetaData.CreationDate = DateTime.Now;

        // Save the PDF document
        var fileName = $"Invoice-{invoice.Number}.pdf";
        pdf.SaveAs(fileName);

        Console.WriteLine($"PDF generated successfully: {fileName}");
    }

    private string GenerateInvoiceHtml(Invoice invoice)
    {
        var itemsHtml = string.Join("", invoice.Items.Select(item => $@"
            <tr>
                <td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
            </tr>"));

        return $@"
            <html>
            <head>
                <style>
                    * {{ box-sizing: border-box; }}
                    body {{ 
                        font-family: 'Segoe UI', Arial, sans-serif; 
                        line-height: 1.6;
                        color: #333;
                        margin: 0;
                        padding: 0;
                    }}
                    .invoice-container {{
                        max-width: 800px;
                        margin: 0 auto;
                        padding: 40px;
                    }}
                    .invoice-header {{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 40px;
                        padding-bottom: 20px;
                        border-bottom: 3px solid #0066cc;
                    }}
                    .company-details {{
                        flex: 1;
                    }}
                    .company-details h1 {{
                        color: #0066cc;
                        margin: 0 0 10px 0;
                        font-size: 28px;
                    }}
                    .invoice-details {{
                        flex: 1;
                        text-align: right;
                    }}
                    .invoice-details h2 {{
                        margin: 0 0 10px 0;
                        color: #666;
                        font-size: 24px;
                    }}
                    .invoice-number {{
                        font-size: 18px;
                        color: #0066cc;
                        font-weight: bold;
                    }}
                    .billing-section {{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 40px;
                    }}
                    .billing-box {{
                        flex: 1;
                        padding: 20px;
                        background: #f8f9fa;
                        border-radius: 8px;
                        margin-right: 20px;
                    }}
                    .billing-box:last-child {{
                        margin-right: 0;
                    }}
                    .billing-box h3 {{
                        margin: 0 0 15px 0;
                        color: #0066cc;
                        font-size: 16px;
                        text-transform: uppercase;
                        letter-spacing: 1px;
                    }}
                    .items-table {{
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 40px;
                    }}
                    .items-table th {{
                        background: #0066cc;
                        color: white;
                        padding: 12px;
                        text-align: left;
                        font-weight: 600;
                    }}
                    .items-table th:last-child {{
                        text-align: right;
                    }}
                    .totals-section {{
                        display: flex;
                        justify-content: flex-end;
                        margin-bottom: 40px;
                    }}
                    .totals-box {{
                        width: 300px;
                    }}
                    .total-row {{
                        display: flex;
                        justify-content: space-between;
                        padding: 8px 0;
                        border-bottom: 1px solid #eee;
                    }}
                    .total-row.final {{
                        border-bottom: none;
                        border-top: 2px solid #0066cc;
                        margin-top: 10px;
                        padding-top: 15px;
                        font-size: 20px;
                        font-weight: bold;
                        color: #0066cc;
                    }}
                    .payment-terms {{
                        background: #f8f9fa;
                        padding: 20px;
                        border-radius: 8px;
                        margin-bottom: 30px;
                    }}
                    .payment-terms h3 {{
                        margin: 0 0 10px 0;
                        color: #0066cc;
                    }}
                    .footer-note {{
                        text-align: center;
                        color: #666;
                        font-size: 14px;
                        margin-top: 40px;
                        padding-top: 20px;
                        border-top: 1px solid #eee;
                    }}
                </style>
            </head>
            <body>
                <div class='invoice-container'>
                    <div class='invoice-header'>
                        <div class='company-details'>
                            <h1>{invoice.CompanyName}</h1>
                            <p>{invoice.CompanyAddress}<br>
                            {invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
                            Phone: {invoice.CompanyPhone}<br>
                            Email: {invoice.CompanyEmail}</p>
                        </div>
                        <div class='invoice-details'>
                            <h2>INVOICE</h2>
                            <p class='invoice-number'>#{invoice.Number}</p>
                            <p><strong>Date:</strong> {invoice.Date:MMMM dd, yyyy}<br>
                            <strong>Due Date:</strong> {invoice.DueDate:MMMM dd, yyyy}</p>
                        </div>
                    </div>

                    <div class='billing-section'>
                        <div class='billing-box'>
                            <h3>Bill To</h3>
                            <p><strong>{invoice.CustomerName}</strong><br>
                            {invoice.CustomerAddress}<br>
                            {invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
                            {invoice.CustomerEmail}</p>
                        </div>
                        <div class='billing-box'>
                            <h3>Payment Information</h3>
                            <p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
                            <strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
                            <strong>Amount Due:</strong> ${invoice.Total:F2}</p>
                        </div>
                    </div>

                    <table class='items-table'>
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th style='text-align: center;'>Quantity</th>
                                <th style='text-align: right;'>Unit Price</th>
                                <th style='text-align: right;'>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            {itemsHtml}
                        </tbody>
                    </table>

                    <div class='totals-section'>
                        <div class='totals-box'>
                            <div class='total-row'>
                                <span>Subtotal:</span>
                                <span>${invoice.Subtotal:F2}</span>
                            </div>
                            <div class='total-row'>
                                <span>Tax ({invoice.TaxRate:F0}%):</span>
                                <span>${invoice.Tax:F2}</span>
                            </div>
                            <div class='total-row final'>
                                <span>Total Due:</span>
                                <span>${invoice.Total:F2}</span>
                            </div>
                        </div>
                    </div>

                    <div class='payment-terms'>
                        <h3>Payment Terms & Conditions</h3>
                        <p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge. 
                        Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
                    </div>

                    <div class='footer-note'>
                        <p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
                        <p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
                    </div>
                </div>
            </body>
            </html>";
    }
}

// Invoice model classes
public class Invoice
{
    public string Number { get; set; }
    public DateTime Date { get; set; }
    public DateTime DueDate { get; set; }
    public string CompanyName { get; set; }
    public string CompanyAddress { get; set; }
    public string CompanyCity { get; set; }
    public string CompanyState { get; set; }
    public string CompanyZip { get; set; }
    public string CompanyPhone { get; set; }
    public string CompanyEmail { get; set; }
    public string CompanyWebsite { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public string CustomerCity { get; set; }
    public string CustomerState { get; set; }
    public string CustomerZip { get; set; }
    public string CustomerEmail { get; set; }
    public string PaymentTerms { get; set; }
    public List<InvoiceItem> Items { get; set; }
    public decimal Subtotal => Items.Sum(i => i.Total);
    public decimal TaxRate { get; set; }
    public decimal Tax => Subtotal * (TaxRate / 100);
    public decimal Total => Subtotal + Tax;
}

public class InvoiceItem
{
    public string Description { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal Total => Quantity * UnitPrice;
}

// Usage example
var generator = new InvoiceGenerator();
var invoice = new Invoice
{
    Number = "INV-2024-001",
    Date = DateTime.Now,
    DueDate = DateTime.Now.AddDays(30),
    CompanyName = "Your Company Name",
    CompanyAddress = "123 Business Street",
    CompanyCity = "New York",
    CompanyState = "NY",
    CompanyZip = "10001",
    CompanyPhone = "(555) 123-4567",
    CompanyEmail = "billing@yourcompany.com",
    CompanyWebsite = "www.yourcompany.com",
    CustomerName = "Acme Corporation",
    CustomerAddress = "456 Client Avenue",
    CustomerCity = "Los Angeles",
    CustomerState = "CA",
    CustomerZip = "90001",
    CustomerEmail = "accounts@acmecorp.com",
    PaymentTerms = "Net 30",
    TaxRate = 8.5m,
    Items = new List<InvoiceItem>
    {
        new() { Description = "Professional Services - March 2024", Quantity = 40, UnitPrice = 125.00m },
        new() { Description = "Software License (Annual)", Quantity = 1, UnitPrice = 2400.00m },
        new() { Description = "Technical Support", Quantity = 10, UnitPrice = 150.00m }
    }
};

generator.CreateInvoice(invoice);
using IronPdf;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

public class InvoiceGenerator
{
    private readonly ChromePdfRenderer _renderer;

    public InvoiceGenerator()
    {
        _renderer = new ChromePdfRenderer();
        ConfigureRenderer();
    }

    private void ConfigureRenderer()
    {
        // Professional page setup
        _renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
        _renderer.RenderingOptions.MarginTop = 25;
        _renderer.RenderingOptions.MarginBottom = 25;
        _renderer.RenderingOptions.MarginLeft = 25;
        _renderer.RenderingOptions.MarginRight = 25;
        _renderer.RenderingOptions.PrintHtmlBackgrounds = true;

        // Add footer with page numbers
        _renderer.RenderingOptions.TextFooter = new TextHeaderFooter
        {
            Text = "Page {page} of {total-pages} | Invoice generated on {date}",
            FontSize = 9,
            Font = "Arial",
            CenterText = true
        };
    }

    public void CreateInvoice(Invoice invoice)
    {
        var html = GenerateInvoiceHtml(invoice);
        var pdf = _renderer.RenderHtmlAsPdf(html);

        // Add metadata to the final document
        pdf.MetaData.Title = $"Invoice {invoice.Number}";
        pdf.MetaData.Author = "Your Company Name";
        pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}";
        pdf.MetaData.Keywords = "invoice, billing, payment";
        pdf.MetaData.CreationDate = DateTime.Now;

        // Save the PDF document
        var fileName = $"Invoice-{invoice.Number}.pdf";
        pdf.SaveAs(fileName);

        Console.WriteLine($"PDF generated successfully: {fileName}");
    }

    private string GenerateInvoiceHtml(Invoice invoice)
    {
        var itemsHtml = string.Join("", invoice.Items.Select(item => $@"
            <tr>
                <td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
            </tr>"));

        return $@"
            <html>
            <head>
                <style>
                    * {{ box-sizing: border-box; }}
                    body {{ 
                        font-family: 'Segoe UI', Arial, sans-serif; 
                        line-height: 1.6;
                        color: #333;
                        margin: 0;
                        padding: 0;
                    }}
                    .invoice-container {{
                        max-width: 800px;
                        margin: 0 auto;
                        padding: 40px;
                    }}
                    .invoice-header {{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 40px;
                        padding-bottom: 20px;
                        border-bottom: 3px solid #0066cc;
                    }}
                    .company-details {{
                        flex: 1;
                    }}
                    .company-details h1 {{
                        color: #0066cc;
                        margin: 0 0 10px 0;
                        font-size: 28px;
                    }}
                    .invoice-details {{
                        flex: 1;
                        text-align: right;
                    }}
                    .invoice-details h2 {{
                        margin: 0 0 10px 0;
                        color: #666;
                        font-size: 24px;
                    }}
                    .invoice-number {{
                        font-size: 18px;
                        color: #0066cc;
                        font-weight: bold;
                    }}
                    .billing-section {{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 40px;
                    }}
                    .billing-box {{
                        flex: 1;
                        padding: 20px;
                        background: #f8f9fa;
                        border-radius: 8px;
                        margin-right: 20px;
                    }}
                    .billing-box:last-child {{
                        margin-right: 0;
                    }}
                    .billing-box h3 {{
                        margin: 0 0 15px 0;
                        color: #0066cc;
                        font-size: 16px;
                        text-transform: uppercase;
                        letter-spacing: 1px;
                    }}
                    .items-table {{
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 40px;
                    }}
                    .items-table th {{
                        background: #0066cc;
                        color: white;
                        padding: 12px;
                        text-align: left;
                        font-weight: 600;
                    }}
                    .items-table th:last-child {{
                        text-align: right;
                    }}
                    .totals-section {{
                        display: flex;
                        justify-content: flex-end;
                        margin-bottom: 40px;
                    }}
                    .totals-box {{
                        width: 300px;
                    }}
                    .total-row {{
                        display: flex;
                        justify-content: space-between;
                        padding: 8px 0;
                        border-bottom: 1px solid #eee;
                    }}
                    .total-row.final {{
                        border-bottom: none;
                        border-top: 2px solid #0066cc;
                        margin-top: 10px;
                        padding-top: 15px;
                        font-size: 20px;
                        font-weight: bold;
                        color: #0066cc;
                    }}
                    .payment-terms {{
                        background: #f8f9fa;
                        padding: 20px;
                        border-radius: 8px;
                        margin-bottom: 30px;
                    }}
                    .payment-terms h3 {{
                        margin: 0 0 10px 0;
                        color: #0066cc;
                    }}
                    .footer-note {{
                        text-align: center;
                        color: #666;
                        font-size: 14px;
                        margin-top: 40px;
                        padding-top: 20px;
                        border-top: 1px solid #eee;
                    }}
                </style>
            </head>
            <body>
                <div class='invoice-container'>
                    <div class='invoice-header'>
                        <div class='company-details'>
                            <h1>{invoice.CompanyName}</h1>
                            <p>{invoice.CompanyAddress}<br>
                            {invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
                            Phone: {invoice.CompanyPhone}<br>
                            Email: {invoice.CompanyEmail}</p>
                        </div>
                        <div class='invoice-details'>
                            <h2>INVOICE</h2>
                            <p class='invoice-number'>#{invoice.Number}</p>
                            <p><strong>Date:</strong> {invoice.Date:MMMM dd, yyyy}<br>
                            <strong>Due Date:</strong> {invoice.DueDate:MMMM dd, yyyy}</p>
                        </div>
                    </div>

                    <div class='billing-section'>
                        <div class='billing-box'>
                            <h3>Bill To</h3>
                            <p><strong>{invoice.CustomerName}</strong><br>
                            {invoice.CustomerAddress}<br>
                            {invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
                            {invoice.CustomerEmail}</p>
                        </div>
                        <div class='billing-box'>
                            <h3>Payment Information</h3>
                            <p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
                            <strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
                            <strong>Amount Due:</strong> ${invoice.Total:F2}</p>
                        </div>
                    </div>

                    <table class='items-table'>
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th style='text-align: center;'>Quantity</th>
                                <th style='text-align: right;'>Unit Price</th>
                                <th style='text-align: right;'>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            {itemsHtml}
                        </tbody>
                    </table>

                    <div class='totals-section'>
                        <div class='totals-box'>
                            <div class='total-row'>
                                <span>Subtotal:</span>
                                <span>${invoice.Subtotal:F2}</span>
                            </div>
                            <div class='total-row'>
                                <span>Tax ({invoice.TaxRate:F0}%):</span>
                                <span>${invoice.Tax:F2}</span>
                            </div>
                            <div class='total-row final'>
                                <span>Total Due:</span>
                                <span>${invoice.Total:F2}</span>
                            </div>
                        </div>
                    </div>

                    <div class='payment-terms'>
                        <h3>Payment Terms & Conditions</h3>
                        <p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge. 
                        Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
                    </div>

                    <div class='footer-note'>
                        <p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
                        <p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
                    </div>
                </div>
            </body>
            </html>";
    }
}

// Invoice model classes
public class Invoice
{
    public string Number { get; set; }
    public DateTime Date { get; set; }
    public DateTime DueDate { get; set; }
    public string CompanyName { get; set; }
    public string CompanyAddress { get; set; }
    public string CompanyCity { get; set; }
    public string CompanyState { get; set; }
    public string CompanyZip { get; set; }
    public string CompanyPhone { get; set; }
    public string CompanyEmail { get; set; }
    public string CompanyWebsite { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public string CustomerCity { get; set; }
    public string CustomerState { get; set; }
    public string CustomerZip { get; set; }
    public string CustomerEmail { get; set; }
    public string PaymentTerms { get; set; }
    public List<InvoiceItem> Items { get; set; }
    public decimal Subtotal => Items.Sum(i => i.Total);
    public decimal TaxRate { get; set; }
    public decimal Tax => Subtotal * (TaxRate / 100);
    public decimal Total => Subtotal + Tax;
}

public class InvoiceItem
{
    public string Description { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal Total => Quantity * UnitPrice;
}

// Usage example
var generator = new InvoiceGenerator();
var invoice = new Invoice
{
    Number = "INV-2024-001",
    Date = DateTime.Now,
    DueDate = DateTime.Now.AddDays(30),
    CompanyName = "Your Company Name",
    CompanyAddress = "123 Business Street",
    CompanyCity = "New York",
    CompanyState = "NY",
    CompanyZip = "10001",
    CompanyPhone = "(555) 123-4567",
    CompanyEmail = "billing@yourcompany.com",
    CompanyWebsite = "www.yourcompany.com",
    CustomerName = "Acme Corporation",
    CustomerAddress = "456 Client Avenue",
    CustomerCity = "Los Angeles",
    CustomerState = "CA",
    CustomerZip = "90001",
    CustomerEmail = "accounts@acmecorp.com",
    PaymentTerms = "Net 30",
    TaxRate = 8.5m,
    Items = new List<InvoiceItem>
    {
        new() { Description = "Professional Services - March 2024", Quantity = 40, UnitPrice = 125.00m },
        new() { Description = "Software License (Annual)", Quantity = 1, UnitPrice = 2400.00m },
        new() { Description = "Technical Support", Quantity = 10, UnitPrice = 150.00m }
    }
};

generator.CreateInvoice(invoice);
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Linq

Public Class InvoiceGenerator
	Private ReadOnly _renderer As ChromePdfRenderer

	Public Sub New()
		_renderer = New ChromePdfRenderer()
		ConfigureRenderer()
	End Sub

	Private Sub ConfigureRenderer()
		' Professional page setup
		_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
		_renderer.RenderingOptions.MarginTop = 25
		_renderer.RenderingOptions.MarginBottom = 25
		_renderer.RenderingOptions.MarginLeft = 25
		_renderer.RenderingOptions.MarginRight = 25
		_renderer.RenderingOptions.PrintHtmlBackgrounds = True

		' Add footer with page numbers
		_renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
			.Text = "Page {page} of {total-pages} | Invoice generated on {date}",
			.FontSize = 9,
			.Font = "Arial",
			.CenterText = True
		}
	End Sub

	Public Sub CreateInvoice(ByVal invoice As Invoice)
		Dim html = GenerateInvoiceHtml(invoice)
		Dim pdf = _renderer.RenderHtmlAsPdf(html)

		' Add metadata to the final document
		pdf.MetaData.Title = $"Invoice {invoice.Number}"
		pdf.MetaData.Author = "Your Company Name"
		pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}"
		pdf.MetaData.Keywords = "invoice, billing, payment"
		pdf.MetaData.CreationDate = DateTime.Now

		' Save the PDF document
		Dim fileName = $"Invoice-{invoice.Number}.pdf"
		pdf.SaveAs(fileName)

		Console.WriteLine($"PDF generated successfully: {fileName}")
	End Sub

	Private Function GenerateInvoiceHtml(ByVal invoice As Invoice) As String
		Dim itemsHtml = String.Join("", invoice.Items.Select(Function(item) $"
            <tr>
                <td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
                <td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
            </tr>"))

		Return $"
            <html>
            <head>
                <style>
                    * {{ box-sizing: border-box; }}
                    body {{ 
                        font-family: 'Segoe UI', Arial, sans-serif; 
                        line-height: 1.6;
                        color: #333;
                        margin: 0;
                        padding: 0;
                    }}
                    .invoice-container {{
                        max-width: 800px;
                        margin: 0 auto;
                        padding: 40px;
                    }}
                    .invoice-header {{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 40px;
                        padding-bottom: 20px;
                        border-bottom: 3px solid #0066cc;
                    }}
                    .company-details {{
                        flex: 1;
                    }}
                    .company-details h1 {{
                        color: #0066cc;
                        margin: 0 0 10px 0;
                        font-size: 28px;
                    }}
                    .invoice-details {{
                        flex: 1;
                        text-align: right;
                    }}
                    .invoice-details h2 {{
                        margin: 0 0 10px 0;
                        color: #666;
                        font-size: 24px;
                    }}
                    .invoice-number {{
                        font-size: 18px;
                        color: #0066cc;
                        font-weight: bold;
                    }}
                    .billing-section {{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 40px;
                    }}
                    .billing-box {{
                        flex: 1;
                        padding: 20px;
                        background: #f8f9fa;
                        border-radius: 8px;
                        margin-right: 20px;
                    }}
                    .billing-box:last-child {{
                        margin-right: 0;
                    }}
                    .billing-box h3 {{
                        margin: 0 0 15px 0;
                        color: #0066cc;
                        font-size: 16px;
                        text-transform: uppercase;
                        letter-spacing: 1px;
                    }}
                    .items-table {{
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 40px;
                    }}
                    .items-table th {{
                        background: #0066cc;
                        color: white;
                        padding: 12px;
                        text-align: left;
                        font-weight: 600;
                    }}
                    .items-table th:last-child {{
                        text-align: right;
                    }}
                    .totals-section {{
                        display: flex;
                        justify-content: flex-end;
                        margin-bottom: 40px;
                    }}
                    .totals-box {{
                        width: 300px;
                    }}
                    .total-row {{
                        display: flex;
                        justify-content: space-between;
                        padding: 8px 0;
                        border-bottom: 1px solid #eee;
                    }}
                    .total-row.final {{
                        border-bottom: none;
                        border-top: 2px solid #0066cc;
                        margin-top: 10px;
                        padding-top: 15px;
                        font-size: 20px;
                        font-weight: bold;
                        color: #0066cc;
                    }}
                    .payment-terms {{
                        background: #f8f9fa;
                        padding: 20px;
                        border-radius: 8px;
                        margin-bottom: 30px;
                    }}
                    .payment-terms h3 {{
                        margin: 0 0 10px 0;
                        color: #0066cc;
                    }}
                    .footer-note {{
                        text-align: center;
                        color: #666;
                        font-size: 14px;
                        margin-top: 40px;
                        padding-top: 20px;
                        border-top: 1px solid #eee;
                    }}
                </style>
            </head>
            <body>
                <div class='invoice-container'>
                    <div class='invoice-header'>
                        <div class='company-details'>
                            <h1>{invoice.CompanyName}</h1>
                            <p>{invoice.CompanyAddress}<br>
                            {invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
                            Phone: {invoice.CompanyPhone}<br>
                            Email: {invoice.CompanyEmail}</p>
                        </div>
                        <div class='invoice-details'>
                            <h2>INVOICE</h2>
                            <p class='invoice-number'>#{invoice.Number}</p>
                            <p><strong>Date:</strong> {invoice.Date:=MMMM dd, yyyy}<br>
                            <strong>Due Date:</strong> {invoice.DueDate:=MMMM dd, yyyy}</p>
                        </div>
                    </div>

                    <div class='billing-section'>
                        <div class='billing-box'>
                            <h3>Bill To</h3>
                            <p><strong>{invoice.CustomerName}</strong><br>
                            {invoice.CustomerAddress}<br>
                            {invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
                            {invoice.CustomerEmail}</p>
                        </div>
                        <div class='billing-box'>
                            <h3>Payment Information</h3>
                            <p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
                            <strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
                            <strong>Amount Due:</strong> ${invoice.Total:F2}</p>
                        </div>
                    </div>

                    <table class='items-table'>
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th style='text-align: center;'>Quantity</th>
                                <th style='text-align: right;'>Unit Price</th>
                                <th style='text-align: right;'>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            {itemsHtml}
                        </tbody>
                    </table>

                    <div class='totals-section'>
                        <div class='totals-box'>
                            <div class='total-row'>
                                <span>Subtotal:</span>
                                <span>${invoice.Subtotal:F2}</span>
                            </div>
                            <div class='total-row'>
                                <span>Tax ({invoice.TaxRate:F0}%):</span>
                                <span>${invoice.Tax:F2}</span>
                            </div>
                            <div class='total-row final'>
                                <span>Total Due:</span>
                                <span>${invoice.Total:F2}</span>
                            </div>
                        </div>
                    </div>

                    <div class='payment-terms'>
                        <h3>Payment Terms & Conditions</h3>
                        <p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge. 
                        Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
                    </div>

                    <div class='footer-note'>
                        <p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
                        <p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
                    </div>
                </div>
            </body>
            </html>"
	End Function
End Class

' Invoice model classes
Public Class Invoice
	Public Property Number() As String
	Public Property [Date]() As DateTime
	Public Property DueDate() As DateTime
	Public Property CompanyName() As String
	Public Property CompanyAddress() As String
	Public Property CompanyCity() As String
	Public Property CompanyState() As String
	Public Property CompanyZip() As String
	Public Property CompanyPhone() As String
	Public Property CompanyEmail() As String
	Public Property CompanyWebsite() As String
	Public Property CustomerName() As String
	Public Property CustomerAddress() As String
	Public Property CustomerCity() As String
	Public Property CustomerState() As String
	Public Property CustomerZip() As String
	Public Property CustomerEmail() As String
	Public Property PaymentTerms() As String
	Public Property Items() As List(Of InvoiceItem)
	Public ReadOnly Property Subtotal() As Decimal
		Get
			Return Items.Sum(Function(i) i.Total)
		End Get
	End Property
	Public Property TaxRate() As Decimal
	Public ReadOnly Property Tax() As Decimal
		Get
			Return Subtotal * (TaxRate / 100)
		End Get
	End Property
	Public ReadOnly Property Total() As Decimal
		Get
			Return Subtotal + Tax
		End Get
	End Property
End Class

Public Class InvoiceItem
	Public Property Description() As String
	Public Property Quantity() As Integer
	Public Property UnitPrice() As Decimal
	Public ReadOnly Property Total() As Decimal
		Get
			Return Quantity * UnitPrice
		End Get
	End Property
End Class

' Usage example
Private generator = New InvoiceGenerator()
Private invoice = New Invoice With {
	.Number = "INV-2024-001",
	.Date = DateTime.Now,
	.DueDate = DateTime.Now.AddDays(30),
	.CompanyName = "Your Company Name",
	.CompanyAddress = "123 Business Street",
	.CompanyCity = "New York",
	.CompanyState = "NY",
	.CompanyZip = "10001",
	.CompanyPhone = "(555) 123-4567",
	.CompanyEmail = "billing@yourcompany.com",
	.CompanyWebsite = "www.yourcompany.com",
	.CustomerName = "Acme Corporation",
	.CustomerAddress = "456 Client Avenue",
	.CustomerCity = "Los Angeles",
	.CustomerState = "CA",
	.CustomerZip = "90001",
	.CustomerEmail = "accounts@acmecorp.com",
	.PaymentTerms = "Net 30",
	.TaxRate = 8.5D,
	.Items = New List(Of InvoiceItem) From {
		New() {
			Description = "Professional Services - March 2024",
			Quantity = 40,
			UnitPrice = 125.00D
		},
		New() {
			Description = "Software License (Annual)",
			Quantity = 1,
			UnitPrice = 2400.00D
		},
		New() {
			Description = "Technical Support",
			Quantity = 10,
			UnitPrice = 150.00D
		}
	}
}

generator.CreateInvoice(invoice)
$vbLabelText   $csharpLabel

IronPdf提供哪些進階 PDF 功能?

IronPDF 不僅限於使用 C# 建立基本的 PDF,還提供複雜的功能,從而實現複雜的文件工作流程和企業級功能。 這些高級功能可讓您在 .NET 中建立 PDF時建立互動式表單、保護敏感文件並精確地操作現有 PDF。 正是這些特性讓全球超過 1,400 萬名開發人員信賴 IronPDF,滿足他們關鍵任務型PDF 產生需求。 了解這些特性有助於您建立全面的 PDF 解決方案,以滿足最嚴苛的要求—從建立可填寫的表單到在C# PDF 建立專案中實現企業級安全性。

產生互動式 PDF 表單

透過程式設計方式建立可填寫的 PDF 表單,為自動化資料收集和文件工作流程開闢了可能性。IronPdf可以將 HTML 表單轉換為互動式 PDF 表單,使用者可以在任何 PDF 閱讀器中填寫:

// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;

var renderer = new ChromePdfRenderer();

// Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

// Create an interactive form with various input types
var formHtml = @"
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; padding: 40px; }
            .form-group { margin-bottom: 20px; }
            label { display: block; margin-bottom: 5px; font-weight: bold; }
            input[type='text'], input[type='email'], select, textarea {
                width: 100%;
                padding: 8px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 14px;
            }
            .checkbox-group { margin: 10px 0; }
            .submit-section { 
                margin-top: 30px; 
                padding-top: 20px; 
                border-top: 2px solid #0066cc; 
            }
        </style>
    </head>
    <body>
        <h1>Application Form</h1>
        <form>
            <div class='form-group'>
                <label for='fullName'>Full Name:</label>
                <input type='text' id='fullName' name='fullName' required />
            </div>

            <div class='form-group'>
                <label for='email'>Email Address:</label>
                <input type='email' id='email' name='email' required />
            </div>

            <div class='form-group'>
                <label for='department'>Department:</label>
                <select id='department' name='department'>
                    <option value=''>Select Department</option>
                    <option value='sales'>Sales</option>
                    <option value='marketing'>Marketing</option>
                    <option value='engineering'>Engineering</option>
                    <option value='hr'>Human Resources</option>
                </select>
            </div>

            <div class='form-group'>
                <label>Interests:</label>
                <div class='checkbox-group'>
                    <label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
                    <label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
                    <label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
                </div>
            </div>

            <div class='form-group'>
                <label for='comments'>Additional Comments:</label>
                <textarea id='comments' name='comments' rows='4'></textarea>
            </div>

            <div class='submit-section'>
                <p><em>Please save this form and email to hr@company.com</em></p>
            </div>
        </form>
    </body>
    </html>";

// Create the PDF with form fields
var formPdf = renderer.RenderHtmlAsPdf(formHtml);

// Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith";
formPdf.Form.FindFormField("email").Value = "john.smith@example.com";
formPdf.Form.FindFormField("department").Value = "engineering";

// Save the interactive form
formPdf.SaveAs("application-form.pdf");

// You can also read and process submitted forms
var submittedPdf = PdfDocument.FromFile("submitted-form.pdf");
var name = submittedPdf.Form.FindFormField("fullName").Value;
var email = submittedPdf.Form.FindFormField("email").Value;
Console.WriteLine($"Form submitted by: {name} ({email})");
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;

var renderer = new ChromePdfRenderer();

// Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

// Create an interactive form with various input types
var formHtml = @"
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; padding: 40px; }
            .form-group { margin-bottom: 20px; }
            label { display: block; margin-bottom: 5px; font-weight: bold; }
            input[type='text'], input[type='email'], select, textarea {
                width: 100%;
                padding: 8px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 14px;
            }
            .checkbox-group { margin: 10px 0; }
            .submit-section { 
                margin-top: 30px; 
                padding-top: 20px; 
                border-top: 2px solid #0066cc; 
            }
        </style>
    </head>
    <body>
        <h1>Application Form</h1>
        <form>
            <div class='form-group'>
                <label for='fullName'>Full Name:</label>
                <input type='text' id='fullName' name='fullName' required />
            </div>

            <div class='form-group'>
                <label for='email'>Email Address:</label>
                <input type='email' id='email' name='email' required />
            </div>

            <div class='form-group'>
                <label for='department'>Department:</label>
                <select id='department' name='department'>
                    <option value=''>Select Department</option>
                    <option value='sales'>Sales</option>
                    <option value='marketing'>Marketing</option>
                    <option value='engineering'>Engineering</option>
                    <option value='hr'>Human Resources</option>
                </select>
            </div>

            <div class='form-group'>
                <label>Interests:</label>
                <div class='checkbox-group'>
                    <label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
                    <label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
                    <label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
                </div>
            </div>

            <div class='form-group'>
                <label for='comments'>Additional Comments:</label>
                <textarea id='comments' name='comments' rows='4'></textarea>
            </div>

            <div class='submit-section'>
                <p><em>Please save this form and email to hr@company.com</em></p>
            </div>
        </form>
    </body>
    </html>";

// Create the PDF with form fields
var formPdf = renderer.RenderHtmlAsPdf(formHtml);

// Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith";
formPdf.Form.FindFormField("email").Value = "john.smith@example.com";
formPdf.Form.FindFormField("department").Value = "engineering";

// Save the interactive form
formPdf.SaveAs("application-form.pdf");

// You can also read and process submitted forms
var submittedPdf = PdfDocument.FromFile("submitted-form.pdf");
var name = submittedPdf.Form.FindFormField("fullName").Value;
var email = submittedPdf.Form.FindFormField("email").Value;
Console.WriteLine($"Form submitted by: {name} ({email})");
' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System

Private renderer = New ChromePdfRenderer()

' Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = True

' Create an interactive form with various input types
Dim formHtml = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; padding: 40px; }
            .form-group { margin-bottom: 20px; }
            label { display: block; margin-bottom: 5px; font-weight: bold; }
            input[type='text'], input[type='email'], select, textarea {
                width: 100%;
                padding: 8px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 14px;
            }
            .checkbox-group { margin: 10px 0; }
            .submit-section { 
                margin-top: 30px; 
                padding-top: 20px; 
                border-top: 2px solid #0066cc; 
            }
        </style>
    </head>
    <body>
        <h1>Application Form</h1>
        <form>
            <div class='form-group'>
                <label for='fullName'>Full Name:</label>
                <input type='text' id='fullName' name='fullName' required />
            </div>

            <div class='form-group'>
                <label for='email'>Email Address:</label>
                <input type='email' id='email' name='email' required />
            </div>

            <div class='form-group'>
                <label for='department'>Department:</label>
                <select id='department' name='department'>
                    <option value=''>Select Department</option>
                    <option value='sales'>Sales</option>
                    <option value='marketing'>Marketing</option>
                    <option value='engineering'>Engineering</option>
                    <option value='hr'>Human Resources</option>
                </select>
            </div>

            <div class='form-group'>
                <label>Interests:</label>
                <div class='checkbox-group'>
                    <label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
                    <label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
                    <label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
                </div>
            </div>

            <div class='form-group'>
                <label for='comments'>Additional Comments:</label>
                <textarea id='comments' name='comments' rows='4'></textarea>
            </div>

            <div class='submit-section'>
                <p><em>Please save this form and email to hr@company.com</em></p>
            </div>
        </form>
    </body>
    </html>"

' Create the PDF with form fields
Dim formPdf = renderer.RenderHtmlAsPdf(formHtml)

' Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith"
formPdf.Form.FindFormField("email").Value = "john.smith@example.com"
formPdf.Form.FindFormField("department").Value = "engineering"

' Save the interactive form
formPdf.SaveAs("application-form.pdf")

' You can also read and process submitted forms
Dim submittedPdf = PdfDocument.FromFile("submitted-form.pdf")
Dim name = submittedPdf.Form.FindFormField("fullName").Value
Dim email = submittedPdf.Form.FindFormField("email").Value
Console.WriteLine($"Form submitted by: {name} ({email})")
$vbLabelText   $csharpLabel

保護您產生的PDF文件

處理敏感文件時,安全至關重要。IronPdf提供全面的安全功能,保護您的 PDF 檔案免於未經授權的存取或修改:

// Namespace: IronPdf
using IronPdf;
// Namespace: IronPdf.Editing
using IronPdf.Editing;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>");

// Apply password protection
pdf.SecuritySettings.UserPassword = "user123";      // Required to open
pdf.SecuritySettings.OwnerPassword = "owner456";    // Required to modify

// Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserFormData = true;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;

// Add digital signature for authenticity
pdf.SignWithFile(
    certificatePath: "certificate.pfx",
    certificatePassword: "certpass123",
    signingReason: "Document Approval",
    signingLocation: "New York, NY",
    signatureImage: new Signature("signature.png")
    {
        Width = 150,
        Height = 50
    }
);

// Apply redaction to hide sensitive information
pdf.RedactTextOnPage(
    pageIndex: 0,
    searchText: "SSN: ***-**-****",
    replacementText: "[REDACTED]",
    caseSensitive: false
);

// Save the secured PDF
pdf.SaveAs("secure-confidential.pdf");
// Namespace: IronPdf
using IronPdf;
// Namespace: IronPdf.Editing
using IronPdf.Editing;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>");

// Apply password protection
pdf.SecuritySettings.UserPassword = "user123";      // Required to open
pdf.SecuritySettings.OwnerPassword = "owner456";    // Required to modify

// Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserFormData = true;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;

// Add digital signature for authenticity
pdf.SignWithFile(
    certificatePath: "certificate.pfx",
    certificatePassword: "certpass123",
    signingReason: "Document Approval",
    signingLocation: "New York, NY",
    signatureImage: new Signature("signature.png")
    {
        Width = 150,
        Height = 50
    }
);

// Apply redaction to hide sensitive information
pdf.RedactTextOnPage(
    pageIndex: 0,
    searchText: "SSN: ***-**-****",
    replacementText: "[REDACTED]",
    caseSensitive: false
);

// Save the secured PDF
pdf.SaveAs("secure-confidential.pdf");
' Namespace: IronPdf
Imports IronPdf
' Namespace: IronPdf.Editing
Imports IronPdf.Editing

Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>")

' Apply password protection
pdf.SecuritySettings.UserPassword = "user123" ' Required to open
pdf.SecuritySettings.OwnerPassword = "owner456" ' Required to modify

' Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserFormData = True
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint

' Add digital signature for authenticity
pdf.SignWithFile(certificatePath:= "certificate.pfx", certificatePassword:= "certpass123", signingReason:= "Document Approval", signingLocation:= "New York, NY", signatureImage:= New Signature("signature.png") With {
	.Width = 150,
	.Height = 50
})

' Apply redaction to hide sensitive information
pdf.RedactTextOnPage(pageIndex:= 0, searchText:= "SSN: ***-**-****", replacementText:= "[REDACTED]", caseSensitive:= False)

' Save the secured PDF
pdf.SaveAs("secure-confidential.pdf")
$vbLabelText   $csharpLabel

合併和拆分PDF

合併多個PDF文件或提取特定頁面對於文件管理工作流程至關重要

// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;

// Merge multiple PDFs into one document
var coverPage = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Annual Report 2024</h1>");
var introduction = PdfDocument.FromFile("introduction.pdf");
var financials = PdfDocument.FromFile("financials.pdf");
var appendix = PdfDocument.FromFile("appendix.pdf");

// Merge all documents
var completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix);

// Add page numbers to the merged document
for (int i = 0; i < completeReport.PageCount; i++)
{
    completeReport.AddTextFooterToPage(i, 
        $"Page {i + 1} of {completeReport.PageCount}", 
        IronPdf.Font.FontTypes.Arial, 
        10);
}

completeReport.SaveAs("annual-report-complete.pdf");

// Extract specific pages
var executiveSummary = completeReport.CopyPages(0, 4); // First 5 pages
executiveSummary.SaveAs("executive-summary.pdf");

// Split a large PDF into chapters
var sourcePdf = PdfDocument.FromFile("large-document.pdf");
var chaptersPerFile = 50;

for (int i = 0; i < sourcePdf.PageCount; i += chaptersPerFile)
{
    var endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1);
    var chapter = sourcePdf.CopyPages(i, endPage);
    chapter.SaveAs($"chapter-{(i / chaptersPerFile) + 1}.pdf");
}
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;

// Merge multiple PDFs into one document
var coverPage = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Annual Report 2024</h1>");
var introduction = PdfDocument.FromFile("introduction.pdf");
var financials = PdfDocument.FromFile("financials.pdf");
var appendix = PdfDocument.FromFile("appendix.pdf");

// Merge all documents
var completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix);

// Add page numbers to the merged document
for (int i = 0; i < completeReport.PageCount; i++)
{
    completeReport.AddTextFooterToPage(i, 
        $"Page {i + 1} of {completeReport.PageCount}", 
        IronPdf.Font.FontTypes.Arial, 
        10);
}

completeReport.SaveAs("annual-report-complete.pdf");

// Extract specific pages
var executiveSummary = completeReport.CopyPages(0, 4); // First 5 pages
executiveSummary.SaveAs("executive-summary.pdf");

// Split a large PDF into chapters
var sourcePdf = PdfDocument.FromFile("large-document.pdf");
var chaptersPerFile = 50;

for (int i = 0; i < sourcePdf.PageCount; i += chaptersPerFile)
{
    var endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1);
    var chapter = sourcePdf.CopyPages(i, endPage);
    chapter.SaveAs($"chapter-{(i / chaptersPerFile) + 1}.pdf");
}
' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System

' Merge multiple PDFs into one document
Private coverPage = (New ChromePdfRenderer()).RenderHtmlAsPdf("<h1>Annual Report 2024</h1>")
Private introduction = PdfDocument.FromFile("introduction.pdf")
Private financials = PdfDocument.FromFile("financials.pdf")
Private appendix = PdfDocument.FromFile("appendix.pdf")

' Merge all documents
Private completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix)

' Add page numbers to the merged document
Dim i As Integer = 0
Do While i < completeReport.PageCount
	completeReport.AddTextFooterToPage(i, $"Page {i + 1} of {completeReport.PageCount}", IronPdf.Font.FontTypes.Arial, 10)
	i += 1
Loop

completeReport.SaveAs("annual-report-complete.pdf")

' Extract specific pages
Dim executiveSummary = completeReport.CopyPages(0, 4) ' First 5 pages
executiveSummary.SaveAs("executive-summary.pdf")

' Split a large PDF into chapters
Dim sourcePdf = PdfDocument.FromFile("large-document.pdf")
Dim chaptersPerFile = 50

For i As Integer = 0 To sourcePdf.PageCount - 1 Step chaptersPerFile
	Dim endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1)
	Dim chapter = sourcePdf.CopyPages(i, endPage)
	chapter.SaveAs($"chapter-{(i \ chaptersPerFile) + 1}.pdf")
Next i
$vbLabelText   $csharpLabel

添加浮水印和印章

在PDF文件上新增浮水印對於文件控制和品牌推廣至關重要。 IronPDF同時支援文字浮水印和影像浮水印:

// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;

var pdf = PdfDocument.FromFile("document.pdf");

// Add text watermark
pdf.ApplyWatermark(
    html: "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>",
    rotation: 45,
    opacity: 50,
    verticalAlignment: VerticalAlignment.Middle,
    horizontalAlignment: HorizontalAlignment.Center
);

// Add image watermark (company logo)
pdf.ApplyWatermark(
    html: "<img src='logo-watermark.png' style='width: 300px;' />",
    rotation: 0,
    opacity: 30,
    verticalAlignment: VerticalAlignment.Bottom,
    horizontalAlignment: HorizontalAlignment.Right
);

// Add stamps for document status
pdf.StampHtml(
    Html: @"<div style='border: 3px solid green; padding: 10px; 
            background: white; font-weight: bold; color: green;'>
            APPROVED<br/>
            " + DateTime.Now.ToString("MM/dd/yyyy") + @"
            </div>",
    X: 400,
    Y: 100,
    Width: 150,
    Height: 60,
    PageIndex: 0
);

pdf.SaveAs("watermarked-document.pdf");
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;

var pdf = PdfDocument.FromFile("document.pdf");

// Add text watermark
pdf.ApplyWatermark(
    html: "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>",
    rotation: 45,
    opacity: 50,
    verticalAlignment: VerticalAlignment.Middle,
    horizontalAlignment: HorizontalAlignment.Center
);

// Add image watermark (company logo)
pdf.ApplyWatermark(
    html: "<img src='logo-watermark.png' style='width: 300px;' />",
    rotation: 0,
    opacity: 30,
    verticalAlignment: VerticalAlignment.Bottom,
    horizontalAlignment: HorizontalAlignment.Right
);

// Add stamps for document status
pdf.StampHtml(
    Html: @"<div style='border: 3px solid green; padding: 10px; 
            background: white; font-weight: bold; color: green;'>
            APPROVED<br/>
            " + DateTime.Now.ToString("MM/dd/yyyy") + @"
            </div>",
    X: 400,
    Y: 100,
    Width: 150,
    Height: 60,
    PageIndex: 0
);

pdf.SaveAs("watermarked-document.pdf");
' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System

Private pdf = PdfDocument.FromFile("document.pdf")

' Add text watermark
pdf.ApplyWatermark(html:= "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>", rotation:= 45, opacity:= 50, verticalAlignment:= VerticalAlignment.Middle, horizontalAlignment:= HorizontalAlignment.Center)

' Add image watermark (company logo)
pdf.ApplyWatermark(html:= "<img src='logo-watermark.png' style='width: 300px;' />", rotation:= 0, opacity:= 30, verticalAlignment:= VerticalAlignment.Bottom, horizontalAlignment:= HorizontalAlignment.Right)

' Add stamps for document status
pdf.StampHtml(Html:= "<div style='border: 3px solid green; padding: 10px; 
            background: white; font-weight: bold; color: green;'>
            APPROVED<br/>
            " & DateTime.Now.ToString("MM/dd/yyyy") & "
            </div>", X:= 400, Y:= 100, Width:= 150, Height:= 60, PageIndex:= 0)

pdf.SaveAs("watermarked-document.pdf")
$vbLabelText   $csharpLabel

如何優化大規模產生 PDF 時的效能?

大規模產生 PDF時,效能至關重要。 無論您是建立數千張發票還是處理大型批次作業,優化PDF 產生程式碼都可以顯著提高吞吐量並降低資源消耗。 現代應用程式需要用 C# 有效率地建立 PDF 文件,既不能阻塞線程,也不能消耗過多記憶體。 以下是一些經過驗證的策略,可最大限度地提高您在使用 .NET 高效生成 PDF時各種 PDF 生成任務的效能。

異步 PDF 生成

現代應用程式需要非阻塞操作來保持響應速度。IronPdf為所有主要操作提供非同步方法:

// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.Collections.Generic
using System.Collections.Generic;
// Namespace: System.Linq
using System.Linq;
// Namespace: System
using System;
// Namespace: System.Threading
using System.Threading;

public class AsyncPdfService
{
    private readonly ChromePdfRenderer _renderer;

    public AsyncPdfService()
    {
        _renderer = new ChromePdfRenderer();
        // Configure renderer once for reuse
        _renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
    }

    public async Task<byte[]> GeneratePdfAsync(string html)
    {
        // Non-blocking PDF generation
        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        return pdf.BinaryData;
    }

    public async Task GenerateBatchAsync(List<string> htmlDocuments)
    {
        // Process multiple PDFs concurrently
        var tasks = htmlDocuments.Select(async (html, index) =>
        {
            var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
            await pdf.SaveAsAsync($"document-{index}.pdf");
        });

        await Task.WhenAll(tasks);
    }

    // Async with cancellation support
    public async Task<PdfDocument> GenerateWithTimeoutAsync(string html, int timeoutSeconds)
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));

        try
        {
            return await _renderer.RenderHtmlAsPdfAsync(html, cts.Token);
        }
        catch (OperationCanceledException)
        {
            throw new TimeoutException("PDF generation exceeded timeout");
        }
    }
}
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.Collections.Generic
using System.Collections.Generic;
// Namespace: System.Linq
using System.Linq;
// Namespace: System
using System;
// Namespace: System.Threading
using System.Threading;

public class AsyncPdfService
{
    private readonly ChromePdfRenderer _renderer;

    public AsyncPdfService()
    {
        _renderer = new ChromePdfRenderer();
        // Configure renderer once for reuse
        _renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
    }

    public async Task<byte[]> GeneratePdfAsync(string html)
    {
        // Non-blocking PDF generation
        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        return pdf.BinaryData;
    }

    public async Task GenerateBatchAsync(List<string> htmlDocuments)
    {
        // Process multiple PDFs concurrently
        var tasks = htmlDocuments.Select(async (html, index) =>
        {
            var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
            await pdf.SaveAsAsync($"document-{index}.pdf");
        });

        await Task.WhenAll(tasks);
    }

    // Async with cancellation support
    public async Task<PdfDocument> GenerateWithTimeoutAsync(string html, int timeoutSeconds)
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));

        try
        {
            return await _renderer.RenderHtmlAsPdfAsync(html, cts.Token);
        }
        catch (OperationCanceledException)
        {
            throw new TimeoutException("PDF generation exceeded timeout");
        }
    }
}
' Namespace: IronPdf
Imports IronPdf
' Namespace: System.Threading.Tasks
Imports System.Threading.Tasks
' Namespace: System.Collections.Generic
Imports System.Collections.Generic
' Namespace: System.Linq
Imports System.Linq
' Namespace: System
Imports System
' Namespace: System.Threading
Imports System.Threading

Public Class AsyncPdfService
	Private ReadOnly _renderer As ChromePdfRenderer

	Public Sub New()
		_renderer = New ChromePdfRenderer()
		' Configure renderer once for reuse
		_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
	End Sub

	Public Async Function GeneratePdfAsync(ByVal html As String) As Task(Of Byte())
		' Non-blocking PDF generation
		Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
		Return pdf.BinaryData
	End Function

	Public Async Function GenerateBatchAsync(ByVal htmlDocuments As List(Of String)) As Task
		' Process multiple PDFs concurrently
		Dim tasks = htmlDocuments.Select(Async Function(html, index)
			Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
			Await pdf.SaveAsAsync($"document-{index}.pdf")
		End Function)

		Await Task.WhenAll(tasks)
	End Function

	' Async with cancellation support
	Public Async Function GenerateWithTimeoutAsync(ByVal html As String, ByVal timeoutSeconds As Integer) As Task(Of PdfDocument)
		Dim cts = New CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds))

		Try
			Return Await _renderer.RenderHtmlAsPdfAsync(html, cts.Token)
		Catch e1 As OperationCanceledException
			Throw New TimeoutException("PDF generation exceeded timeout")
		End Try
	End Function
End Class
$vbLabelText   $csharpLabel

批量處理最佳實踐

處理多個PDF文件時,合理的資源管理和平行處理可以顯著提高效能:

using IronPdf;
using System.Threading.Tasks.Dataflow;

public class BatchPdfProcessor
{
    private readonly ChromePdfRenderer _renderer;
    private readonly ActionBlock<PdfJob> _processingBlock;

    public BatchPdfProcessor(int maxConcurrency = 4)
    {
        _renderer = new ChromePdfRenderer();

        // Create a processing pipeline with controlled concurrency
        _processingBlock = new ActionBlock<PdfJob>(
            async job => await ProcessPdfAsync(job),
            new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = maxConcurrency,
                BoundedCapacity = maxConcurrency * 2
            });
    }

    private async Task ProcessPdfAsync(PdfJob job)
    {
        try
        {
            var pdf = await _renderer.RenderHtmlAsPdfAsync(job.Html);
            await pdf.SaveAsAsync(job.OutputPath);
            job.OnSuccess?.Invoke();
        }
        catch (Exception ex)
        {
            job.OnError?.Invoke(ex);
        }
    }

    public async Task<bool> QueuePdfAsync(PdfJob job)
    {
        return await _processingBlock.SendAsync(job);
    }

    public async Task CompleteAsync()
    {
        _processingBlock.Complete();
        await _processingBlock.Completion;
    }
}

public class PdfJob
{
    public string Html { get; set; }
    public string OutputPath { get; set; }
    public Action OnSuccess { get; set; }
    public Action<Exception> OnError { get; set; }
}
using IronPdf;
using System.Threading.Tasks.Dataflow;

public class BatchPdfProcessor
{
    private readonly ChromePdfRenderer _renderer;
    private readonly ActionBlock<PdfJob> _processingBlock;

    public BatchPdfProcessor(int maxConcurrency = 4)
    {
        _renderer = new ChromePdfRenderer();

        // Create a processing pipeline with controlled concurrency
        _processingBlock = new ActionBlock<PdfJob>(
            async job => await ProcessPdfAsync(job),
            new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = maxConcurrency,
                BoundedCapacity = maxConcurrency * 2
            });
    }

    private async Task ProcessPdfAsync(PdfJob job)
    {
        try
        {
            var pdf = await _renderer.RenderHtmlAsPdfAsync(job.Html);
            await pdf.SaveAsAsync(job.OutputPath);
            job.OnSuccess?.Invoke();
        }
        catch (Exception ex)
        {
            job.OnError?.Invoke(ex);
        }
    }

    public async Task<bool> QueuePdfAsync(PdfJob job)
    {
        return await _processingBlock.SendAsync(job);
    }

    public async Task CompleteAsync()
    {
        _processingBlock.Complete();
        await _processingBlock.Completion;
    }
}

public class PdfJob
{
    public string Html { get; set; }
    public string OutputPath { get; set; }
    public Action OnSuccess { get; set; }
    public Action<Exception> OnError { get; set; }
}
Imports IronPdf
Imports System.Threading.Tasks.Dataflow

Public Class BatchPdfProcessor
	Private ReadOnly _renderer As ChromePdfRenderer
	Private ReadOnly _processingBlock As ActionBlock(Of PdfJob)

	Public Sub New(Optional ByVal maxConcurrency As Integer = 4)
		_renderer = New ChromePdfRenderer()

		' Create a processing pipeline with controlled concurrency
		_processingBlock = New ActionBlock(Of PdfJob)(Async Function(job) Await ProcessPdfAsync(job), New ExecutionDataflowBlockOptions With {
			.MaxDegreeOfParallelism = maxConcurrency,
			.BoundedCapacity = maxConcurrency * 2
		})
	End Sub

	Private Async Function ProcessPdfAsync(ByVal job As PdfJob) As Task
		Try
			Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(job.Html)
			Await pdf.SaveAsAsync(job.OutputPath)
			If job.OnSuccess IsNot Nothing Then
				job.OnSuccess.Invoke()
			End If
		Catch ex As Exception
			If job.OnError IsNot Nothing Then
				job.OnError.Invoke(ex)
			End If
		End Try
	End Function

	Public Async Function QueuePdfAsync(ByVal job As PdfJob) As Task(Of Boolean)
		Return Await _processingBlock.SendAsync(job)
	End Function

	Public Async Function CompleteAsync() As Task
		_processingBlock.Complete()
		Await _processingBlock.Completion
	End Function
End Class

Public Class PdfJob
	Public Property Html() As String
	Public Property OutputPath() As String
	Public Property OnSuccess() As Action
	Public Property OnError() As Action(Of Exception)
End Class
$vbLabelText   $csharpLabel

記憶體優化技術

對於大型 PDF 檔案或高容量處理,記憶體管理至關重要:

using IronPdf;

public class MemoryEfficientPdfGenerator
{
    private readonly ChromePdfRenderer _renderer;

    public MemoryEfficientPdfGenerator()
    {
        _renderer = new ChromePdfRenderer();

        // Optimize for memory usage
        _renderer.RenderingOptions.RenderQuality = 90; // Slightly lower quality for smaller size
        _renderer.RenderingOptions.ImageQuality = 85; // Compress images
    }

    // Stream large PDFs instead of loading into memory
    public async Task GenerateLargePdfToStreamAsync(string html, Stream outputStream)
    {
        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);

        // Write directly to stream without keeping in memory
        using (pdf)
        {
            var bytes = pdf.BinaryData;
            await outputStream.WriteAsync(bytes, 0, bytes.Length);
        }
    }

    // Process large HTML in chunks
    public async Task<PdfDocument> GenerateFromChunksAsync(List<string> htmlChunks)
    {
        var pdfs = new List<PdfDocument>();

        try
        {
            // Generate each chunk separately
            foreach (var chunk in htmlChunks)
            {
                var chunkPdf = await _renderer.RenderHtmlAsPdfAsync(chunk);
                pdfs.Add(chunkPdf);
            }

            // Merge all chunks
            return PdfDocument.Merge(pdfs.ToArray());
        }
        finally
        {
            // Ensure all temporary PDFs are disposed
            foreach (var pdf in pdfs)
            {
                pdf?.Dispose();
            }
        }
    }
}
using IronPdf;

public class MemoryEfficientPdfGenerator
{
    private readonly ChromePdfRenderer _renderer;

    public MemoryEfficientPdfGenerator()
    {
        _renderer = new ChromePdfRenderer();

        // Optimize for memory usage
        _renderer.RenderingOptions.RenderQuality = 90; // Slightly lower quality for smaller size
        _renderer.RenderingOptions.ImageQuality = 85; // Compress images
    }

    // Stream large PDFs instead of loading into memory
    public async Task GenerateLargePdfToStreamAsync(string html, Stream outputStream)
    {
        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);

        // Write directly to stream without keeping in memory
        using (pdf)
        {
            var bytes = pdf.BinaryData;
            await outputStream.WriteAsync(bytes, 0, bytes.Length);
        }
    }

    // Process large HTML in chunks
    public async Task<PdfDocument> GenerateFromChunksAsync(List<string> htmlChunks)
    {
        var pdfs = new List<PdfDocument>();

        try
        {
            // Generate each chunk separately
            foreach (var chunk in htmlChunks)
            {
                var chunkPdf = await _renderer.RenderHtmlAsPdfAsync(chunk);
                pdfs.Add(chunkPdf);
            }

            // Merge all chunks
            return PdfDocument.Merge(pdfs.ToArray());
        }
        finally
        {
            // Ensure all temporary PDFs are disposed
            foreach (var pdf in pdfs)
            {
                pdf?.Dispose();
            }
        }
    }
}
Imports IronPdf

Public Class MemoryEfficientPdfGenerator
	Private ReadOnly _renderer As ChromePdfRenderer

	Public Sub New()
		_renderer = New ChromePdfRenderer()

		' Optimize for memory usage
		_renderer.RenderingOptions.RenderQuality = 90 ' Slightly lower quality for smaller size
		_renderer.RenderingOptions.ImageQuality = 85 ' Compress images
	End Sub

	' Stream large PDFs instead of loading into memory
	Public Async Function GenerateLargePdfToStreamAsync(ByVal html As String, ByVal outputStream As Stream) As Task
		Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)

		' Write directly to stream without keeping in memory
		Using pdf
			Dim bytes = pdf.BinaryData
			Await outputStream.WriteAsync(bytes, 0, bytes.Length)
		End Using
	End Function

	' Process large HTML in chunks
	Public Async Function GenerateFromChunksAsync(ByVal htmlChunks As List(Of String)) As Task(Of PdfDocument)
		Dim pdfs = New List(Of PdfDocument)()

		Try
			' Generate each chunk separately
			For Each chunk In htmlChunks
				Dim chunkPdf = Await _renderer.RenderHtmlAsPdfAsync(chunk)
				pdfs.Add(chunkPdf)
			Next chunk

			' Merge all chunks
			Return PdfDocument.Merge(pdfs.ToArray())
		Finally
			' Ensure all temporary PDFs are disposed
			For Each pdf In pdfs
				If pdf IsNot Nothing Then
					pdf.Dispose()
				End If
			Next pdf
		End Try
	End Function
End Class
$vbLabelText   $csharpLabel

快取和模板優化

透過快取常用元素和優化模板來減少渲染時間:

using IronPdf;
using Microsoft.Extensions.Caching.Memory;

public class CachedPdfService
{
    private readonly ChromePdfRenderer _renderer;
    private readonly IMemoryCache _cache;
    private readonly Dictionary<string, string> _compiledTemplates;

    public CachedPdfService(IMemoryCache cache)
    {
        _renderer = new ChromePdfRenderer();
        _cache = cache;
        _compiledTemplates = new Dictionary<string, string>();

        // Pre-compile common templates
        PrecompileTemplates();
    }

    private void PrecompileTemplates()
    {
        // Load and cache common CSS
        var commonCss = File.ReadAllText("Templates/common.css");
        _compiledTemplates["commonCss"] = commonCss;

        // Cache logo as Base64
        var logoBytes = File.ReadAllBytes("Assets/logo.png");
        var logoBase64 = Convert.ToBase64String(logoBytes);
        _compiledTemplates["logoData"] = $"data:image/png;base64,{logoBase64}";
    }

    public async Task<byte[]> GenerateInvoicePdfAsync(string invoiceId, InvoiceData data)
    {
        // Check cache first
        var cacheKey = $"invoice_{invoiceId}";
        if (_cache.TryGetValue<byte[]>(cacheKey, out var cachedPdf))
        {
            return cachedPdf;
        }

        // Generate PDF with cached templates
        var html = BuildHtmlWithCache(data);
        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        var pdfBytes = pdf.BinaryData;

        // Cache for 1 hour
        _cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));

        return pdfBytes;
    }

    private string BuildHtmlWithCache(InvoiceData data)
    {
        return $@"
            <html>
            <head>
                <style>{_compiledTemplates["commonCss"]}</style>
            </head>
            <body>
                <img src='{_compiledTemplates["logoData"]}' />
                <!-- Rest of invoice HTML -->
            </body>
            </html>";
    }
}
using IronPdf;
using Microsoft.Extensions.Caching.Memory;

public class CachedPdfService
{
    private readonly ChromePdfRenderer _renderer;
    private readonly IMemoryCache _cache;
    private readonly Dictionary<string, string> _compiledTemplates;

    public CachedPdfService(IMemoryCache cache)
    {
        _renderer = new ChromePdfRenderer();
        _cache = cache;
        _compiledTemplates = new Dictionary<string, string>();

        // Pre-compile common templates
        PrecompileTemplates();
    }

    private void PrecompileTemplates()
    {
        // Load and cache common CSS
        var commonCss = File.ReadAllText("Templates/common.css");
        _compiledTemplates["commonCss"] = commonCss;

        // Cache logo as Base64
        var logoBytes = File.ReadAllBytes("Assets/logo.png");
        var logoBase64 = Convert.ToBase64String(logoBytes);
        _compiledTemplates["logoData"] = $"data:image/png;base64,{logoBase64}";
    }

    public async Task<byte[]> GenerateInvoicePdfAsync(string invoiceId, InvoiceData data)
    {
        // Check cache first
        var cacheKey = $"invoice_{invoiceId}";
        if (_cache.TryGetValue<byte[]>(cacheKey, out var cachedPdf))
        {
            return cachedPdf;
        }

        // Generate PDF with cached templates
        var html = BuildHtmlWithCache(data);
        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        var pdfBytes = pdf.BinaryData;

        // Cache for 1 hour
        _cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));

        return pdfBytes;
    }

    private string BuildHtmlWithCache(InvoiceData data)
    {
        return $@"
            <html>
            <head>
                <style>{_compiledTemplates["commonCss"]}</style>
            </head>
            <body>
                <img src='{_compiledTemplates["logoData"]}' />
                <!-- Rest of invoice HTML -->
            </body>
            </html>";
    }
}
Imports IronPdf
Imports Microsoft.Extensions.Caching.Memory

Public Class CachedPdfService
	Private ReadOnly _renderer As ChromePdfRenderer
	Private ReadOnly _cache As IMemoryCache
	Private ReadOnly _compiledTemplates As Dictionary(Of String, String)

	Public Sub New(ByVal cache As IMemoryCache)
		_renderer = New ChromePdfRenderer()
		_cache = cache
		_compiledTemplates = New Dictionary(Of String, String)()

		' Pre-compile common templates
		PrecompileTemplates()
	End Sub

	Private Sub PrecompileTemplates()
		' Load and cache common CSS
		Dim commonCss = File.ReadAllText("Templates/common.css")
		_compiledTemplates("commonCss") = commonCss

		' Cache logo as Base64
		Dim logoBytes = File.ReadAllBytes("Assets/logo.png")
		Dim logoBase64 = Convert.ToBase64String(logoBytes)
		_compiledTemplates("logoData") = $"data:image/png;base64,{logoBase64}"
	End Sub

	Public Async Function GenerateInvoicePdfAsync(ByVal invoiceId As String, ByVal data As InvoiceData) As Task(Of Byte())
		' Check cache first
		Dim cacheKey = $"invoice_{invoiceId}"
		Dim cachedPdf As var
		If _cache.TryGetValue(Of Byte())(cacheKey, cachedPdf) Then
			Return cachedPdf
		End If

		' Generate PDF with cached templates
		Dim html = BuildHtmlWithCache(data)
		Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
		Dim pdfBytes = pdf.BinaryData

		' Cache for 1 hour
		_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1))

		Return pdfBytes
	End Function

	Private Function BuildHtmlWithCache(ByVal data As InvoiceData) As String
		Return $"
            <html>
            <head>
                <style>{_compiledTemplates("commonCss")}</style>ignoreignoreignore</head><body><img src='{_compiledTemplates("logoData")}' /><!-- Rest of invoice HTML --></body></html>"
	End Function
End Class
$vbLabelText   $csharpLabel

建立 PDF 時常見的問題有哪些?如何解決這些問題?

即使使用像IronPdf這樣強大的.NET PDF 庫在 C# 中建立 PDF時,在開發或部署過程中也可能會遇到挑戰。 了解常見問題及其解決方案有助於您快速解決問題並保持流暢的PDF 生成操作。 好消息是,由於超過 1400 萬開發者使用IronPdf作為他們的C# PDF 產生器,大多數問題都已被遇到並解決。 本故障排除指南涵蓋了開發人員在 .NET 中建立 PDF時遇到的最常見問題,並根據實際經驗提供了實用的解決方案。 請記住,如果您在建立 PDF 文件時遇到任何問題需要立即協助,我們始終提供24/7 全天候支援

問題一:渲染失敗或產生空白PDF文件

最常見的問題之一是 PDF 檔案顯示空白或無法正確渲染。 這通常發生在資源載入不及時或JavaScript 有時序問題時:

// Namespace: IronPdf
using IronPdf;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;

// Problem: PDF is blank or missing content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(complexHtml); // Results in blank PDF

// Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000; // Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = true;

// Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = new WaitFor()
{
    JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
    WaitForType = WaitForType.JavaScript,
    Timeout = 30000 // 30 second timeout
};

// Solution 3: Use base path for local assets
var basePath = Path.GetFullPath("Assets");
var pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath);

// Solution 4: Embed assets as Base64
var imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"));
var htmlWithEmbedded = $@"<img src='data:image/png;base64,{imageBase64}' />";
// Namespace: IronPdf
using IronPdf;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;

// Problem: PDF is blank or missing content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(complexHtml); // Results in blank PDF

// Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000; // Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = true;

// Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = new WaitFor()
{
    JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
    WaitForType = WaitForType.JavaScript,
    Timeout = 30000 // 30 second timeout
};

// Solution 3: Use base path for local assets
var basePath = Path.GetFullPath("Assets");
var pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath);

// Solution 4: Embed assets as Base64
var imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"));
var htmlWithEmbedded = $@"<img src='data:image/png;base64,{imageBase64}' />";
' Namespace: IronPdf
Imports IronPdf
' Namespace: System.IO
Imports System.IO
' Namespace: System
Imports System

' Problem: PDF is blank or missing content
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf(complexHtml) ' Results in blank PDF

' Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000 ' Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = True

' Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = New WaitFor() With {
	.JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
	.WaitForType = WaitForType.JavaScript,
	.Timeout = 30000
}

' Solution 3: Use base path for local assets
Dim basePath = Path.GetFullPath("Assets")
Dim pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath)

' Solution 4: Embed assets as Base64
Dim imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"))
Dim htmlWithEmbedded = $"<img src='data:image/png;base64,{imageBase64}' />"
$vbLabelText   $csharpLabel

如果持續出現渲染問題,請啟用日誌記錄以診斷問題:

// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
' Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = True
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log"
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
$vbLabelText   $csharpLabel

了解更多關於解決渲染問題的信息

問題 2:初始渲染速度慢

由於初始化開銷,首次產生 PDF 檔案的速度可能會較慢。IronPdf的初始渲染可能需要 2-3 秒才能完成,這是正常的啟動時間,類似於 Chrome 在桌面環境下開啟所需的時間:

// Problem: First PDF takes too long to generate
public class PdfService
{
    private ChromePdfRenderer _renderer;

    // Solution 1: Initialize renderer at startup
    public void Initialize()
    {
        _renderer = new ChromePdfRenderer();

        // Warm up the renderer
        _ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
    }

    // Solution 2: Use IronPdf.Native packages for faster initialization
    // Install-Package IronPdf.Native.Windows.X64
    // This includes pre-loaded binaries for your platform

    // Solution 3: For cloud deployments, use appropriate packages
    // For Linux: Install-Package IronPdf.Linux
    // For Docker: Use IronPdf.Linux with proper dependencies
}

// Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = true; // Use only with persistent storage
// Problem: First PDF takes too long to generate
public class PdfService
{
    private ChromePdfRenderer _renderer;

    // Solution 1: Initialize renderer at startup
    public void Initialize()
    {
        _renderer = new ChromePdfRenderer();

        // Warm up the renderer
        _ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
    }

    // Solution 2: Use IronPdf.Native packages for faster initialization
    // Install-Package IronPdf.Native.Windows.X64
    // This includes pre-loaded binaries for your platform

    // Solution 3: For cloud deployments, use appropriate packages
    // For Linux: Install-Package IronPdf.Linux
    // For Docker: Use IronPdf.Linux with proper dependencies
}

// Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = true; // Use only with persistent storage
' Problem: First PDF takes too long to generate
Public Class PdfService
	Private _renderer As ChromePdfRenderer

	' Solution 1: Initialize renderer at startup
	Public Sub Initialize()
		_renderer = New ChromePdfRenderer()

		' Warm up the renderer
'INSTANT VB TODO TASK: Underscore 'discards' are not converted by Instant VB:
'ORIGINAL LINE: _ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
		underscore = _renderer.RenderHtmlAsPdf("<p>Warm up</p>")
	End Sub

	' Solution 2: Use IronPdf.Native packages for faster initialization
	' Install-Package IronPdf.Native.Windows.X64
	' This includes pre-loaded binaries for your platform

	' Solution 3: For cloud deployments, use appropriate packages
	' For Linux: Install-Package IronPdf.Linux
	' For Docker: Use IronPdf.Linux with proper dependencies
End Class

' Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = True ' Use only with persistent storage
$vbLabelText   $csharpLabel

閱讀更多關於優化新創企業績效的內容

問題 3:Linux/Docker 上的部署問題

IronPDF 需要特定的 Linux 依賴項,而這些依賴項可能在最小 Docker 映像中不存在。 以下是解決常見部署問題的方法:

# Dockerfile forIronPdfon Linux
FROM mcr.microsoft.com/dotnet/aspnet:8.0

# Install required dependencies
RUN apt-get update && apt-get install -y \
    libglib2.0-0 \
    libnss3 \
    libatk1.0-0 \
    libatk-bridge2.0-0 \
    libcups2 \
    libxkbcommon0 \
    libxcomposite1 \
    libxdamage1 \
    libxrandr2 \
    libgbm1 \
    libpango-1.0-0 \
    libcairo2 \
    libasound2 \
    libxshmfence1 \
    libx11-xcb1

# Copy and run your application
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet", "YourApp.dll"]

具體來說,針對 Google Cloud Run:

// Use 2nd generation execution environment
// Deploy with: gcloud run deploy --execution-environment gen2

// In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Use 2nd generation execution environment
// Deploy with: gcloud run deploy --execution-environment gen2

// In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
' Use 2nd generation execution environment
' Deploy with: gcloud run deploy --execution-environment gen2

' In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
$vbLabelText   $csharpLabel

了解更多關於 Docker 部署的信息

問題 4:記憶體和效能問題

對於大批量 PDF 生成,請優化記憶體使用和效能:

// Problem: High memory usage or slow batch processing
public class OptimizedPdfService
{
    private readonly ChromePdfRenderer _renderer;

    public OptimizedPdfService()
    {
        _renderer = new ChromePdfRenderer();

        // Optimize for performance
        _renderer.RenderingOptions.RenderQuality = 90;
        _renderer.RenderingOptions.ImageQuality = 85;

        // Disable features you don't need
        _renderer.RenderingOptions.EnableJavaScript = false; // If not needed
        _renderer.RenderingOptions.RenderDelay = 0; // If content is static
    }

    // Solution 1: Process large documents in chunks
    public async Task<PdfDocument> GenerateLargeReportAsync(List<ReportSection> sections)
    {
        var pdfs = new List<PdfDocument>();

        foreach (var section in sections)
        {
            var sectionHtml = GenerateSectionHtml(section);
            var sectionPdf = await _renderer.RenderHtmlAsPdfAsync(sectionHtml);
            pdfs.Add(sectionPdf);

            // Force garbage collection after each section
            if (pdfs.Count % 10 == 0)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        return PdfDocument.Merge(pdfs.ToArray());
    }

    // Solution 2: Use streaming for large files
    public async Task StreamLargePdfAsync(string html, HttpResponse response)
    {
        response.ContentType = "application/pdf";
        response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf");

        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        var bytes = pdf.BinaryData;

        await response.Body.WriteAsync(bytes, 0, bytes.Length);
        await response.Body.FlushAsync();
    }
}
// Problem: High memory usage or slow batch processing
public class OptimizedPdfService
{
    private readonly ChromePdfRenderer _renderer;

    public OptimizedPdfService()
    {
        _renderer = new ChromePdfRenderer();

        // Optimize for performance
        _renderer.RenderingOptions.RenderQuality = 90;
        _renderer.RenderingOptions.ImageQuality = 85;

        // Disable features you don't need
        _renderer.RenderingOptions.EnableJavaScript = false; // If not needed
        _renderer.RenderingOptions.RenderDelay = 0; // If content is static
    }

    // Solution 1: Process large documents in chunks
    public async Task<PdfDocument> GenerateLargeReportAsync(List<ReportSection> sections)
    {
        var pdfs = new List<PdfDocument>();

        foreach (var section in sections)
        {
            var sectionHtml = GenerateSectionHtml(section);
            var sectionPdf = await _renderer.RenderHtmlAsPdfAsync(sectionHtml);
            pdfs.Add(sectionPdf);

            // Force garbage collection after each section
            if (pdfs.Count % 10 == 0)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        return PdfDocument.Merge(pdfs.ToArray());
    }

    // Solution 2: Use streaming for large files
    public async Task StreamLargePdfAsync(string html, HttpResponse response)
    {
        response.ContentType = "application/pdf";
        response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf");

        var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        var bytes = pdf.BinaryData;

        await response.Body.WriteAsync(bytes, 0, bytes.Length);
        await response.Body.FlushAsync();
    }
}
' Problem: High memory usage or slow batch processing
Public Class OptimizedPdfService
	Private ReadOnly _renderer As ChromePdfRenderer

	Public Sub New()
		_renderer = New ChromePdfRenderer()

		' Optimize for performance
		_renderer.RenderingOptions.RenderQuality = 90
		_renderer.RenderingOptions.ImageQuality = 85

		' Disable features you don't need
		_renderer.RenderingOptions.EnableJavaScript = False ' If not needed
		_renderer.RenderingOptions.RenderDelay = 0 ' If content is static
	End Sub

	' Solution 1: Process large documents in chunks
	Public Async Function GenerateLargeReportAsync(ByVal sections As List(Of ReportSection)) As Task(Of PdfDocument)
		Dim pdfs = New List(Of PdfDocument)()

		For Each section In sections
			Dim sectionHtml = GenerateSectionHtml(section)
			Dim sectionPdf = Await _renderer.RenderHtmlAsPdfAsync(sectionHtml)
			pdfs.Add(sectionPdf)

			' Force garbage collection after each section
			If pdfs.Count Mod 10 = 0 Then
				GC.Collect()
				GC.WaitForPendingFinalizers()
			End If
		Next section

		Return PdfDocument.Merge(pdfs.ToArray())
	End Function

	' Solution 2: Use streaming for large files
	Public Async Function StreamLargePdfAsync(ByVal html As String, ByVal response As HttpResponse) As Task
		response.ContentType = "application/pdf"
		response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf")

		Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
		Dim bytes = pdf.BinaryData

		Await response.Body.WriteAsync(bytes, 0, bytes.Length)
		Await response.Body.FlushAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

閱讀完整的效能優化指南

問題五:字體與編碼問題

處理國際內容或自訂字體時:

// Problem: Fonts not rendering correctly
var renderer = new ChromePdfRenderer();

// Solution 1: Install fonts on the server
// For Linux/Docker, add to Dockerfile:
// RUN apt-get install -y fonts-liberation fonts-noto

// Solution 2: Embed fonts in HTML
var html = @"
<html>
<head>
    <style>
        @font-face {
            font-family: 'CustomFont';
            src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
        }
        body { font-family: 'CustomFont', Arial, sans-serif; }
    </style>
</head>
<body>
    <p>Content with custom font</p>
</body>
</html>";

// Solution 3: Use web fonts
var htmlWithWebFont = @"
<html>
<head>
    <link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
    <style>
        body { font-family: 'Noto Sans JP', sans-serif; }
    </style>
</head>
<body>
    <p>日本語のテキスト</p>
</body>
</html>";

// Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8;
// Problem: Fonts not rendering correctly
var renderer = new ChromePdfRenderer();

// Solution 1: Install fonts on the server
// For Linux/Docker, add to Dockerfile:
// RUN apt-get install -y fonts-liberation fonts-noto

// Solution 2: Embed fonts in HTML
var html = @"
<html>
<head>
    <style>
        @font-face {
            font-family: 'CustomFont';
            src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
        }
        body { font-family: 'CustomFont', Arial, sans-serif; }
    </style>
</head>
<body>
    <p>Content with custom font</p>
</body>
</html>";

// Solution 3: Use web fonts
var htmlWithWebFont = @"
<html>
<head>
    <link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
    <style>
        body { font-family: 'Noto Sans JP', sans-serif; }
    </style>
</head>
<body>
    <p>日本語のテキスト</p>
</body>
</html>";

// Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8;
' Problem: Fonts not rendering correctly
Dim renderer = New ChromePdfRenderer()

' Solution 1: Install fonts on the server
' For Linux/Docker, add to Dockerfile:
' RUN apt-get install -y fonts-liberation fonts-noto

' Solution 2: Embed fonts in HTML
Dim html = "
<html>
<head>
    <style>
        @font-face {
            font-family: 'CustomFont';
            src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
        }
        body { font-family: 'CustomFont', Arial, sans-serif; }
    </style>
</head>
<body>
    <p>Content with custom font</p>
</body>
</html>"

' Solution 3: Use web fonts
Dim htmlWithWebFont = "
<html>
<head>
    <link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
    <style>
        body { font-family: 'Noto Sans JP', sans-serif; }
    </style>
</head>
<body>
    <p>日本語のテキスト</p>
</body>
</html>"

' Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8
$vbLabelText   $csharpLabel

尋求協助

如果您遇到此處未涵蓋的問題,IronPDF 提供了優秀的幫助資源:

1.全天候線上聊天支援- 與工程師即時溝通,30 秒內即可獲得回應 2.完善的文件- 詳細的 API 參考和指南 3.知識庫- 常見問題的解決方案 4.程式碼範例- 可直接使用的程式碼片段

請求支援時,請包含以下資訊:

-IronPdf版本

  • .NET 版本與平台
  • 可重現問題的最小程式碼範例
  • 日誌檔(如有)
  • 堆疊追蹤或錯誤訊息

哪些平台支援IronPdf產生 PDF 檔案?

IronPDF 的跨平台支援確保您的PDF 生成程式碼在不同的環境中都能一致地運作。 無論您是部署到 Windows 伺服器、Linux 容器或雲端平台,IronPDF 都能提供C# PDF 生成器生產部署所需的靈活性和可靠性。 這種普遍的兼容性是50 多個國家的組織依賴IronPdf每天產生數百萬個 PDF 文件的原因之一。 從創建財務報告的財富 500 強公司到產生客戶發票的新創公司,IronPDF 可擴展以滿足.NET 中創建 PDF的任何需求。 了解平台特定因素有助於確保在您的基礎架構中順利部署—無論是在本機伺服器還是需要在雲端環境使用 C# 建置 PDF

.NET 版本相容性

IronPDF 支援所有現代 .NET 版本,並持續更新以支援最新版本:

  • .NET 8 - 完全支援所有功能
  • .NET 9 - 完全支援(目前最新版本)
  • .NET 10 - 提供預發布支援(IronPDF 已符合 2025 年 11 月發布的 .NET 10 版本要求)
  • 完全支援.NET 7、6、5
  • 支援.NET Core 3.1+及更高版本的所有功能
  • .NET Framework 4.6.2+ - 保留舊版支持

作業系統支援

將您的 PDF 生成解決方案部署到任何主流作業系統:

Windows

  • Windows 11、10、8、7
  • Windows Server 2022、2019、2016、2012

Linux

  • Ubuntu 20.04、22.04、24.04
  • Debian 10、11、12 CentOS 7、8
  • 紅帽企業 Linux
  • Alpine Linux(需額外設定)

macOS

  • macOS 13 (Ventura) 及更高版本
  • 原生支援 Apple Silicon (M1/M2/M3)
  • 完全支援基於 Intel 的 Mac 電腦

雲端平台部署

IronPDF 可在所有主流雲端平台上無縫運作:

Microsoft Azure

// Azure App Service configuration
// Use at least B1 tier for optimal performance
// Enable 64-bit platform in Configuration settings

// For Azure Functions
public static class PdfFunction
{
    [FunctionName("GeneratePdf")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
    {
        var renderer = new ChromePdfRenderer();
        var html = await new StreamReader(req.Body).ReadToEndAsync();
        var pdf = await renderer.RenderHtmlAsPdfAsync(html);

        return new FileContentResult(pdf.BinaryData, "application/pdf");
    }
}
// Azure App Service configuration
// Use at least B1 tier for optimal performance
// Enable 64-bit platform in Configuration settings

// For Azure Functions
public static class PdfFunction
{
    [FunctionName("GeneratePdf")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
    {
        var renderer = new ChromePdfRenderer();
        var html = await new StreamReader(req.Body).ReadToEndAsync();
        var pdf = await renderer.RenderHtmlAsPdfAsync(html);

        return new FileContentResult(pdf.BinaryData, "application/pdf");
    }
}
' Azure App Service configuration
' Use at least B1 tier for optimal performance
' Enable 64-bit platform in Configuration settings

' For Azure Functions
Public Module PdfFunction
	<FunctionName("GeneratePdf")>
	Public Async Function Run(<HttpTrigger(AuthorizationLevel.Function, "post")> ByVal req As HttpRequest) As Task(Of IActionResult)
		Dim renderer = New ChromePdfRenderer()
		Dim html = Await (New StreamReader(req.Body)).ReadToEndAsync()
		Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)

		Return New FileContentResult(pdf.BinaryData, "application/pdf")
	End Function
End Module
$vbLabelText   $csharpLabel

亞馬遜網路服務(AWS)

// AWS Lambda configuration
// Use custom runtime or container deployment
// Ensure Lambda has at least 512MB memory

public class PdfLambdaFunction
{
    private readonly ChromePdfRenderer _renderer;

    public PdfLambdaFunction()
    {
        _renderer = new ChromePdfRenderer();
        // Configure for Lambda environment
        IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
    }

    public async Task<APIGatewayProxyResponse> FunctionHandler(
        APIGatewayProxyRequest request, 
        ILambdaContext context)
    {
        var pdf = await _renderer.RenderHtmlAsPdfAsync(request.Body);

        return new APIGatewayProxyResponse
        {
            StatusCode = 200,
            Headers = new Dictionary<string, string> 
            { 
                { "Content-Type", "application/pdf" } 
            },
            Body = Convert.ToBase64String(pdf.BinaryData),
            IsBase64Encoded = true
        };
    }
}
// AWS Lambda configuration
// Use custom runtime or container deployment
// Ensure Lambda has at least 512MB memory

public class PdfLambdaFunction
{
    private readonly ChromePdfRenderer _renderer;

    public PdfLambdaFunction()
    {
        _renderer = new ChromePdfRenderer();
        // Configure for Lambda environment
        IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
    }

    public async Task<APIGatewayProxyResponse> FunctionHandler(
        APIGatewayProxyRequest request, 
        ILambdaContext context)
    {
        var pdf = await _renderer.RenderHtmlAsPdfAsync(request.Body);

        return new APIGatewayProxyResponse
        {
            StatusCode = 200,
            Headers = new Dictionary<string, string> 
            { 
                { "Content-Type", "application/pdf" } 
            },
            Body = Convert.ToBase64String(pdf.BinaryData),
            IsBase64Encoded = true
        };
    }
}
' AWS Lambda configuration
' Use custom runtime or container deployment
' Ensure Lambda has at least 512MB memory

Public Class PdfLambdaFunction
	Private ReadOnly _renderer As ChromePdfRenderer

	Public Sub New()
		_renderer = New ChromePdfRenderer()
		' Configure for Lambda environment
		IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
	End Sub

	Public Async Function FunctionHandler(ByVal request As APIGatewayProxyRequest, ByVal context As ILambdaContext) As Task(Of APIGatewayProxyResponse)
		Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(request.Body)

		Return New APIGatewayProxyResponse With {
			.StatusCode = 200,
			.Headers = New Dictionary(Of String, String) From {
				{"Content-Type", "application/pdf"}
			},
			.Body = Convert.ToBase64String(pdf.BinaryData),
			.IsBase64Encoded = True
		}
	End Function
End Class
$vbLabelText   $csharpLabel

Google Cloud Platform

# app.yaml for App Engine
runtime: aspnetcore
env: flex

# Use 2nd generation for Cloud Run
# Deploy with: gcloud run deploy --execution-environment gen2
# app.yaml for App Engine
runtime: aspnetcore
env: flex

# Use 2nd generation for Cloud Run
# Deploy with: gcloud run deploy --execution-environment gen2
YAML

容器部署(Docker/Kubernetes)

IronPDF 已做好容器化準備,完全支援Docker和 Kubernetes:

# Multi-stage Dockerfile for optimal size
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["YourApp.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish

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

# InstallIronPdfdependencies
RUN apt-get update && apt-get install -y \
    libglib2.0-0 libnss3 libatk1.0-0 libatk-bridge2.0-0 \
    libcups2 libxkbcommon0 libxcomposite1 libxdamage1 \
    libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2

COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "YourApp.dll"]

桌面應用程式支援

IronPDF 可與所有主流 .NET 桌面框架搭配使用:

WPF(Windows Presentation Foundation)

public partial class MainWindow : Window
{
    private async void GeneratePdfButton_Click(object sender, RoutedEventArgs e)
    {
        var renderer = new ChromePdfRenderer();
        var html = HtmlEditor.Text;

        var pdf = await renderer.RenderHtmlAsPdfAsync(html);

        var saveDialog = new SaveFileDialog
        {
            Filter = "PDF files (*.pdf)|*.pdf",
            DefaultExt = "pdf"
        };

        if (saveDialog.ShowDialog() == true)
        {
            pdf.SaveAs(saveDialog.FileName);
            MessageBox.Show("PDF saved successfully!");
        }
    }
}
public partial class MainWindow : Window
{
    private async void GeneratePdfButton_Click(object sender, RoutedEventArgs e)
    {
        var renderer = new ChromePdfRenderer();
        var html = HtmlEditor.Text;

        var pdf = await renderer.RenderHtmlAsPdfAsync(html);

        var saveDialog = new SaveFileDialog
        {
            Filter = "PDF files (*.pdf)|*.pdf",
            DefaultExt = "pdf"
        };

        if (saveDialog.ShowDialog() == true)
        {
            pdf.SaveAs(saveDialog.FileName);
            MessageBox.Show("PDF saved successfully!");
        }
    }
}
Partial Public Class MainWindow
	Inherits Window

	Private Async Sub GeneratePdfButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
		Dim renderer = New ChromePdfRenderer()
		Dim html = HtmlEditor.Text

		Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)

		Dim saveDialog = New SaveFileDialog With {
			.Filter = "PDF files (*.pdf)|*.pdf",
			.DefaultExt = "pdf"
		}

		If saveDialog.ShowDialog() = True Then
			pdf.SaveAs(saveDialog.FileName)
			MessageBox.Show("PDF saved successfully!")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

Windows視窗

public partial class PdfGeneratorForm : Form
{
    private void btnGeneratePdf_Click(object sender, EventArgs e)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);

        using (var saveDialog = new SaveFileDialog())
        {
            saveDialog.Filter = "PDF files|*.pdf";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                pdf.SaveAs(saveDialog.FileName);
                MessageBox.Show($"PDF saved to {saveDialog.FileName}");
            }
        }
    }
}
public partial class PdfGeneratorForm : Form
{
    private void btnGeneratePdf_Click(object sender, EventArgs e)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);

        using (var saveDialog = new SaveFileDialog())
        {
            saveDialog.Filter = "PDF files|*.pdf";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                pdf.SaveAs(saveDialog.FileName);
                MessageBox.Show($"PDF saved to {saveDialog.FileName}");
            }
        }
    }
}
Partial Public Class PdfGeneratorForm
	Inherits Form

	Private Sub btnGeneratePdf_Click(ByVal sender As Object, ByVal e As EventArgs)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(txtHtml.Text)

		Using saveDialog = New SaveFileDialog()
			saveDialog.Filter = "PDF files|*.pdf"
			If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				pdf.SaveAs(saveDialog.FileName)
				MessageBox.Show($"PDF saved to {saveDialog.FileName}")
			End If
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

MAUI(多平台應用程式使用者介面)

public partial class MainPage : ContentPage
{
    public async Task GeneratePdfAsync()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync(HtmlContent);

        // Save to app's document directory
        var documentsPath = FileSystem.Current.AppDataDirectory;
        var filePath = Path.Combine(documentsPath, "output.pdf");

        await File.WriteAllBytesAsync(filePath, pdf.BinaryData);

        await DisplayAlert("Success", $"PDF saved to {filePath}", "OK");
    }
}
public partial class MainPage : ContentPage
{
    public async Task GeneratePdfAsync()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync(HtmlContent);

        // Save to app's document directory
        var documentsPath = FileSystem.Current.AppDataDirectory;
        var filePath = Path.Combine(documentsPath, "output.pdf");

        await File.WriteAllBytesAsync(filePath, pdf.BinaryData);

        await DisplayAlert("Success", $"PDF saved to {filePath}", "OK");
    }
}
Partial Public Class MainPage
	Inherits ContentPage

	Public Async Function GeneratePdfAsync() As Task
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = Await renderer.RenderHtmlAsPdfAsync(HtmlContent)

		' Save to app's document directory
		Dim documentsPath = FileSystem.Current.AppDataDirectory
		Dim filePath = Path.Combine(documentsPath, "output.pdf")

		Await File.WriteAllBytesAsync(filePath, pdf.BinaryData)

		Await DisplayAlert("Success", $"PDF saved to {filePath}", "OK")
	End Function
End Class
$vbLabelText   $csharpLabel

PDF 建立入門

準備好在 C# 應用程式中建立 PDF 了嗎? 請依照以下步驟指南,即可完成從安裝到產生第一個 PDF 檔案的整個過程。IronPdf讓您輕鬆上手,每一步都提供全面的資源和支援。

步驟 1:安裝 IronPDF

選擇最適合您開發環境的安裝方法:

Visual Studio 套件管理器**(受到推崇的)

  1. 在 Visual Studio 中開啟你的專案
  2. 在解決方案資源管理器中以滑鼠右鍵按一下您的專案。
  3. 選擇"管理 NuGet 套件"
  4. 搜尋"IronPDF"
  5. 點選 Iron Software 提供的 IronPdf 軟體包上的"安裝"按鈕。

軟體包管理器控制台**

Install-Package IronPdf

.NET CLI

dotnet add package IronPdf

NuGet 套件包含在 Windows、Linux 和 macOS 上產生 PDF 所需的一切。 對於特殊部署,請考慮使用以下針對特定平台的軟體包,這些軟體包可最佳化大小和效能:

IronPdf.Linux - 針對 Linux 環境進行了最佳化

  • IronPdf.MacOs - 原生 Apple Silicon 支持 IronPdf.Slim - 運行時下載依賴項的最小軟體包

步驟 2:建立您的第一個 PDF

首先從一個簡單的例子開始,驗證一切是否正常運作:

using IronPdf;

class Program
{
    static void Main()
    {
        // Create a new PDF generator instance
        var renderer = new ChromePdfRenderer();

        // Generate PDF from HTML
        var pdf = renderer.RenderHtmlAsPdf(@"
            <h1>Welcome to IronPDF!</h1>
            <p>This is your first generated PDF document.</p>
            <p>Created on: " + DateTime.Now + "</p>"
        );

        // Save the PDF
        pdf.SaveAs("my-first-pdf.pdf");

        Console.WriteLine("PDF created successfully!");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Create a new PDF generator instance
        var renderer = new ChromePdfRenderer();

        // Generate PDF from HTML
        var pdf = renderer.RenderHtmlAsPdf(@"
            <h1>Welcome to IronPDF!</h1>
            <p>This is your first generated PDF document.</p>
            <p>Created on: " + DateTime.Now + "</p>"
        );

        // Save the PDF
        pdf.SaveAs("my-first-pdf.pdf");

        Console.WriteLine("PDF created successfully!");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Create a new PDF generator instance
		Dim renderer = New ChromePdfRenderer()

		' Generate PDF from HTML
		Dim pdf = renderer.RenderHtmlAsPdf("
            <h1>Welcome to IronPDF!</h1>
            <p>This is your first generated PDF document.</p>
            <p>Created on: " & DateTime.Now & "</p>")

		' Save the PDF
		pdf.SaveAs("my-first-pdf.pdf")

		Console.WriteLine("PDF created successfully!")
	End Sub
End Class
$vbLabelText   $csharpLabel

步驟三:探索範例與教學課程

IronPDF 提供豐富的資源,幫助您掌握 PDF 生成技巧:

1.程式碼範例- 常見場景的即用型程式碼片段 2.教程- 特定功能的逐步指南 3.操作指南-解決實際問題的實用方案

  1. API 參考- 所有類別和方法的完整文檔

第四步:需要時尋求協助

IronPDF提供多種支援管道,確保您成功:

-全天候線上聊天支援- 與工程師即時聊天,獲得即時幫助 -電子郵件支援- 取得複雜問題的詳細解答 Stack Overflow - 社群支援和解決方案

第五步:開發與部署

免費開發許可

IronPDF 可免費用於開發和測試。 在開發過程中,您可以不受任何限制地探索所有功能。 開發模式下產生的 PDF 檔案上會顯示浮水印,但不會影響其功能。

生產部署選項

當您準備將產品部署到生產環境時,IronPDF 提供靈活的許可方式:

1.免費試用- 取得 30 天試用許可證,可在生產環境中進行測試,無浮水印 2.商業許可- 單一項目部署的$799 3.企業解決方案- 為大型組織量身訂製的軟體包

要在程式碼中套用許可證:

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

第六步:保持更新

保持您的PDF生成功能處於最新狀態:

訂閱更新- 取得新功能和改進的通知 -關注部落格- 了解最佳實踐和新技術 -查看更新日誌- 查看每個版本新增的內容

定期更新可確保與最新的 .NET 版本相容,並包含效能改進、新功能和安全性更新。

為什麼選擇IronPdf進行 C# 中的 PDF 產生?

在探索了使用 C# 建立 PDF 的各種方法之後,你可能會想知道是什麼讓IronPdf成為許多開發人員的首選。 這不僅關乎功能,而是關乎整個開發者體驗,從初始實現到長期維護,當您需要在 .NET 中產生 PDF時,都會涉及這方面。 全球有超過 1400 萬開發者使用IronPdf作為他們的C# PDF 生成器,它已成為 .NET 應用程式中PDF 生成的實際標準。 讓我們來探討為什麼開發人員選擇IronPdf來滿足他們在 C# 中建立 PDF 的需求。

像素級完美渲染

與其他產生 HTML 設計近似值的 PDF 庫不同,IronPDF 使用真正的 Chromium 引擎,以確保您的 PDF 文件看起來與在現代 Web 瀏覽器中完全一樣。 正是這種像素級精確渲染能力,使得金融機構信賴IronPdf來產生對精確度要求極高的監理報告。 您的CSS Grid 佈局flexbox 設計JavaScript 渲染的內容都運作完美。 建立 PDF 文件時,無需再與專有佈局引擎作鬥爭,也無需再接受"差不多就行"的結果。

開發者友善 API

IronPDF 的 API由開發者設計,服務開發者。 由於 API 的簡單性,新創公司可以在幾個小時內(而不是幾天內)實現PDF 生成功能。 無需學習複雜的PDF規範,您只需運用熟悉的概念

using IronPdf;

// Other libraries might require this:
// document.Add(new Paragraph("Hello World"));
// document.Add(new Table(3, 2));
// cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);

// With IronPDF, just use HTML:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
    <h1>Hello World</h1>
    <table>
        <tr style='background: lightgray;'>
            <td>Simple</td>
            <td>Intuitive</td>
        </tr>
    </table>
");
using IronPdf;

// Other libraries might require this:
// document.Add(new Paragraph("Hello World"));
// document.Add(new Table(3, 2));
// cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);

// With IronPDF, just use HTML:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
    <h1>Hello World</h1>
    <table>
        <tr style='background: lightgray;'>
            <td>Simple</td>
            <td>Intuitive</td>
        </tr>
    </table>
");
Imports IronPdf

' Other libraries might require this:
' document.Add(new Paragraph("Hello World"));
' document.Add(new Table(3, 2));
' cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);

' With IronPDF, just use HTML:
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("
    <h1>Hello World</h1>
    <table>
        <tr style='background: lightgray;'>
            <td>Simple</td>
            <td>Intuitive</td>
        </tr>
    </table>
")
$vbLabelText   $csharpLabel

企業級功能

IronPDF 具備企業應用程式所需的功能,因此財富 500 強企業都依賴它來產生關鍵任務文件

-安全性:加密、數位簽章和權限控制保護敏感文檔 -合規性PDF/APDF/UA支援確保您產生的 PDF符合法規要求 -效能:非同步操作和批次處理能夠有效率地處理數百萬份文件。 -可靠性:完善的錯誤處理和日誌記錄機制有助於維持生產環境的正常運作時間。

傑出支持

當您需要協助時,IronPDF 的支援團隊由真正的工程師組成,他們了解您面臨的挑戰。 我們提供全天候線上聊天支持,通常響應時間不到 30 秒,您無需長時間等待即可獲得答案。 正是這種程度的支持,使得開發者們一直將IronPdf評為業界支援最好的公司。 支援團隊可以協助您解決從基本問題到複雜實施難題的一切問題,確保您的PDF 生成專案成功。

透明定價

沒有隱藏費用沒有意外支出沒有伺服器授權方面的複雜問題。IronPdf的許可模式簡單明了,這意味著您可以清楚地知道自己支付的費用包含哪些內容。 開發始終免費,生產許可證是永久的——您將永遠擁有它們。 在以複雜的許可製度著稱的行業中,這種透明度令人耳目一新。

積極發展

IronPDF 透過每月更新不斷改進,增加功能、提高效能並確保與最新的 .NET 版本相容。 團隊積極關注客戶回饋,並定期實施客戶要求的功能。 近期新增功能包括增強的表單處理、改進的PDF 編輯功能以及針對雲端部署的最佳化。

真實世界的成功案例

各行各業數千家公司信賴IronPdf來產生關鍵任務型 PDF 檔案

-金融領域:銀行每月使用IronPdf的安全文件功能產生數百萬份報表和報告。 -醫療保健:醫院使用符合 HIPAA 標準的安全設定建立病患記錄和化驗結果。 -電子商務:線上零售商大規模產生發票和出貨標籤,輕鬆應對高峰期訂單量。 政府機構:各機構產生具有數位簽章和加密功能的官方文件和表格。

這些機構選擇IronPdf是因為它能夠大規模地提供一致的結果——無論是產生單一發票還是每天處理數百萬份文件。

IronPdf與其他 C# PDF 程式庫相比如何?

在 C# 中產生 PDF時,選擇合適的PDF 庫對於專案的成功至關重要。 讓我們來看看IronPdf與.NET 生態系統中其他流行的PDF 創建選項相比如何。 此比較基於實際使用情況、開發人員回饋以及希望在 .NET 中建立 PDF 的技術能力。 了解這些差異有助於您根據自身需求選擇最佳的C# PDF 產生器

對比表

特點IronPdfwkhtmltopdfQuestPDFiText 7PdfSharp融合Aspose.PDF
HTML 轉 PDF 質量像素級完美印刷風格不適用限額無HTML好的好的
HTML5/CSS3 支持全文過時的僅代碼部分的全文全文
JavaScript 支援全文限額限額限額
易用性3 行僅限命令列介面程式碼優先複雜的低等級好的複雜的
伺服器依賴項執行檔
表現快速 + 非同步慢的快速地快速地快速地快速地快速地
積極發展非常活躍積極的積極的極簡主義積極的積極的
許可證類型商業的開源麻省理工學院→商業*AGPL/商業商業的商業的
起價$799自由的599美元起*$2,399 +自由的2,995美元以上2,499美元以上

*註:QuestPDF 最近已從 和 許可變更為商業許可。

詳細比較

IronPdf與 wkhtmltopdf

-wkhtmltopdf雖然免費,但已於 2020 年停止維護,生成的 PDF 文件看起來過時。

  • 需要特定於平台的可執行文件,這使得部署變得複雜。 不支援 JavaScript 意味著現代 Web 應用程式將無法正確渲染。 IronPDF 提供無需外部依賴的現代化渲染功能

IronPdf對比 QuestPDF

QuestPDF 要求完全使用 C# 程式碼建立 PDF,不支援 HTML。

  • 適合程式化建立 PDF 文件,但處理複雜佈局比較耗時
  • 最近已從 和 許可切換到商業許可。 IronPDF 讓您能夠運用您已有的 HTML/CSS 技能。

IronPdf與 iText 7 的比較

iText 採用 AGPL 許可,這可能會"影響"您的程式碼庫。 商業許可起價為 1,999 美元,定價機制較為複雜。

  • HTML 轉 PDF 功能有限,CSS 支援較差 IronPDF 以更低的價格提供卓越的 HTML 渲染效果。

IronPdf與 PdfSharp

PdfSharp 非常適合底層 PDF 處理,但完全不支援 HTML。

  • 需要手動定位頁面上的每個元素
  • 免費開源,但功能非常有限 IronPDF 既能處理進階 HTML 操作,也能處理低階 PDF 操作。

IronPdf與 Syncfusion/Aspose.PDF 的比較

兩者都是企業級解決方案,功能強大,但價格較高。 Syncfusion 起價為 2,995 美元,Aspose 起價為 2,499 美元。 兩者都無法像IronPdf那樣實現像素級完美的 HTML 渲染。 IronPDF 在提供同等企業級功能的同時,也能提供更高的性價比。

遷移路徑

許多開發者從其他庫轉而使用 IronPDF。 原因如下

從 wkhtmltopdf

"我們厭倦了處理特定平台的二進位和過時的渲染方式。" "IronPDF 為我們提供了現代化的 CSS 支持,並解決了我們 Docker 方面的難題。"

來自 iTextSharp/iText 7

"學習曲線嚴重影響了我們的工作效率——IronPDF 讓我們能夠使用 HTML 來代替它。" "AGPL許可協議對我們的商業產品來說是致命的缺陷。"

來自 PdfSharp

"我們需要將 HTML 轉換為 PDF,而 PdfSharp 根本無法做到這一點。" "手動定位每個元素太費時了。"

來自 QuestPDF

"與使用 HTML/CSS 相比,用 C# 程式碼建立佈局非常繁瑣。" "最近的許可證變更讓我們重新考慮了我們的選擇。"

結論

用 C# 建立 PDF並不一定很複雜。 使用 IronPDF,您可以利用您現有的 HTML 和 CSS 技能來產生專業的 PDF 文件。 無論您是建立簡單的報告還是包含圖表和表單的複雜文檔,IronPDF 都能處理繁重的工作,讓您可以專注於應用程式邏輯。 加入全球 1,400 萬開發者的行列,他們信賴IronPdf作為C# PDF 產生器,能夠可靠且有效率地產生 PDF 文件

在本指南中,我們探討如何使用多種方法建立 PDF 文件-從 HTML 字串和 URL 到轉換現有文件(如 Word 文件和 Markdown)。 我們已經看到 IronPDF基於 Chromium 的現代渲染引擎如何產生像素級完美的效果,使其看起來真正像您的網頁設計,而不是過時的列印輸出。IronPdf能夠以程式設計方式操作 PDF 文件、新增安全功能並優化效能,使其成為 .NET 中所有PDF 生成任務完整解決方案

IronPDF 的獨特之處在於其以開發者為先的方法。 只需三行程式碼,即可產生您的第一個 PDF 檔案。 直覺的 API 意味著您可以減少學習專有 PDF 語法的時間,從而將更多時間用於建立功能。IronPdf結合了真正的工程師提供的出色支援透明的定價持續的更新(包括對 .NET 10 的預發布支援),讓您確信您在 C# 創建的 PDF現在和將來都能正常工作。

立即開始建立 PDF -取得免費試用許可證,了解在 .NET 中為您的應用程式產生 PDF有多麼容易。 使用 IronPDF,您只需幾分鐘即可產生專業的 PDF 文件,而無需花費數小時。

準備好創建你的第一個 PDF 檔案了嗎?**立即開始使用IronPdf吧——它對開發是免費的,你可以在幾分鐘內**用 C# 建立 PDF 文件

請注意Aspose、iText、wkhtmltopdf、QuestPDF、PdfSharp 和 SyncFusion 為其各自所有者的註冊商標。 本網站與 Aspose、iText、wkhtmltopdf、QuestPDF、PdfSharp 或 SyncFusion 沒有任何關聯,也未獲得其認可或贊助。 所有產品名稱、標誌和品牌均為其各自擁有者的財產。 提供的比較資料僅供參考,並基於撰寫時的公開資訊。

常見問題解答

如何在 C# 中從 HTML 內容創建 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法在 C# 中從 HTML 內容創建 PDF。這使您能夠輕鬆地將 HTML 字符串或 URL 直接轉換為 PDF 文件。

使用商業 PDF 庫比免費 PDF 庫有什麼優勢?

商業 PDF 庫如 IronPDF 提供強大的功能,比如完全支持 JavaScript、CSS3 和響應式佈局。它們提供可靠的性能、定期更新、全面的支持,並針對創建高質量 PDF 進行了優化。

IronPDF 可以用於生成 ASP.NET MVC 應用程序中的 PDF 文件嗎?

是的,IronPDF 可以在 ASP.NET MVC 應用程序中使用,將 Razor 視圖或 HTML 模板轉換為 PDF,允許將 PDF 生成無縫集成到您的 Web 應用程序中。

如何使用 C# 在我的 PDF 文檔中集成圖像和 CSS?

使用 IronPDF,您可以輕鬆地將圖像和 CSS 集成到您的 PDF 文檔中。這可以通過在您的 HTML 內容中包含圖像標記和 CSS 樣式來實現,然後使用 IronPDF 的渲染功能將其轉換為 PDF。

在 C# 中,可以向 PDF 添加頁眉、頁腳和頁碼嗎?

是的,IronPDF 提供了先進的功能,允許您向 PDF 文檔添加頁眉、頁腳和頁碼。這可以通過在渲染 HTML 內容之前配置 PDF 設置來完成。

在生成 C# PDF 時,如何處理 XML 數據?

使用 IronPDF,您可以通過將 XML 轉換為 HTML 或使用 XSLT 來為 XML 數據設置樣式,然後使用 IronPDF 的 RenderHtmlAsPdf 方法將其轉換為 PDF 文件。

在 C# 中生成 PDF 時有哪些常見挑戰?

常見的挑戰包括保持佈局的一致性、處理複雜的 CSS 和 JavaScript 以及確保對 Web 技術的準確渲染。IronPDF 通過其現代的 Chromium 引擎和 HTML5 及 CSS3 標準的廣泛支持來應對這些挑戰。

如何使用 C# 高效地生成大型 PDF?

IronPDF 被設計用於高效地處理大型 PDF 的生成。它使用高性能的渲染引擎並支持異步操作以輕鬆管理大量文檔。

我可以在沒有商業許可證的情況下測試 IronPDF 嗎?

是的,IronPDF 提供免費許可證,用於開發和測試目的,使您能在購買商業許可證以作為生產用途之前評估其功能。

.NET 10 兼容性:IronPDF 可以在 .NET 10 中使用嗎?有什麼特別的考量嗎?

是的,IronPDF 與 .NET 10 完全相容。它開箱即支持 .NET 10,包括在針對 Windows、Linux、容器化環境和 .NET Framework 的專案中。不需要特殊配置,只需安裝最新的 IronPDF NuGet 包,它就能與 .NET 10 無縫配合。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。