跳至頁尾內容
使用 IRONPDF

使用 C# .NET 程式庫建立 PDF

使用 IronPDF 的 .NET 庫,只需一行程式碼即可在 C# 中建立 PDF,該程式庫透過內建的渲染功能和輕鬆的 Visual Studio 集成,簡化了從 HTML 字串、URL 或表單生成 PDF 的過程。

有了正確的指導,使用 C# .NET 程式庫建立 PDF 檔案既簡單又有效率。 使用 IronPDF,您可以根據應用程式的需求,以簡單的方式建立和編輯 PDF 功能。 本教學範例展示如何在專案中有效使用該軟體,只需單擊一個按鈕即可建立 PDF!

PDF .NET 函式庫

  • 安裝 IronPDF C# .NET 函式庫
  • 用一行程式碼在 C# 中建立 PDF
  • 一鍵將表單轉換為 PDF

步驟 1

如何安裝 C# PDF 函式庫 .NET?

進入圖書館主要有兩種方式:

  1. Download and unpack the [IronPDF Package](https://ironpdf.com/packages/IronPdf.zip) DLL file
  2. Navigate to [NuGet](https://www.nuget.org/packages/IronPdf) and install the package via Visual Studio.

對於學習.NET PDF 產生的初學者來說,NuGet 套件管理器提供了最簡單的安裝方法。 它會自動處理依賴關係,並確保您使用的是最新的穩定版本。 安裝概述為各種開發環境提供了詳細指導。


我該選擇哪一種安裝方式?

# Use the NuGet package manager to install IronPDF
nuget install IronPdf
# Use the NuGet package manager to install IronPDF
nuget install IronPdf
SHELL

NuGet 是大多數開發人員推薦的方法,尤其是剛接觸 .NET 開發的開發人員。 它與 Visual Studio 和其他 IDE 無縫集成,非常適合用C# 建立 PDF 。 軟體套件管理器會自動處理所有複雜的配置,包括:

  • 依賴關係解析和版本相容性
  • 適用於WindowsLinuxMac的特定平台二進位文件
  • 透過 Visual Studio 的套件管理器自動更新
  • 與專案建置流程集成

常見的安裝問題有哪些?

安裝 IronPDF 時,開發人員有時會遇到一些常見的挑戰。 故障排除指南涵蓋了大多數情況,但以下是最常見的幾種情況:

1.缺少 Visual C++ 執行時間:IronPDF 需要 Visual C++ 可再發行元件。 如果發生缺少 DLL 檔案的錯誤,請從 Microsoft 安裝最新的 Visual C++ 執行階段環境。

2.防火牆阻止 NuGet :企業環境可能會阻止 NuGet.org。 在這種情況下,您可以下載離線安裝套件並手動安裝。

3.平台不符:確保您的專案面向正確的平台(x86、x64 或 AnyCPU)。 IronPDF 最好是針對特定平台進行最佳化,而不是使用 AnyCPU。

為什麼要使用 NuGet 而不是手動安裝?

對於學習HTML 轉 PDF 的開發人員來說,NuGet 提供了以下幾個優點:

-自動更新:自動取得安全性修補程式和新功能 -版本控制:如有需要,可輕鬆回滾到先前的版本 -團隊協作:所有開發人員都獲得相同的軟體包版本 -建立伺服器相容性:與 CI/CD 管線無縫協作 -軟體包恢復:建置時自動下載缺少的軟體包

NuGet 套件文件提供了針對特定場景(例如Azure 部署Docker 容器)的進階配置選項。


操作指南

如何使用 PDF .NET 函式庫?

C# 程式語言標誌 - 紫色六角形徽章,上面有白色的
漸層色的V形箭頭(從紫色到藍綠色)指示PDF轉換工作流程方向
設計與測量工具圖示 - 黑色鋼筆與藍色尺子交叉,用於 PDF 註釋功能
IronPDF 中表示文件轉換過程的多色 V 形箭頭
Adobe PDF 文件圖標,顯示 .NET 應用程式中使用的標準 PDF 文件格式

現在我們有了這款軟體,我們可以產生 PDF 文件調整設置,添加自訂文字和圖像,並修改 PDF 文件以滿足我們的專案需求。 IronPDF 提供全面的功能,可用於建立新的 PDF編輯現有的 PDF ,甚至可以將各種格式(如圖像到 PDFXML 到 PDF)進行轉換。

ChromePdfRenderer作用是什麼?

在下面的程式碼中,我們使用 C# 窗體來示範如何使用 C# .NET 程式庫建立 PDF。 在這個例子中,我們有一個TextBox來輸入我們自己的文本,然後點擊一個按鈕即可生成 PDF 文件。 ChromePdfRenderer類別提供了一種最簡單的方法,可以從不同的來源產生 PDF 文件,包括HTML 字串Web URL另一個渲染器下的 doc 文件

ChromePdfRenderer是 IronPDF 渲染引擎的核心。它採用與 Google Chrome 相同的技術,確保您的 PDF 檔案在現代網頁瀏覽器中的顯示效果與在瀏覽器中完全一致。 這意味著全面支持:

如何處理PDF產生過程中的錯誤?

錯誤處理對於可靠地產生PDF文件至關重要。 IronPDF 提供詳細的異常訊息,有助於快速識別問題。 以下是一種具有錯誤處理功能的穩健的 PDF 生成方法:

using IronPdf;
using System;
using System.IO;

public class PdfGenerator
{
    public static bool CreatePdfSafely(string htmlContent, string outputPath)
    {
        try
        {
            var renderer = new ChromePdfRenderer();

            // Configure rendering options for better results
            renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
            renderer.RenderingOptions.MarginTop = 20;
            renderer.RenderingOptions.MarginBottom = 20;
            renderer.RenderingOptions.PrintHtmlBackgrounds = true;

            // Generate the PDF
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Ensure directory exists
            string directory = Path.GetDirectoryName(outputPath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // Save the PDF
            pdf.SaveAs(outputPath);

            return true;
        }
        catch (Exception ex)
        {
            // Log the error (you can use your preferred logging framework)
            Console.WriteLine($"PDF generation failed: {ex.Message}");
            return false;
        }
    }
}
using IronPdf;
using System;
using System.IO;

public class PdfGenerator
{
    public static bool CreatePdfSafely(string htmlContent, string outputPath)
    {
        try
        {
            var renderer = new ChromePdfRenderer();

            // Configure rendering options for better results
            renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
            renderer.RenderingOptions.MarginTop = 20;
            renderer.RenderingOptions.MarginBottom = 20;
            renderer.RenderingOptions.PrintHtmlBackgrounds = true;

            // Generate the PDF
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Ensure directory exists
            string directory = Path.GetDirectoryName(outputPath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // Save the PDF
            pdf.SaveAs(outputPath);

            return true;
        }
        catch (Exception ex)
        {
            // Log the error (you can use your preferred logging framework)
            Console.WriteLine($"PDF generation failed: {ex.Message}");
            return false;
        }
    }
}
$vbLabelText   $csharpLabel

對於更進階的錯誤情況,請參閱故障排除指南,其中涵蓋了記憶體管理渲染延遲等常見問題。

何時應該使用 HTML 渲染,何時應該直接建立 PDF?

了解何時使用 HTML 渲染,何時直接建立 PDF,有助於您選擇正確的方法。 IronPDF 在 HTML 渲染方面表現出色,因為它具備以下優勢:

HTML渲染優勢:

  • 利用現有的網站開發技能
  • 使用熟悉的 CSS 進行樣式設置
  • 易於響應的設計,並帶有視口設置 -支援 JavaScript的動態內容 快速原型製作與迭代

何時使用 HTML 渲染:

直接操作 PDF 檔案更適合以下情況:

// C# Program to create PDF from TextBox input using IronPDF
using IronPdf;
using System.Windows.Forms;

namespace readpdf
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Event handler for the button click
        private void button1_Click(object sender, System.EventArgs e)
        {
            // Create a ChromePdfRenderer object to convert HTML to PDF
            var HtmlLine = new ChromePdfRenderer();

            // Retrieve the text from the TextBox
            string text = textBox1.Text;

            // Render the HTML as a PDF, wrapping the text in an <h1> tag
            using var pdf = HtmlLine.RenderHtmlAsPdf("<h1>" + text + "</h1>");

            // Save the PDF to a file called "custom.pdf"
            pdf.SaveAs("custom.pdf");

            // Show a confirmation message to the user
            MessageBox.Show("Done!");
        }
    }
}
// C# Program to create PDF from TextBox input using IronPDF
using IronPdf;
using System.Windows.Forms;

namespace readpdf
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Event handler for the button click
        private void button1_Click(object sender, System.EventArgs e)
        {
            // Create a ChromePdfRenderer object to convert HTML to PDF
            var HtmlLine = new ChromePdfRenderer();

            // Retrieve the text from the TextBox
            string text = textBox1.Text;

            // Render the HTML as a PDF, wrapping the text in an <h1> tag
            using var pdf = HtmlLine.RenderHtmlAsPdf("<h1>" + text + "</h1>");

            // Save the PDF to a file called "custom.pdf"
            pdf.SaveAs("custom.pdf");

            // Show a confirmation message to the user
            MessageBox.Show("Done!");
        }
    }
}
$vbLabelText   $csharpLabel

如何將 C# 表單轉換為 PDF?

我們使用 C# Windows Forms 應用程式向您展示了帶有自訂文字的完美輸出效果。 只需按一下, TextBox的文字即可轉換為自訂 PDF。 這只需要一行程式碼,而且很容易理解。 對於更複雜的場景,您可能需要探索 MVC 應用程式的CSHTML 到 PDF 轉換或現代 Web 應用程式的Blazor PDF 生成

為什麼這種單擊式方法有效?

點擊方法之所以有效,是因為 IronPDF 在內部處理了所有複雜的渲染。 當您呼叫RenderHtmlAsPdf()時,IronPDF:

1.初始化 Chrome 引擎:使用與 Chrome 瀏覽器相同的渲染引擎 2.處理 HTML :解析 HTML 字串並套用任何內聯樣式 3.渲染為 PDF :將渲染後的內容轉換為 PDF 格式 4.最佳化輸出:應用壓縮和最佳化

IronPDF 的簡潔性使其成為需要快速結果的快速開發場景的理想選擇。 該程式庫可自動處理字型管理映像嵌入,甚至JavaScript 執行

我可以匯出為哪些文件格式?

雖然 PDF 是主要輸出格式,但 IronPDF 也支援各種匯出和轉換選項:

此外,IronPDF還可以從各種來源匯入資料:

如何自訂PDF輸出?

IronPDF 透過RenderingOptions類提供豐富的自訂選項。 以下是一個展示常見自訂設定的範例:

using IronPdf;

// Create renderer with custom settings
var renderer = new ChromePdfRenderer();

// Page setup options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;

// Margins (in millimeters)
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;

// Header and footer configuration
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    Height = 15,
    HtmlFragment = "<div style='text-align: center;'>{page} of {total-pages}</div>",
    DrawDividerLine = true
};

// Additional options
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.GrayScale = false;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

// Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

// Generate PDF with all customizations
var pdf = renderer.RenderHtmlAsPdf("<h1>Customized PDF Output</h1>");
pdf.SaveAs("customized.pdf");
using IronPdf;

// Create renderer with custom settings
var renderer = new ChromePdfRenderer();

// Page setup options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;

// Margins (in millimeters)
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;

// Header and footer configuration
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    Height = 15,
    HtmlFragment = "<div style='text-align: center;'>{page} of {total-pages}</div>",
    DrawDividerLine = true
};

// Additional options
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.GrayScale = false;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

// Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

// Generate PDF with all customizations
var pdf = renderer.RenderHtmlAsPdf("<h1>Customized PDF Output</h1>");
pdf.SaveAs("customized.pdf");
$vbLabelText   $csharpLabel

如需更多進階自訂設置,請探索: -自訂紙張尺寸 -頁首和頁尾 背景和前景 頁碼 水印

C# 表單

Windows Forms 應用程式展示了 IronPDF 整合——文字輸入欄位帶有

~ PDF ~

在 Adobe Acrobat Pro DC 中顯示的 PDF 輸出檔案包含使用 IronPDF 庫建立的自訂文字。

圖書館快速訪問

`documentation related to 圖書館快速訪問

分享 API 參考

Read through and share the API Reference for all the functionality you need to work with PDFs in your .NET project. The comprehensive documentation covers everything from basic [PDF creation](https://ironpdf.com/tutorials/csharp-create-pdf-complete-tutorial/) to advanced features like [digital signatures](https://ironpdf.com/tutorials/csharp-pdf-security-complete-tutorial/) and [form handling](https://ironpdf.com/how-to/edit-forms/).

IronPDF API 參考

常見問題解答

如何在我的 C# 專案中安裝 PDF 庫?

你可以透過直接下載軟體包 DLL 檔案或使用 NuGet 透過 Visual Studio 安裝 PDF 庫(例如 IronPDF)。

如何使用 PDF 庫從 C# 建立 PDF 文件?

使用 IronPDF 等 PDF 庫,您可以利用ChromePdfRenderer類別將 HTML 字串或 URL 轉換為 PDF,從而以最少的程式碼建立 PDF。

我可以使用 PDF 庫將 C# 表單轉換為 PDF 嗎?

是的,使用 IronPDF,您可以將 C# 表單轉換為 PDF。這包括捕獲表單資料並使用庫的渲染功能將其渲染為 PDF。

使用 PDF 庫產生 PDF 的最簡單方法是什麼?

使用 IronPDF 產生 PDF 最簡單的方法是使用ChromePdfRenderer物件直接將 HTML 內容渲染成 PDF。

如何使用 PDF 庫為 PDF 添加自訂文字和圖像?

您可以使用 IronPDF 的功能,在將 HTML 內容渲染成 PDF 之前對其進行操作,從而為 PDF 添加自訂文字和圖像。

是否可以使用 PDF 庫編輯現有的 PDF 檔案?

是的,IronPDF 提供了操作和編輯現有 PDF 的功能,可讓您根據需要更新內容。

如何使用 PDF 函式庫將 URL 直接轉換為 PDF?

IronPDF 讓您可以使用ChromePdfRenderer物件將 Web URL 直接轉換為 PDF,從而簡化了轉換過程。

.NET 平台的 PDF 函式庫主要有哪些特性?

IronPDF 等 PDF 庫提供 PDF 創建、編輯、HTML 轉換以及添加自訂文字和圖像等功能,使其成為 .NET 開發人員的多功能工具。

我可以使用 PDF 庫自訂 PDF 設定嗎?

是的,IronPDF 允許您自訂各種 PDF 設置,包括頁面大小、方向和邊距,以滿足您的特定專案要求。

如何在 C# 中使用 PDF 庫時排查問題?

如需進行故障排除,您可以參考 IronPDF 提供的文件和資源,或諮詢社區論壇以尋求常見問題的解決方案。

IronPDF 是否相容於 .NET 10? .NET 10 能帶來哪些好處?

是的,IronPDF 與 .NET 10 完全相容。它支援 .NET 10 中引入的運行時和語言增強功能,包括改進的記憶體使用、效能提升(如數組介面方法去虛擬化)以及減少 PDF 生成和操作的開銷。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。