A PHP Error was encountered

Severity: Warning

Message: count(): Parameter must be an array or an object that implements Countable

Filename: libraries/StructuredData.php

Line Number: 618

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 618
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 661
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2680
Function: buildWebPageSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: libraries/StructuredData.php

Line Number: 621

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 621
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 661
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2680
Function: buildWebPageSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: libraries/StructuredData.php

Line Number: 623

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 623
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 661
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2680
Function: buildWebPageSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: libraries/StructuredData.php

Line Number: 624

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 624
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 661
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2680
Function: buildWebPageSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: count(): Parameter must be an array or an object that implements Countable

Filename: libraries/StructuredData.php

Line Number: 618

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 618
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1487
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: libraries/StructuredData.php

Line Number: 621

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 621
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1487
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: libraries/StructuredData.php

Line Number: 623

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 623
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1487
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: libraries/StructuredData.php

Line Number: 624

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 624
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1487
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: count(): Parameter must be an array or an object that implements Countable

Filename: libraries/StructuredData.php

Line Number: 618

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 618
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1256
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 815
Function: buildSingleDocArticleSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1520
Function: buildHowToSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: libraries/StructuredData.php

Line Number: 621

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 621
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1256
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 815
Function: buildSingleDocArticleSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1520
Function: buildHowToSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: libraries/StructuredData.php

Line Number: 623

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 623
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1256
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 815
Function: buildSingleDocArticleSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1520
Function: buildHowToSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: libraries/StructuredData.php

Line Number: 624

Backtrace:

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 624
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1256
Function: getWebPageAuthor

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 815
Function: buildSingleDocArticleSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 1520
Function: buildHowToSchema

File: /var/www/ironpdf.com/application/libraries/StructuredData.php
Line: 2701
Function: buildBlogPostSchema

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 354
Function: setJsonLDStructuredData

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

跳過到頁腳內容
如何在 .NET 6 中產生 PDF 文件

C#創建PDF(代碼示例教程)

常見問題解答

如何使用 C# 從 HTML 內容建立 PDF?

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

使用商業 PDF 庫相比免費 PDF 庫有哪些優勢?

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

IronPDF 能否用於在 ASP.NET MVC 應用程式中產生 PDF 檔案?

是的,IronPDF 可用於 ASP.NET MVC 應用程序,將 Razor 視圖或 HTML 模板轉換為 PDF,從而將 PDF 生成無縫整合到您的 Web 應用程式中。

如何使用 C# 將圖像和 CSS 整合到我的 PDF 文件中?

使用 IronPDF,您可以輕鬆地將圖像和 CSS 整合到 PDF 文件中。只需在 HTML 內容中包含圖像標籤和 CSS 樣式,然後使用 IronPDF 的渲染功能將其轉換為 PDF 即可實現這一點。

是否可以在 C# 中為 PDF 新增頁首、頁尾和頁碼?

是的,IronPDF 提供進階功能,可讓您為 PDF 文件新增頁首、頁尾和頁碼。這可以透過在渲染 HTML 內容之前配置 PDF 設定來實現。

在C#中產生PDF時,如何處理XML資料?

使用 IronPDF,您可以處理 XML 數據,方法是將 XML 轉換為 HTML 或使用 XSLT 對 XML 進行樣式設置,然後可以使用 IronPDF 的RenderHtmlAsPdf方法將其轉換為 PDF 文件。

在 C# 中產生 PDF 時,常見的挑戰有哪些?

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

如何使用 C# 高效率地產生大型 PDF 檔案?

IronPDF 旨在高效處理大型 PDF 文件的產生。它採用高效能渲染引擎,並支援非同步操作,可以輕鬆管理大型文件。

我可以在沒有商業授權的情況下試用 IronPDF 嗎?

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

.NET 10 相容性:我可以在 .NET 10 中使用 IronPDF 嗎?有什麼特殊注意事項嗎?

是的,IronPDF 完全相容於 .NET 10。它開箱即用,支援包括 Windows、Linux、容器化環境和 Web 框架的專案在內的所有 .NET 10 環境。無需任何特殊配置——只需安裝最新的 IronPDF NuGet 包,即可與 .NET 10 無縫協作。

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: sections/author_component.php

Line Number: 18

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 18
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/blog/main_post.php
Line: 40
Function: main_view

File: /var/www/ironpdf.com/application/views/products/blog/blog_post.php
Line: 24
Function: include

File: /var/www/ironpdf.com/application/views/products/blog/index.php
Line: 83
Function: include

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: sections/author_component.php

Line Number: 38

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 38
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/blog/main_post.php
Line: 40
Function: main_view

File: /var/www/ironpdf.com/application/views/products/blog/blog_post.php
Line: 24
Function: include

File: /var/www/ironpdf.com/application/views/products/blog/index.php
Line: 83
Function: include

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: sections/author_component.php

Line Number: 48

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 48
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/blog/main_post.php
Line: 40
Function: main_view

File: /var/www/ironpdf.com/application/views/products/blog/blog_post.php
Line: 24
Function: include

File: /var/www/ironpdf.com/application/views/products/blog/index.php
Line: 83
Function: include

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Blog.php
Line: 77
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

相關文章

使用IRONPDF

在 C# 中創建 PDF 是現代 .NET 開發人員的一項基本技能,無論您是構建財務報告、生成醫療文件還是製作電子商務收據。使用正確的 .NET PDF 庫,您可以將 HTML 內容轉換為專業的 PDF 文件,只需幾行代碼即可完成,讓您完全控制文檔結構和外觀。

IronPDF 是目前為止最簡單、最易用的 .NET PDF 創建庫 - 擁有令人難以置信的簡單學習曲線,讓您在幾分鐘內(而不是幾小時)生成 PDF。 這本綜合指南將向您展示如何使用IronPDF在 C# 中創建 PDF 文件 - 一個強大的 C# PDF 生成器,生成像素完美的結果,支持所有現代 .NET 平台,包括 2025 年 11 月即將推出的 .NET 10 版本。雖然本教程涵蓋了從最簡單的用例到最先進的PDF 生成場景,但不要氣餒 - 從頭開始並向前推進。 您將學習多種方法來生成 PDF,從簡單的 HTML 字符串到複雜的多頁報告,以及如何排解常見問題,為各種PDF 生成任務優化性能。

role="alert"> 當您需要幫助時,IronPDF 的支持團隊由了解您挑戰的實際工程師組成。憑藉 24 小時/ 7 天在線支持 以及低於 30 秒的平均響應時間,您永遠不會等待答复。這種支持水平是開發人員一致認為IronPDF擁有該行業最佳支持的原因。支持團隊可以幫助處理一切 # 如何在 C# 中創建 PDF - .NET 中 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 合規性。 電子商務平台生成PDF 收據、發貨標籤和包含 QR 碼(使用像 IronQR 之類的工具)的票據直接嵌入在 PDF 中。 以程序編寫方式操作 PDF 文件的能力意味著您可以創建、修改和大規模地安全文件而無需人工干預。

使用現代.NET PDF 庫(如 IronPDF)的美妙之處在於它能無縫整合到您的組織現有的工作流程中。 Whether you're converting Word documents from your business users, transforming Markdown documentation from your development team, or generating PDFs from web-based reports,IronPDFhandles it all. 這種組織靈活性是公司選擇基於程式化的.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 Foundation 和 Microsoft 密切合作,以確保當天兼容性)。 設置過程很簡單,但了解您的選擇有助於您選擇最適合您的特定需求的最佳方法

安裝方法

方法 1:Visual Studio 程序包管理器(適合初學者的推薦方法)

最簡單的開始使用IronPDF的方式 是通過 Visual Studio 的內置 NuGet 程序包管理器。 這個圖形界面使瀏覽、安裝和管理您 PDF 生成的依賴項變得簡單易行:

  1. 右鍵單擊 Solution Explorer 中的項目
  2. 選擇“管理 NuGet 包”
  3. 點擊“瀏覽”並搜索“IronPDF”
  4. 選擇由 Iron Software 提供的 IronPdf 包
  5. 點擊安裝並接受許可協議
包管理控制台

方法 2:程序包管理控制台

對於更喜歡命令行工具的開發人員,程序包管理控制台提供了一種快速安裝IronPDF的方式:

Install-Package IronPdf

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

如果您正在 macOS、Linux 上工作或偏好 .NET CLI,請在您的專案目錄中使用此命令:

dotnet add package IronPdf

選擇合適的包

IronPDF 提供不同的 NuGet 包,以針對不同的部署場景進行優化。 了解這些選項可以幫助您最小化部署大小優化性能

  • IronPdf:適用於 Windows、macOS 和 Linux 的標準包,包含所需的一切。適用於大多數應用程序。 - IronPdf.Slim:輕量基礎包,在運行時下載平台特定的組件,非常適合雲部署,當包大小至關重要時。
  • IronPdf.Linux:專為 Linux 部署而優化,並預打包所有必要的依賴項。
  • IronPdf.MacOs:專為 macOS 環境設計,具有本地蘋果矽支持。
    請注意對於在 Azure、AWS 或 Docker 上的雲部署,考慮使用 IronPdf.Slim 以減少容器大小。所需的組件會在首次使用時自動下載。

驗證您的安裝

安裝後,使用這個簡單的測試來驗證一切是否正常運行,該測試將創建一個新文件:

在 C# 中生成 PDF 的不同方法是什麼?

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

IronPDF 提供了多種方法構建 PDF 文件,每種方法都適合不同的場景和需求。

了解這些方法有助於您選擇最有效的方法,用於特定用途,在您需要在 .NET 中生成 PDF時。 無論您是在從頭開始以HTML 字符串創建 PDF、轉換現有文件還是捕捉實時 Web 內容,IronPDF 作為一個全面的C# PDF 生成器都能滿足您的需求。 讓我們以實用示例來詳細探討每種方法,以展示 C# 中PDF 創建的真實應用場景。 ### 1. 從 HTML 字符串創建 PDF(最靈活)

從 HTML 字符串創建 PDF 使您在將HTML 內容轉換為 PDF 格式時對最終文檔的內容和樣式擁有完全控制

這種方法適合用於生成動態報告、發票或任何因數據變更而內容發生變化的文件。 您可以使用現代 HTML5 和 CSS3 功能 - 包括 flexbox 和 grid 布局 - 將 HTML 內容轉換為專業的 PDF。 能夠動態轉換 HTML 內容使得 C# 中的PDF 創建方法變得非常靈活: ### 2. 從 URL 生成 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

有時候您需要將現有的網頁轉換為 PDF 文檔 - 非常適合歸檔、報告或創建在線內容的離線版本。

IronPDF 的 URL 到 PDF 轉換使用真正的 Chromium 引擎,確保 JavaScript 繁重的網站正確渲染。 此方法對於創建儀表板快照、保存在線收據或列印基於 Web 報告非常有價值:

URL 到 PDF 示例

3. 從 HTML 文件創建 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");
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

當您擁有可以獨立於應用程式代碼進行維護的複雜布局時,基於模板的 PDF 生成是理想的選擇。

通過將 HTML 模板作為文件儲存,您可以實現設計和邏輯的清晰分離。 這種方法在生成一致的文件(例如證書、合同或標準化的報告)時效果特別好:

HTML 文件到 PDF

4. 將 Markdown 轉換為 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

Markdown 已成為技術文檔、README 文件和內容管理系統的標準

IronPDF 使其易於將 Markdown 內容直接轉換為 PDF,同時在創建具有專業外觀的文件時保留格式。 此功能對於那些以 Markdown 格式維護其文檔的組織特別有價值 - 開發人員可以以其偏好的格式撰寫文檔,而系統可以自動生成 PDF以供客戶或利益相關者分發。 Markdown 到 PDF 的轉換對於使用如 Git 等版本控制系統的組織特別有用

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 文件,CI/CD 管道自動生成 PDF 文件,利益相關者收到具有專業格式的文檔而無需手動干預。 這種無縫整合進入現有工作流程是許多開發團隊選擇IronPDF作為其文檔需求的原因。 ### 5. 將 Word 文件 (DOCX) 轉換為 PDF

許多企業擁有需轉換為 PDF 以便分發或歸檔的現有 Word 文件。

IronPDF 提供的無縫 DOCX 到 PDF 轉換保持格式、圖像,甚至複雜的功能如郵件合併。 這一功能對企業具有變革意義 - 業務用戶可以繼續在熟悉的 Microsoft Word 中工作,而系統可以自動生成 PDF以供外部分發。 DOCX 到 PDF 轉換功能填補了偏愛使用 Word 的業務用戶與對安全、無法編輯的 PDF 文檔需求之間的空白。 此 DOCX 轉換功能在組織內部對自動化文檔工作流程無價

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

考慮一個銷售團隊在 Word 中創建提案 - 使用 IronPDF,這些提案可以自動轉換為帶有水印、安保設置以及以程序方式應用的數字簽名的 PDF。 郵件合併功能使得批量生成個性化 PDF 文件成為可能 - 非常適合生成數千份定制化的信件、證書或合同而無需人工干預。 這種集成能力是全球企業信賴IronPDF處理其文檔自動化需求的原因。 ### 6. 將圖像轉換為 PDF

將圖像轉換為 PDF 對於創建照片集、掃描文件匯編或基於圖像的報告來說是必不可少的。

IronPDF 支持所有主要圖像格式並提供控制布局和質量的選項: ### 7. 從 ASP.NET 頁面生成 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");
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

對於網絡應用程序,從現有視圖生成PDF提供了一種無縫的方式來創建可下載的網絡內容版本。

此整合功能對需要從其 Web 應用程序創建 PDF的組織至關重要 - 無論是客戶門戶生成報表,管理儀錶板出具報告,還是電子學習平台創建證書。IronPDF可與所有 ASP.NET 技術 (包括 MVC、Razor Pages 和 Blazor) 一起使用,使其成為已投資於微軟生態系統的組織的完美選擇: ## 如何讓我的 PDF 看起來更專業?

// 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 是一回事 - 在 .NET 中生成 PDF時,讓它們看起來專業是將您的應用程序與眾不同的關鍵。

專業的 PDF 文檔需要在佈局、排版和品牌一致方面注重細節,以創造正確的印象。 使用IronPDF的綜合樣式選項和高級 PDF 功能,您可以使用這個強大的C# PDF 生成器,創建完全匹配您的企業形象的文件。 HTML 到 PDF 轉換能力確保您的樣式文件在製作為 PDF 時保持其視覺吸引力。 讓我們探討將基本 PDF 轉變為拋光、專業文檔並給客戶和利益相關者留下深刻印象的功能。 ### 頁眉、頁腳和頁碼

專業文件需要一致的頁眉和頁腳,提供上下文和導航。

IronPDF 提供簡單的基於文本和複雜的基於 HTML 的頁眉和頁腳選項。 這種靈活性是組織需要在大規模生成品牌 PDF時選擇IronPDF的原因。 您可以包含動態內容,如頁碼、日期和文檔標題 - 確保每個生成的 PDF都保持專業標準: 這些頁眉和頁腳選項使組織能夠在所有生成的 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

無論您是創建財務報告還是技術文檔,專業的頁眉和頁腳可以確保您的文檔符合企業標準。 ### 高級頁面設置和佈局控制

對頁面佈局的控制對於創建在所有設備上正確打印並顯示專業的文件至關重要。

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 支持 Web 字體、定制字體和高級排版功能: ## 實例:我如何生成發票 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");
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 文件的最佳實踐。

這個例子展示了為什麼數千家公司選擇IronPDF作為其C# PDF 生成器來滿足發票生成需求 - 它結合了數據綁定、專業樣式和適當的文件結構,既強大又可維護。 類似的實現被電子商務平台使用,以便每月創建數百萬張發票,證明了程式化PDF 生成在 .NET中的可擴展性。 你可以調整這段代碼來實現自己的PDF 創建任務: ##IronPDF提供哪些高級 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 超越了基本的在 C# 中創建 PDF,提供高級功能,可以啟用複雜的文檔工作流程和企業級功能。

這些高級能力使您能夠創建交互表單、保護敏感文檔,並在您在 .NET 中構建 PDF時精確操作現有 PDF。 這些功能是超過 1400 萬開發人員在全球範圍內信賴IronPDF作為其關鍵任務PDF 生成需求的原因。 了解這些功能有助於您構建滿足各種要求的綜合 PDF 解決方案 - 從創建可填寫表單到在以 C# 創建 PDF 的項目中實施企業級安全。 ### 生成交互式 PDF 表單

以程序化方式創建可填寫的 PDF 表單可以自動化數據收集和文件工作流程。

IronPDF 可以將 HTML 表單轉換為用戶可以在任何 PDF 閱讀器中填寫的互動式 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

當處理敏感文件時,安全性至關重要

IronPDF 提供全面的安全功能,保護您的 PDF 文件免受未授權的訪問或修改: ### 合併和拆分 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 或提取特定頁面對於文件管理工作流來說至關重要

添加水印和印章

// 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 支持文本和圖像水印: ## 如何在大規模生成 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
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 生成代碼可以顯著提高吞吐量並減少資源消耗。 現代應用程序需要高效的在 C# 中創建 PDF,不會阻塞線程或消耗過多內存。 這裡有驗證過的策略,用於在不同的 PDF 生成任務中最大化性能,當您在 .NET 中需要高效生成 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

通過緩存常見元素和優化模板來加快渲染時間:

創建 PDF 時常見問題是什麼,我該如何解決?

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

即使使用像IronPDF這樣強大的.NET PDF 庫,當您在 C# 中構建 PDF時,也可能會在開發或部署過程中遇到挑戰。

了解常見問題及其解決方案有助於您快速解決問題,並保持順暢PDF 生成作業。 好消息是,隨著超過 1400 萬開發人員在使用IronPDF作為他們的C# PDF 生成器,大多數問題已經被遇到並解決過。 此故障排除指南涵蓋了開發人員在.NET 中創建 PDF時面臨的最常見問題,並根據實際經驗提供實用解決方案。 記住,隨時提供 24/7 支持,如果您需要立即解決你的PDF 創建挑戰。 ### 問題 1:渲染失敗或空白 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 映像中不存在。

以下為解決常見部署問題的方法: 專門針對 Google Cloud Run:

# 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"]

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

// 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

問題 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

問題 5:字體和編碼問題

當涉及國際化內容或自定義字體時:

獲得幫助

// 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. 24/7 在線支持 - 與工程師實時對話,平均響應時間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 的雲端環境。 Understanding platform-specific considerations helps ensure smooth deployments across your infrastructure - whether that's on-premise servers or cloud environments where you need to build PDFs with C#.

IronPDF 支持所有現代 .NET 版本,並會不斷更新以支持最新的發布版本:

  • .NET 8 - 完整支持所有功能

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

    操作系統支持

在任何主要操作系統上部署您的 PDF 生成解決方案:

  • Alpine Linux(需額外配置)

  • Alpine Linux(需額外配置)

  • Alpine Linux(需額外配置)
  • Alpine Linux(需額外配置)

  • Alpine Linux(需額外配置)

  • Alpine Linux(需額外配置)
  • Alpine Linux(需額外配置)
  • Alpine Linux(需額外配置)
  • Alpine Linux(需額外配置)
  • macOS 13(Ventura)及更新版本

  • macOS 13(Ventura)及更新版本

  • 原生支持蘋果矽(M1/M2/M3)
  • 完全支持基於 Intel 的 Mac

雲平台部署

IronPDF 在所有主要雲平台上運行流暢:

微軟 Azure

亞馬遜網路服務(AWS)

// 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

Google 雲平台

// 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

容器部署(Docker/Kubernetes)

# 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

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 繪圖基礎)

MAUI(多平台應用 UI)

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

MAUI(多平台應用 UI)

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

創建 PDF 的入門指南

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

準備好在您的 C# 應用程序中開始創建 PDF 嗎?

按照此分步指南,您將從安裝到您的第一個生成的 PDF。IronPDF讓您可以輕鬆入門,並在每一步都有全面的資源和支持。 ### 步驟 1:安裝 IronPDF

Step 1: Install 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

步驟 3:探索範例和教程

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

  1. 程式碼範例 - 現成的代碼片段供常見場景使用
  2. 教程 - 針對特定功能的逐步指南
  3. 操作指南 - 真實情況問題的實用解決方案
  4. API 參考 - 全面的類和方法文檔

步驟 4:在需要時獲取幫助

IronPDF 提供多種支援途徑確保您的成功:

步驟 5:開發和部署

免費開發許可

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

步驟 6:保持更新

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

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

為什麼選擇IronPDF在 C# 中生成 PDF?

在探索了各種 創建 PDF 的方法 之後,您可能會想知道為什麼IronPDF是許多開發者的 首選。 這不僅僅是關於功能,還涉及到從初始實施到長期維護,當您需要用 .NET 生成 PDF 時的整體開發者體驗。 全球超過1400萬開發者使用IronPDF作為其 C# PDF 生成工具,它已經成為 PDF 生成 在 .NET 應用中事實上的標準。 讓我們來看看為什麼開發者選擇IronPDF滿足他們的C# 中的 PDF 創建需求。

像素完美的渲染

與其他生成近似於您的 HTML 設計的 PDF 庫不同,IronPDF 使用真正的 Chromium 引擎,確保您的 PDF 看起來完全相同於現代網頁瀏覽器中。 這種像素完美的渲染能力是金融機構為確保精確生成 合規報告 時為什麼信任IronPDF的原因。 您的 CSS 網格佈局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 強公司依賴它來處理關鍵任務的文件生成

  • 安全性:加密、數位簽名和許可權控管保護敏感文檔
  • Compliance: PDF/A and PDF/UA support ensures your generated PDFs meet regulatory requirements
  • 性能:異步操作和批量處理可高效應對數百萬份文件
  • 可靠性:大量錯誤處理和日誌記錄幫助維持生產中的穩定性

卓越支持

當您需要幫助時,IronPDF 的支援團隊由真正的工程師組成,他們了解您的挑戰。 具有 24/7 即時聊天支持30 秒以內的典型響應時間,您不會被卡住並等待答案。 這種支援水平是開發者一致評價IronPDF擁有業界最佳支持的原因。 支持團隊可以在從基本問題到複雜實施挑戰的過程中提供幫助,確保您的PDF 生成專案獲得成功。

透明的定價

無隱藏費用無驚喜費用無伺服器許可的複雜問題。IronPDF簡單明瞭的許可模式意味著您清楚地知道您支付了什麼。 開發永遠免費,並且生產的許可是永久的——您可以永遠擁有它們。 在一個以複雜許可方案聞名的行業中,這種透明性令人耳目一新。

積極開發

IronPDF 不斷改進,每月增添新功能、提升性能,並確保與最新 .NET 釋放的相容性。 團隊積極監控客戶反饋並定期實施請求的功能。 Recent additions include enhanced form handling, improved PDF editing capabilities, and optimizations for cloud deployments.

實際成功故事

數以千計的公司在各行各業中信任IronPDF處理關鍵任務的PDF 生成

  • 金融:銀行每月使用IronPDF的安全文件功能生成數百萬份報告和報告
  • 健康醫療:醫院使用 HIPAA 合規的安全設置 創建病人記錄和化驗結果
  • 電子商務:線上零售商大規模生成發票和運單,輕鬆處理高峰負載
  • 政府:機構使用數位簽名和加密生成官方文件和表格

這些組織選擇 IronPDF,因為它能在規模化的情況下提供一致的結果——無論是生成單個發票還是每天處理數百萬份文檔。

IronPDF如何與其他 C# PDF 庫進行比較?

當您需要 用 C# 生成 PDF 時,選擇正確的 PDF 庫 對您專案的成功至關重要。 讓我們來看看IronPDF如何在 .NET 生態系統 中相較其他受歡迎的選項進行 PDF 創建。 這些比較基於實際使用、開發者反饋以及技術能力,以幫助尋找 建立 PDF 的開發者**最佳化選擇。 了解這些差異有助於您根據您的具體需求選擇最好的 C# PDF 生成工具**。

比對表

功能 IronPDF wkhtmltopdf QuestPDF iText 7 PdfSharp Syncfusion Aspose.PDF
HTML 到 PDF 的質量 像素完美 打印風格 不適用 有限 無 HTML
HTML5/CSS3 支持 全面 過時 讚只能是代碼 部分 全面 全面
JavaScript 支援 全面 有限 有限 有限
易用性 3 行 只有命令行為 代碼優先 複雜 低級 複雜
伺服器依賴性 可執行
性能 快 + 異步
積極開發 非常積極 已放棄 積極 積極 極少 積極 積極
許可證類型 商業 開源 MIT→商業* AGPL/商業 MIT 商業 商業
起始價 $799 免費 $599+* $2,399+ 免費 $2,995+ $2,499+

*Note:QuestPDFrecently changed fromMITto commercial licensing

詳細比較

IronPDFvs wkhtmltopdf

-wkhtmltopdfis free but was abandoned in 2020 and produces dated-looking PDFs

  • 需要平台專用的可執行文件,部署更為繁瑣 -否JavaScript support means modern web apps won't render correctly -IronPDFoffers modern rendering with no external dependencies

IronPDFvs QuestPDF

-QuestPDFrequires building PDFs entirely in C# code with no HTML support -好for programmatic PDF creation but time-consuming for complex layouts

  • Recently switched fromMITto commercial licensing -IronPDFlets you use HTML/CSS skills you already have

IronPDFvs iText 7

  • iText 使用的 AGPL 許可可能會 "傳染" 您的代碼 -商業licenses start at $1,999 with complex pricing -有限HTML to PDF capabilities with poor CSS support -IronPDFprovides superior HTML rendering at a lower price point

IronPDFvs PdfSharp

-PdfSharpis great for low-level PDF manipulation but has zero HTML support

  • 需手動定位頁面上的每個元素 -免費and open source but very limited in features -IronPDFhandles both high-level HTML and low-level PDF operations

IronPDFvs Syncfusion/Aspose.PDF

  • 兩者均為企業級方案,功能豐富但價格較高 -Syncfusionstarts at $2,995, Aspose at $2,499
  • 兩者均未能實現 IronPDF 的像素完美 HTML 渲染 -IronPDFoffers better value with comparable enterprise features

遷移路徑

Many developers switch toIronPDFfrom other libraries. 原因如下:

從 wkhtmltopdf

  • "我們對處理平台特定的二進制文件和過時的渲染已經厭倦了"
  • "IronPDF 提供了現代化的 CSS 支持並且消除了我們的 Docker 頭痛"

從 iTextSharp/iText 7

  • "The learning curve was killing our productivity -IronPDFlet us use HTML instead"
  • "AGPL 許可對我們的商業產品是一個攔路虎"

從 PdfSharp

  • "We needed HTML to PDF conversion, whichPdfSharpsimply doesn't do"
  • "手動定位每個元素耗費時間"

從 QuestPDF

  • "在 C# 代碼中製作佈局比用 HTML/CSS 繁瑣"
  • "最近的許可變更讓我們重新考慮我們的選擇"

結論

在 C# 中創建 PDF 並不一定很復雜。 有了 IronPDF,您可以使用您已經擁有的 HTML 和 CSS 技能 生成專業的 PDF 文件。 Whether you're building simple reports or complex documents with charts and forms,IronPDFhandles the heavy lifting so you can focus on your application logic. Join the 14 million developers worldwide who trustIronPDFas their C# PDF generator to produce PDFs reliably and efficiently.

在本指南中,我們探討了使用多種方法來 創建 PDF 文件 - 從 HTML 字串和 URL 到轉換現有文件諸如 Word 文件和 Markdown。 我們已經看到 IronPDF 的 現代化的基於 Chromium 的渲染引擎 如何產生 熟悉的像素完美結果,確保它看起來和您的 Web 設計一樣,而不是過時的打印輸出。 The ability to manipulate PDF documents programmatically, add security features, and optimize performance makesIronPDFa complete solution for all your PDF generation tasks in .NET.

What setsIronPDFapart is its developer-first approach. 只需三行代碼,您就可以 生成您的第一個 PDF。 直觀的 API 意味著您花在學習專有 PDF 語法上的時間更少,在建立功能上更多。 Combined with excellent support from real engineers, transparent pricing, and continuous updates (including pre-release support for .NET 10),IronPDFgives you confidence that your PDF creation in C# will work today and in the future.

今天開始 創建 PDF - 獲得您的免費試用許可證,看看在您的應用中 PDF 生成在 .NET 有多容易。 使用 IronPDF,您將在幾分鐘內 生成專業的 PDF,而不是幾小時。

準備好建立您的第一個 PDF 嗎? 開始使用 IronPDF 進行開發 - 它是免費的,您將在幾分鐘內 使用 C# 創建 PDF

請注意Aspose, iText, wkhtmltopdf, QuestPDF,PdfSharpand SyncFusion are registered trademarks of their respective owners. 本網站未與 Aspose、iText、wkhtmltopdf、QuestPDF、PdfSharp 或 SyncFusion 相關聯,不受其認可或贊助。 所有產品名稱、標誌和品牌均為其各自所有者的財產。 比較僅供參考,基於撰寫時可公開獲取的信息。