C# 匯出到 PDF 代碼範例教程
IronPDF 是一個C# PDF Library,可讓您使用 C# 將 HTML 保存為 PDF。 它還允許C# / VB開發人員以程式設計方式編輯PDF文件。
開始使用 IronPDF
立即在您的專案中使用IronPDF,並享受免費試用。
如何在 C# 中導出 PDF
- 從NuGet下載並安裝C# PDF匯出庫
- 探索PdfDocument文檔以發現數位簽署匯出PDF的方法
- 使用 System.IO.MemoryStream 儲存 PDF 至記憶體
- 以二進位數據而非HTML格式將PDF提供給網頁
- 將 PDF 匯出為檔案
儲存 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();