C# 匯出到 PDF 代碼範例教程

查克尼思·賓
查克尼思·賓
2023年1月25日
已更新 2024年12月10日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPDF 是一個C# PDF Library,可讓您使用 C# 將 HTML 保存為 PDF。 它還允許C# / VB開發人員以程式設計方式編輯PDF文件。

開始使用 IronPDF

立即在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer



儲存 PDF 的選項

如何將PDF保存到磁盤

使用PdfDocument.SaveAs方法將您的PDF保存到磁碟。

您會發現這個方法支持添加密碼保護。 請查看以下文章以了解更多關於數位簽署匯出PDF的資訊:'數位簽署PDF文件'。

如何將 PDF 檔案儲存到 C# 中的 MemoryStream (System.IO.MemoryStream)

IronPdf.PdfDocument.Stream 屬性使用 System.IO.MemoryStream 將 PDF 保存到記憶體中。

如何保存到二進制數據

IronPdf.PdfDocument.BinaryData 屬性將 PDF 文件匯出為內存中的二進位數據。

這會將 PDF 輸出為 ByteArray,在 C# 中表示為 byte []

如何從網絡伺服器提供到瀏覽器

要將 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"
};

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();      
查克尼思·賓
軟體工程師
Chaknith 致力於 IronXL 和 IronBarcode。他在 C# 和 .NET 方面擁有豐富的專業知識,協助改進軟體並支持客戶。他從用戶互動中獲得的洞察力有助於提高產品、文檔和整體體驗。