如何在 C# 中導出 PDF | IronPDF

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

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

使用 IronPdf 在 C# 中使用 SaveAs(), StreamBinaryData 等簡單的方法將 HTML 內容匯出至 PDF。 此 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 匯出功能整合到他們的應用程式中。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 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 權限和密碼指南

How to Save a PDF File to MemoryStream in C# (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 的網路應用程式而言,這是非常重要的。 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 支援 Windows, Linux, 和 macOS.

結論

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 bots,將他對技術的熱愛與創意結合。

審核人
Jeff Fritz
Jeffrey T. Fritz
首席計畫經理 - .NET 社群團隊
Jeff 也是 .NET 和 Visual Studio 團隊的首席計畫經理。他是 .NET Conf 虛擬會議系列的執行製作人,並主持「Fritz and Friends」開發人直播串流,每週播出兩次,與觀眾一起討論技術和編寫程式碼。Jeff 為 Microsoft Build、Microsoft Ignite、.NET Conf 和 Microsoft MVP Summit 等大型 Microsoft 開發人員活動撰寫工作坊、簡報和規劃內容。
準備好開始了嗎?
Nuget 下載 17,527,568 | 版本: 2026.2 剛剛發布