如何在 C# 中導出 PDF | IronPDF

C# 匯出到 PDF 程式碼範例教學

This article was translated from English: Does it need improvement?
Translated
View the article in English

使用IronPDF在 C# 中將 HTML 內容匯出為 PDF,方法很簡單,例如 StreamBinaryData。 這個 C# PDF 庫使開發人員能夠以程式設計方式將 HTML 轉換為 PDF 文檔,並將其提供給 Web 瀏覽器或儲存到磁碟。

IronPDF是一個C# PDF 庫,它允許您使用 C# 將 HTML 儲存為 PDF。 它還允許 C# / VB 開發人員以程式設計方式編輯 PDF 文件。 無論您是產生報表、建立發票還是轉換網頁, IronPDF為 C# 應用程式中的 PDF 產生提供了一個強大的解決方案。

快速入門:使用IronPDF在 C# 中將 HTML 匯出為 PDF

使用IronPDF在 C# 中將 HTML 內容匯出為 PDF。 本指南將向您展示如何僅用幾行程式碼將 HTML 轉換為 PDF 文件並儲存。 IronPDF簡化了 PDF 生成流程,使開發人員能夠將 PDF 匯出功能整合到他們的應用程式中。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 複製並運行這段程式碼。

    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");
  3. 部署到您的生產環境進行測試

    今天就在您的專案中開始使用免費試用IronPDF

    arrow pointer


儲存PDF檔案有哪些不同的選項?

在 C# 中處理 PDF 文件時, IronPDF提供了多種儲存和匯出生成的 PDF 的選項。 每種方法都適用於不同的使用場景,從簡單的文件儲存到在 Web 應用程式中提供 PDF 文件。 以下各節介紹了在 C# 中匯出和儲存 PDF 的可用選項。

如何將 PDF 檔案儲存到磁碟

使用PdfDocument.SaveAs方法將 PDF 儲存到磁碟。 對於桌面應用程式或需要在伺服器上永久儲存 PDF 檔案的情況,這是最直接的方法。

// Complete example for saving PDF to disk
using IronPdf;

// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();

// Create HTML content with styling
string htmlContent = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");

// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");
// Complete example for saving PDF to disk
using IronPdf;

// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();

// Create HTML content with styling
string htmlContent = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");

// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");
$vbLabelText   $csharpLabel

此方法支援新增密碼保護。 請查看以下文章,以了解有關對匯出的 PDF 進行數位簽章的更多資訊:"對 PDF 文件進行數位簽章"。有關其他安全性選項,請瀏覽我們的PDF 權限和密碼指南。

如何在 C# 中將 PDF 檔案儲存到 MemoryStream (System.IO.MemoryStream)

IronPdf.PdfDocument.Stream屬性使用 System.IO.MemoryStream 將 PDF 儲存到記憶體中。 當您需要在記憶體中操作 PDF 資料或將其傳遞給其他方法而無需建立臨時檔案時,這種方法是理想的選擇。 了解更多關於使用PDF記憶體流的資訊

// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");

// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;

// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);

// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");

// Remember to dispose of the stream when done
stream.Dispose();
// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");

// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;

// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);

// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");

// Remember to dispose of the stream when done
stream.Dispose();
$vbLabelText   $csharpLabel

如何儲存為二進位數據

IronPdf.PdfDocument.BinaryData屬性將 PDF 文件以二進位資料的形式匯出到記憶體中。 這對於資料庫儲存或與需要位元組數組的 API 整合時尤其有用。

這將 PDF 輸出為 ByteArray,在 C# 中表示為 byte []

// Example: Convert PDF to binary data
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};

// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");

// Get binary data
byte[] binaryData = pdf.BinaryData;

// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);

// Example: Send via API
// apiClient.UploadDocument(binaryData);
// Example: Convert PDF to binary data
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};

// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");

// Get binary data
byte[] binaryData = pdf.BinaryData;

// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);

// Example: Send via API
// apiClient.UploadDocument(binaryData);
$vbLabelText   $csharpLabel

對於涉及二進位資料操作的更進階場景,請參閱我們的PDF 轉 MemoryStream指南。

如何從 Web 伺服器向瀏覽器提供服務

要將 PDF 文件提供給網絡,我們需要將其作為二進位資料而不是 HTML 格式發送。 對於使用者需要在瀏覽器中直接下載或查看 PDF 的 Web 應用程式來說,這一點至關重要。 IronPDF可以與 MVC 和傳統的ASP.NET應用程式整合。

MVC PDF匯出

在現代 MVC 應用程式中,使用 FileStreamResult 提供 PDF 服務非常簡單。 這種方法非常適用於ASP.NET Core MVC 應用程式

// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Create PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Get the PDF stream
    MemoryStream stream = pdf.Stream;

    // Reset stream position
    stream.Position = 0;

    // Return file to browser - will prompt download
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Return PDF for browser viewing
    return File(pdf.BinaryData, "application/pdf");
}
// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Create PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Get the PDF stream
    MemoryStream stream = pdf.Stream;

    // Reset stream position
    stream.Position = 0;

    // Return file to browser - will prompt download
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Return PDF for browser viewing
    return File(pdf.BinaryData, "application/pdf");
}
$vbLabelText   $csharpLabel

ASP.NET PDF匯出

對於傳統的ASP.NET WebForms 應用程序,您可以透過 Response 物件直接提供 PDF 檔案:

// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    // Create your PDF document
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Generate PDF from current page or custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieves the PDF binary data
    byte[] Binary = MyPdfDocument.BinaryData;

    // Clears the existing response content
    Response.Clear();

    // Sets the response content type to 'application/octet-stream', suitable for PDF files
    Response.ContentType = "application/octet-stream";

    // Add content disposition header for download
    Response.AddHeader("Content-Disposition", 
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");

    // Writes the binary data to the response output stream
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);

    // Flushes the response to send the data to the client
    Response.Flush();

    // End the response
    Response.End();
}
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    // Create your PDF document
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Generate PDF from current page or custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieves the PDF binary data
    byte[] Binary = MyPdfDocument.BinaryData;

    // Clears the existing response content
    Response.Clear();

    // Sets the response content type to 'application/octet-stream', suitable for PDF files
    Response.ContentType = "application/octet-stream";

    // Add content disposition header for download
    Response.AddHeader("Content-Disposition", 
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");

    // Writes the binary data to the response output stream
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);

    // Flushes the response to send the data to the client
    Response.Flush();

    // End the response
    Response.End();
}
$vbLabelText   $csharpLabel

進階出口方案

批量匯出 PDF

處理多個PDF檔案時,您可以最佳化匯出流程:

// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
    using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
    {
        var renderer = new ChromePdfRenderer();

        for (int i = 0; i < htmlDocuments.Count; i++)
        {
            // Render each HTML document
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);

            // Add to zip archive
            var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
            using (var entryStream = entry.Open())
            {
                pdf.Stream.CopyTo(entryStream);
            }
        }
    }
}
// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
    using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
    {
        var renderer = new ChromePdfRenderer();

        for (int i = 0; i < htmlDocuments.Count; i++)
        {
            // Render each HTML document
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);

            // Add to zip archive
            var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
            using (var entryStream = entry.Open())
            {
                pdf.Stream.CopyTo(entryStream);
            }
        }
    }
}
$vbLabelText   $csharpLabel

基於使用者權限的條件匯出

// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Apply security based on user role
    if (userRole == UserRole.Guest)
    {
        // Restrict printing and copying for guests
        pdf.SecuritySettings.AllowUserPrinting = false;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }
    else if (userRole == UserRole.Standard)
    {
        // Allow printing but not editing
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserEditing = false;
    }

    return pdf.BinaryData;
}
// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Apply security based on user role
    if (userRole == UserRole.Guest)
    {
        // Restrict printing and copying for guests
        pdf.SecuritySettings.AllowUserPrinting = false;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }
    else if (userRole == UserRole.Standard)
    {
        // Allow printing but not editing
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserEditing = false;
    }

    return pdf.BinaryData;
}
$vbLabelText   $csharpLabel

PDF匯出最佳實踐

在生產環境中匯出 PDF 檔案時,請遵循以下最佳實踐:

1.記憶體管理:對於大型 PDF 或高流量應用程序,應妥善處置 PDF 物件和串流,以防止記憶體洩漏。 考慮使用 async 方法以獲得更好的性能。 2.錯誤處理:匯出 PDF 時,尤其是在可能出現網路問題的 Web 應用程式中,請務必實施適當的錯誤處理。 3.壓縮:對於大型 PDF 文件,在提供給使用者之前使用 PDF 壓縮來減少文件大小。 4.元資料:設定適當的 PDF 元數據,包括標題、作者和建立日期,以便更好地管理文件。 5.跨平台相容性:確保您的匯出功能在不同平台上都能正常運作。 IronPDF支援 LinuxmacOS

結論

IronPDF為 C# 應用程式提供了全面的 PDF 匯出選項,從簡單的文件儲存到複雜的 Web 伺服器場景。 選擇適合您使用場景的匯出方法,可以有效地產生 PDF 文件並將其交付給用戶,同時保持安全性和效能標準。

常見問題解答

如何在 C# 中將 HTML 內容匯出至 PDF?

您可以使用 IronPDF 的 ChromePdfRenderer 類,在 C# 中將 HTML 匯出為 PDF。只需創建一個渲染器實例,使用 RenderHtmlAsPdf() 方法轉換您的 HTML 內容,然後用 SaveAs() 方法保存即可。IronPDF 可輕鬆地將 HTML 字串、檔案或 URL 直接轉換為 PDF 文件。

使用 C# 儲存 PDF 有哪些不同的方法?

IronPDF 提供了多種儲存 PDF 的方法:SaveAs() 用於儲存至磁碟,Stream 用於在 Web 應用程式中提供 PDF 而無需建立臨時檔案,而 BinaryData 用於以位元組陣列的方式取得 PDF。IronPDF 中的每種方法都服務於不同的用例,從簡單的檔案儲存到動態的網頁傳送。

我可以將 PDF 儲存至記憶體而非磁碟嗎?

是的,IronPDF 允許您使用 System.IO.MemoryStream 將 PDF 儲存至記憶體。這對於想要直接向使用者提供 PDF 而不在伺服器上建立臨時檔案的 Web 應用程式非常有用。您可以使用 Stream 屬性或將 PDF 轉換為二進位資料。

如何在儲存 PDF 時加入密碼保護?

IronPDF 透過在儲存前設定 PdfDocument 物件的 Password 屬性來啟用密碼保護。只需將密碼字串指定給 pdf.Password,然後使用 SaveAs() 建立需要密碼才能開啟的受保護 PDF 檔案。

我可以直接將 PDF 提供給 Web 瀏覽器而不儲存到磁碟嗎?

是的,IronPDF 允許您以二進位資料的形式直接向網頁瀏覽器提供 PDF。您可以使用 BinaryData 屬性,以位元組陣列的方式取得 PDF,並透過網頁應用程式的回應串流提供 PDF,省去暫存檔案的需求。

在一行中將 HTML 轉換並儲存為 PDF 的最簡單方法是什麼?

IronPDF 提供了單一行式的解決方案:new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf")。這會在單一語句中建立一個渲染器,將 HTML 轉換成 PDF,並將其儲存到磁碟中。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

審核人
Jeff Fritz
Jeffrey T. Fritz
首席程序经理 - .NET 社群团队
Jeff 也是 .NET 和 Visual Studio 团队的首席程序经理。他是 .NET Conf 虚拟会议系列的执行制作人,并主持“Fritz 和朋友”这一每周两次的開發者的直播节目,在节目上讨论技術并与观众一起编写代碼。Jeff 撰写研讨会、主持演讲,并计划大型 Microsoft 開發者活動(包括 Microsoft Build、Microsoft Ignite、.NET Conf 和 Microsoft MVP Summit)的內容。
準備好開始了嗎?
Nuget 下載 17,803,474 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想快速取得證據? PM > Install-Package IronPdf
運行範例看著你的HTML程式碼變成PDF檔。