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

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文件.'

如何將 PDF 檔案儲存到記憶體流中 C# (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"
};
' Send MyPdfDocument.Stream to this method
Return New FileStreamResult(stream, "application/pdf") With {.FileDownloadName = "file.pdf"}
VB   C#

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()
VB   C#