C# 导出到 PDF 代码示例教程

查克尼特·宾
查克尼特·宾
2023年一月25日
更新 2024年十二月10日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPDF 是一个 C# PDF 库,允许您使用 C# 将 HTML 保存为 PDF。 它还允许 C# / VB 开发者以编程方式编辑 PDF 文档。

开始使用IronPDF

立即在您的项目中开始使用IronPDF,并享受免费试用。

第一步:
green arrow pointer



保存 PDF 的选项

如何将 PDF 保存到磁盘

使用PdfDocument.SaveAs方法将PDF保存到磁盘。

您会发现此方法支持添加密码保护。 查看以下文章以了解更多关于数字签署导出 PDF 的信息:'数字签署 PDF 文档.'

如何在 C# 中将 PDF 文件保存到 MemoryStream(System.IO.MemoryStream

IronPdf.PdfDocument.Stream 属性使用 System.IO.MemoryStream 将 PDF 保存到内存中。

如何保存二进制数据

IronPdf.PdfDocument.BinaryData 属性将 PDF 文档以二进制数据的形式导出到内存中。

这将输出 PDF 为ByteArray,在 C# 中表示为byte []

如何从Web服务器提供到浏览器

要向网络提供 PDF,我们需要将其作为二进制数据而不是 HTML 发送。

MVC PDF 导出

// Send MyPdfDocument.Stream to this method
return new FileStreamResult(stream, "application/pdf")
{
    FileDownloadName = "file.pdf"
};
// Send MyPdfDocument.Stream to this method
return new FileStreamResult(stream, "application/pdf")
{
    FileDownloadName = "file.pdf"
};
' Send MyPdfDocument.Stream to this method
Return New FileStreamResult(stream, "application/pdf") With {.FileDownloadName = "file.pdf"}
$vbLabelText   $csharpLabel

ASP.NET PDF 导出

byte [] Binary = MyPdfDocument.BinaryData;
Response.Clear();
Response.ContentType = "application/octet-stream";
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();      
byte [] Binary = MyPdfDocument.BinaryData;
Response.Clear();
Response.ContentType = "application/octet-stream";
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();      
Dim Binary() As Byte = MyPdfDocument.BinaryData
Response.Clear()
Response.ContentType = "application/octet-stream"
Context.Response.OutputStream.Write(Binary, 0, Binary.Length)
Response.Flush()
$vbLabelText   $csharpLabel
查克尼特·宾
软件工程师
Chaknith 负责 IronXL 和 IronBarcode 的工作。他在 C# 和 .NET 方面拥有深厚的专业知识,帮助改进软件并支持客户。他从用户互动中获得的洞察力,有助于提升产品、文档和整体体验。