IRONSOFTWAREHOME

如何在IronPDF C#中匯出和儲存PDF

Curtis Chau
Curtis Chau
Updated: 2026年6月29日

IronPDF在C#中透過SaveAsRevision進行歸檔、無障礙和版本化輸出。 每個方法都會將您已經渲染的文件寫入應用程式所需的目的地,無論是檔案路徑、記憶體緩衝區或HTTP回應。

本指南介紹從單行檔案儲存到直接服務PDF至瀏覽器的每個匯出目標,以及生成符合標籤輸出的方式。

快速入門:在C#中匯出HTML為PDF

渲染HTML並將結果寫入磁碟中的單一聲明。 SaveAs使其持久化。

  1. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2複製並運行這段程式碼片段。

    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");
    C#
  3. 3部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用
    arrow pointer

儲存PDF有哪些選項?

IronPDF將byte[],以及用於歸檔、無障礙或增量修訂的符合標準標籤檔案。 以下章節介紹每個目標的測試範例,從最簡單的檔案儲存開始,到專門的匯出方法結束。

如何將PDF儲存至磁碟

使用PdfDocument寫入檔案路徑。 這是一個直接的途徑,適用於桌面應用程式或任何將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");

同一個範例還設定Password屬性,然後再進行第二次儲存,這會加密檔案,使其無法在沒有該密碼的情況下開啟。 如需更精細的控制接收者能對檔案進行的操作,請參閱PDF權限和密碼指南

輸出

如何將PDF儲存到MemoryStream

System.IO.MemoryStream返回。 當您需要將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();

輸出

如何儲存為二進位資料

byte[]返回。 位元組陣列適用於資料庫欄位、快取條目和接受原始位元組而不是流的API。

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

當您需要反向操作時,將位元組重新載入為可編輯文件,本指南涵蓋將PDF轉換為MemoryStream

輸出

如何將PDF從Web伺服器提供給瀏覽器?

要透過HTTP返回PDF,您需要將位元組作為檔案回應發送,而不是HTML。 BinaryData直接插入ASP.NET提供的檔案結果型別,因此控制器渲染文件並返回,而不需要觸摸磁碟。

如何在MVC中匯出PDF?

在ASP.NET Core MVC中,將File以內嵌顯示PDF。以下兩個行動展示了這兩種情況。 這自然與將CSHTML視圖渲染為PDF配對。

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

    // Render the PDF with IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Take the PDF stream and rewind it
    MemoryStream stream = pdf.Stream;
    stream.Position = 0;

    // Returning a FileStreamResult prompts a download in the browser
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Returning BinaryData with no filename displays the PDF inline
    return File(pdf.BinaryData, "application/pdf");
}
C#

如何在ASP.NET WebForms中匯出PDF?

傳統的ASP.NET WebForms應用程式通過Response物件寫入位元組。 配置渲染選項一次,提取BinaryData,並將其流到客戶端。

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

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

    // Render from custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieve the PDF bytes
    byte[] Binary = MyPdfDocument.BinaryData;

    // Write the bytes to the response as a download
    Response.Clear();
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition",
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
    Response.Flush();
    Response.End();
}
C#

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic

Microsoft MVP

查看案例研究

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle

首席技術官,OPYN

查看案例研究

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones

首席軟體工程師,Agorus Build

查看案例研究

如何匯出PDF/A、PDF/UA和修訂版本?

除了通用的儲存目標外,IronPDF還寫入三種符合標準的格式。 SaveAsRevision向現有文件新增增量修訂。

如何將PDF/A存檔檔案

SaveAsPdfA寫入一個自包含的檔案,符合長期儲存的ISO PDF/A標準,嵌入需要許多年後讀取的字體和色彩資料。 PdfA3b

using IronPdf;

var renderer = new ChromePdfRenderer();

// Render the document you want to archive
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>");

// Save as a PDF/A-3b file for long-term archiving.
// PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).
pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b);
C#

輸出

如何儲存無障礙PDF/UA檔案

SaveAsPdfUA寫入符合PDF/UA無障礙標準的標籤化PDF,供螢幕閱讀器瀏覽文件。 第三個參數設置文件語言,以便輔助技術用正確的語音讀取。

using IronPdf;

var renderer = new ChromePdfRenderer();

// Render content that should be tagged for assistive technology
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>");

// Save as a PDF/UA-1 file. The last argument sets the document's primary
// language, which screen readers use to choose the correct voice.
pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom);
C#

輸出

如何儲存增量修訂

SaveAsRevision追加更改到檔案,而不是重寫它,從而使早期修訂,包括任何數位簽名,保持完整。 必須使用ChangeTrackingModes.EnableChangeTracking開啟文件才能進行增量儲存。

using IronPdf;
using IronPdf.Rendering;

var renderer = new ChromePdfRenderer();

// Create and save the original revision of the document
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>");
pdf.SaveAs("revision-base.pdf");

// Re-open with change tracking enabled so the next save appends a revision
// instead of rewriting the file. This preserves earlier signed revisions.
PdfDocument loaded = PdfDocument.FromFile("revision-base.pdf", null, null, ChangeTrackingModes.EnableChangeTracking);

// Write an incremental revision on top of the existing bytes
loaded.SaveAsRevision("revision-v2.pdf");
C#

輸出

如何非同步匯出PDF?

渲染會阻塞呼叫執行緒,直到Chromium引擎完成為止。 在Web請求或桌面使用者介面中,請改用SaveAs方法儲存返回的文件。 這讓執行緒在渲染運行時保留空閒。

using IronPdf;
using System.Threading.Tasks;

var renderer = new ChromePdfRenderer();

// Render off the calling thread so a web request or UI stays responsive
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>");

// SaveAs writes the finished document to disk once the render completes
pdf.SaveAs("async-render.pdf");
C#

輸出

總結

IronPDF匯出渲染的PdfDocument至磁碟、記憶體、HTTP回應或符合標準標籤的文件,這都通過您已經構建的文件上的一個方法進行。 選擇符合位元組需要去向的目標,並在輸出必須符合存檔、無障礙或版本標準時,應用SaveAsRevision

從這裡,可以使用PDF記憶體流工作流程將位元組完全保存在磁碟之外,或者使用PDF權限和密碼鎖定已儲存的檔案。

常見問題

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

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

using C# 儲存 PDF 的不同方法是什麼?

IronPDF 提供多種儲存 PDF 的方法:SaveAs() 以儲存到磁碟、Stream 以便在不建立臨時檔案的情況下在網頁應用程式中提供 PDF,以及 BinaryData 以獲取 PDF 作為字節陣列。IronPDF 中的每個方法針對不同的使用案例,從簡單的檔案儲存到動態網頁交付。

我可以將 PDF 儲存到記憶體而不是磁碟嗎?

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

儲存 PDF 時如何新增密碼保護?

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

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

可以,IronPDF 允許您將 PDF 作為二進位資料直接提供給網頁瀏覽器。您可以使用 BinaryData 屬性獲取 PDF 作為字節陣列,並通過您的網頁應用程式的回應流提供,無需臨時檔案儲存。

用一句話轉換並儲存 HTML 為 PDF 的最簡單方法是什麼?

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

Can I password-protect a PDF using IronPDF?

Yes, IronPDF allows you to set a password on a `PdfDocument` via the `Password` property before saving it. This ensures that a PDF cannot be opened without the correct password.

What should I do if I need an accessible PDF conforming to PDF/UA standards?

You can create a PDF that conforms to PDF/UA standards using IronPDF by calling the `SaveAsPdfUA` method. This ensures that the document includes tags to aid navigation by screen readers.

How can I keep different versions of a PDF document?

IronPDF supports incremental saves with the `SaveAsRevision` method, which appends changes to an existing PDF file while preserving previous revisions, ideal for maintaining version history.

Why should I consider exporting PDFs using the PDF/A format?

Exporting PDFs in PDF/A format ensures that the document is self-contained and suitable for long-term archiving, as it includes all necessary components like fonts and color data to ensure fidelity over time.

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備開始了嗎?

Nuget Downloads 20,990,528版本:2026.9剛剛發布

立即獲取免費

立即獲取 30天試用金鑰

bullet_checked無需信用卡或註冊帳號
bullet_test在生產
環境中進行測試,且不顯示浮水印
bullet_calendar30 天全
功能產品
bullet_support試用期間提供 24/5 技術
支援
立即獲取您的免費30天試用密鑰
不需要信用卡或建立賬戶
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999

有問題嗎?聯絡我們的開發團隊。

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

OR
bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999