如何在IronPDF C#中匯出和儲存PDF
IronPDF在C#中透過SaveAsRevision進行歸檔、無障礙和版本化輸出。 每個方法都會將您已經渲染的文件寫入應用程式所需的目的地,無論是檔案路徑、記憶體緩衝區或HTTP回應。
本指南介紹從單行檔案儲存到直接服務PDF至瀏覽器的每個匯出目標,以及生成符合標籤輸出的方式。
快速入門:在C#中匯出HTML為PDF
渲染HTML並將結果寫入磁碟中的單一聲明。 SaveAs使其持久化。
最小工作流程 (5步)
- 從NuGet下載C# PDF程式庫
- 渲染或載入
PdfDocument - 使用
SaveAs儲存到磁碟,或者使用Stream和BinaryData儲存到記憶體中 - 將位元組作為檔案回應傳送到網頁,而非HTML
- 使用
SaveAsPdfA,SaveAsPdfUA或SaveAsRevision匯出符合標準的輸出
儲存PDF有哪些選項?
IronPDF將byte[],以及用於歸檔、無障礙或增量修訂的符合標準標籤檔案。 以下章節介紹每個目標的測試範例,從最簡單的檔案儲存開始,到專門的匯出方法結束。
如何將PDF儲存至磁碟
使用PdfDocument寫入檔案路徑。 這是一個直接的途徑,適用於桌面應用程式或任何將PDF保存在檔案系統中的伺服器程式。
:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-2.cs
// 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");
Imports IronPdf
' Initialize the Chrome PDF renderer
Dim renderer As New ChromePdfRenderer()
' Create HTML content with styling
Dim htmlContent As String = "
<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
Dim pdf As PdfDocument = 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記憶體流。
:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-3.cs
// 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();
Imports IronPdf
Imports System.IO
' Example: Save PDF to MemoryStream
Dim renderer As New ChromePdfRenderer()
' Render HTML content
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>")
' Get the PDF as a MemoryStream
Dim stream As MemoryStream = 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。
:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-4.cs
// 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);
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Configure rendering options for better quality
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
.MarginTop = 20,
.MarginBottom = 20,
.MarginLeft = 10,
.MarginRight = 10,
.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
}
' Render content to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>")
' Get binary data
Dim binaryData As Byte() = 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");
}
// 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");
}
Imports System.IO
Imports Microsoft.AspNetCore.Mvc
' MVC controller methods for PDF export
Public Class InvoiceController
Inherits Controller
Public Function DownloadInvoice(invoiceId As Integer) As IActionResult
' Generate your HTML content
Dim htmlContent As String = GenerateInvoiceHtml(invoiceId)
' Render the PDF with IronPDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Take the PDF stream and rewind it
Dim stream As MemoryStream = pdf.Stream
stream.Position = 0
' Returning a FileStreamResult prompts a download in the browser
Return New FileStreamResult(stream, "application/pdf") With {
.FileDownloadName = $"invoice_{invoiceId}.pdf"
}
End Function
Public Function ViewInvoice(invoiceId As Integer) As IActionResult
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId))
' Returning BinaryData with no filename displays the PDF inline
Return File(pdf.BinaryData, "application/pdf")
End Function
Private Function GenerateInvoiceHtml(invoiceId As Integer) As String
' Placeholder for the method that generates HTML content
Return String.Empty
End Function
End Class
如何在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();
}
// 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();
}
' ASP.NET WebForms PDF export
Protected Sub ExportButton_Click(sender As Object, e As EventArgs)
Dim renderer As New ChromePdfRenderer()
' Configure rendering options
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
.PrintHtmlBackgrounds = True,
.CreatePdfFormsFromHtml = True
}
' Render from custom HTML
Dim MyPdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml())
' Retrieve the PDF bytes
Dim Binary As Byte() = 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()
End Sub
如何匯出PDF/A、PDF/UA和修訂版本?
除了通用的儲存目標外,IronPDF還寫入三種符合標準的格式。 SaveAsRevision向現有文件新增增量修訂。
如何將PDF/A存檔檔案
SaveAsPdfA寫入一個自包含的檔案,符合長期儲存的ISO PDF/A標準,嵌入需要許多年後讀取的字體和色彩資料。 PdfA3b。
:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-pdfa.cs
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);
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Render the document you want to archive
Dim pdf As PdfDocument = 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)
輸出
如何儲存無障礙PDF/UA檔案
SaveAsPdfUA寫入符合PDF/UA無障礙標準的標籤化PDF,供螢幕閱讀器瀏覽文件。 第三個參數設置文件語言,以便輔助技術用正確的語音讀取。
:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-pdfua.cs
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);
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Render content that should be tagged for assistive technology
Dim pdf As PdfDocument = 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)
輸出
如何儲存增量修訂
SaveAsRevision追加更改到檔案,而不是重寫它,從而使早期修訂,包括任何數位簽名,保持完整。 必須使用ChangeTrackingModes.EnableChangeTracking開啟文件才能進行增量儲存。
:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-revision.cs
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");
Imports IronPdf
Imports IronPdf.Rendering
Dim renderer As New ChromePdfRenderer()
' Create and save the original revision of the document
Dim pdf As PdfDocument = 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.
Dim loaded As PdfDocument = PdfDocument.FromFile("revision-base.pdf", Nothing, Nothing, ChangeTrackingModes.EnableChangeTracking)
' Write an incremental revision on top of the existing bytes
loaded.SaveAsRevision("revision-v2.pdf")
輸出
如何非同步匯出PDF?
渲染會阻塞呼叫執行緒,直到Chromium引擎完成為止。 在Web請求或桌面使用者介面中,請改用SaveAs方法儲存返回的文件。 這讓執行緒在渲染運行時保留空閒。
:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-async.cs
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");
Imports IronPdf
Imports System.Threading.Tasks
Dim renderer As New ChromePdfRenderer()
' Render off the calling thread so a web request or UI stays responsive
Dim pdf As PdfDocument = Await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>")
' SaveAs writes the finished document to disk once the render completes
pdf.SaveAs("async-render.pdf")
輸出
總結
IronPDF匯出渲染的PdfDocument至磁碟、記憶體、HTTP回應或符合標準標籤的文件,這都通過您已經構建的文件上的一個方法進行。 選擇符合位元組需要去向的目標,並在輸出必須符合存檔、無障礙或版本標準時,應用SaveAsRevision。
常見問題
如何在 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,並在一個語句中將其儲存到磁碟。

