如何在IronPDF C#中导出并保存PDF
IronPDF通过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的指南涵盖了这一内容。
输出
如何从Web服务器将PDF提供到浏览器?
要通过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请求或桌面UI中,改为调用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,并通过网络应用程序的响应流提供 PDF,从而无需临时文件存储。
在一行中将 HTML 转换并保存为 PDF 的最简单方法是什么?
IronPDF 提供了单行解决方案:new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf")。只需一条语句,即可创建渲染器、将 HTML 转换为 PDF 并保存到磁盘。

