C# 导出与保存 PDF 代码示例教程
使用IronPDF在 C# 中将 HTML 内容导出为 PDF,使用简单的方法,例如 Stream 和 BinaryData。 该 C# PDF 库使开发人员能够以编程方式将 HTML 转换为 PDF 文档,并将其提供给网络浏览器或保存到磁盘。
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 导出功能集成到他们的应用程序中。
最小工作流程(5 个步骤)
- 从 NuGet 安装 C# PDF 导出库。
- 探索数字签名方法的 `PdfDocument` 文档
- 使用 `System.IO.MemoryStream` 将 PDF 保存到内存中
- 将 PDF 以二进制数据而非 HTML 的形式提供给网络
- 将 PDF 导出为文件
保存 PDF 的不同选项有哪些?
在使用 C# 处理 PDF 文档时,IronPDF 提供了多种保存和导出生成 PDF 的选项。 从简单的文件存储到在网络应用程序中提供 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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
此方法支持添加密码保护。 查看以下文章,了解更多有关对导出的 PDF 进行数字签名的信息: 对 PDF 文档进行数字签名。有关其他安全选项,请浏览我们的PDF权限和密码指南。
如何在 C# 中将 PDF 文件保存到 MemoryStream (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();
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()
如何保存为二进制数据
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);
Imports IronPdf
' Example: Convert PDF to binary data
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 提供给网络,我们需要将其作为二进制数据而不是 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");
}
Imports System.IO
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf
' MVC Controller method for PDF export
Public Function DownloadInvoice(invoiceId As Integer) As IActionResult
' Generate your HTML content
Dim htmlContent As String = GenerateInvoiceHtml(invoiceId)
' Create PDF using IronPDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Get the PDF stream
Dim stream As MemoryStream = pdf.Stream
' Reset stream position
stream.Position = 0
' Return file to browser - will prompt download
Return New FileStreamResult(stream, "application/pdf") With {
.FileDownloadName = $"invoice_{invoiceId}.pdf"
}
End Function
' Alternative: Display PDF in browser instead of downloading
Public Function ViewInvoice(invoiceId As Integer) As IActionResult
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId))
' Return PDF for browser viewing
Return File(pdf.BinaryData, "application/pdf")
End Function
ASP.NET PDF 导出
对于传统的 ASP.NET WebForms 应用程序,您可以通过响应对象直接提供 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();
}
' ASP.NET WebForms PDF export
Protected Sub ExportButton_Click(sender As Object, e As EventArgs)
' Create your PDF document
Dim renderer As New ChromePdfRenderer()
' Configure rendering options
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
.PrintHtmlBackgrounds = True,
.CreatePdfFormsFromHtml = True
}
' Generate PDF from current page or custom HTML
Dim MyPdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml())
' Retrieves the PDF binary data
Dim Binary As Byte() = 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()
End Sub
高级导出场景
批量导出 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);
}
}
}
}
Imports System.IO.Compression
' Batch export multiple PDFs to a zip file
Public Sub ExportMultiplePdfsAsZip(htmlDocuments As List(Of String), zipFilePath As String)
Using zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)
Dim renderer = New ChromePdfRenderer()
For i As Integer = 0 To htmlDocuments.Count - 1
' Render each HTML document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlDocuments(i))
' Add to zip archive
Dim entry = zipArchive.CreateEntry($"document_{i + 1}.pdf")
Using entryStream = entry.Open()
pdf.Stream.CopyTo(entryStream)
End Using
Next
End Using
End Sub
基于用户权限的有条件导出
// 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;
}
' Export with different options based on user role
Public Function ExportPdfWithPermissions(htmlContent As String, userRole As UserRole) As Byte()
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Apply security based on user role
If userRole = UserRole.Guest Then
' Restrict printing and copying for guests
pdf.SecuritySettings.AllowUserPrinting = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
ElseIf userRole = UserRole.Standard Then
' Allow printing but not editing
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserEditing = False
End If
Return pdf.BinaryData
End Function
PDF 导出的最佳实践
在生产应用程序中导出 PDF 时,请考虑以下最佳实践:
1.内存管理:对于大型 PDF 或高流量应用程序,应正确处理 PDF 对象和流以防止内存泄漏。 考虑使用 async 方法以获得更好的性能。
2.错误处理:在导出 PDF 时,尤其是在可能出现网络问题的网络应用程序中,始终执行适当的错误处理。
3.PDF压缩:对于大型 PDF,在提供给用户之前,请使用 PDF压缩来减小文件大小。
4.元数据:设置适当的 PDF 元数据,包括标题、作者和创建日期,以便更好地管理文件。
5.跨平台兼容性:确保您的导出功能可在不同平台上运行。 IronPDF支持 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 用于在网络应用程序中提供 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 并保存到磁盘。

