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 文件。


C# NuGet 程式庫用于 PDF

安裝與 NuGet

Install-Package IronPdf
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

C# NuGet 程式庫用于 PDF

安裝與 NuGet

Install-Package IronPdf
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

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

第一步:
green arrow pointer

查看 IronPDFNuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變PDF。

C# NuGet 程式庫用于 PDF nuget.org/packages/IronPdf/
Install-Package IronPdf

請考慮安裝 IronPDF DLL 直接下載並手動安裝到您的專案或GAC表單: IronPdf.zip

手動安裝到您的項目中

下載DLL

儲存 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 [].

如何從網頁伺服器提供檔案給瀏覽器

要將 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#