IRONSOFTWAREHOME

如何在IronPDF C#中导出并保存PDF

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

IronPDF通过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的指南涵盖了这一内容。

输出

如何从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");
}
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

微软MVP

查看案例研究

IronOCR 意味着我们每年可以节省 $40,000 的人工处理成本,同时提高生产力,并释放资源用于高影响任务。我强烈推荐它。

Brent Matzelle

首席技术官,OPYN

查看案例研究

Iron Suite 在我们的运营中起着至关重要的作用。这些工具提高了业务各方面的效率,包括创建平面图和改善库存管理。

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请求或桌面UI中,改为调用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,并通过网络应用程序的响应流提供 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 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

...
阅读更多

准备开始了吗?

Nuget Downloads 20,809,720版本: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% 解锁。无需信用卡。

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 天试用密钥
无需信用卡或创建账户