如何在 ASP.NET Core 中顯示 PDF 文件
PDF文件廣泛用於文件共享和資料展示。 在 Web 應用程式中,經常需要直接在瀏覽器中向使用者顯示 PDF 檔案。 ASP.NET Core 應用程式提供了多種實現此功能的選項,而 IronPDF 是處理 PDF 檔案的一種流行庫。
IronPDF是一個功能強大的 .NET 程式庫,它允許開發人員輕鬆建立、編輯和操作 PDF 文件。 本文將探討如何使用 IronPDF 在 ASP.NET Core PDF 檢視器應用程式中顯示 PDF 檔案。 本文將介紹設定必要元件的步驟,並提供範例邏輯來示範 ASP.NET Core PDF 檢視器整合。
營造環境
首先,請確保您已具備以下先決條件:
- Visual Studio:安裝最新版本的 Visual Studio 或您選擇的任何其他相容的整合開發環境 (IDE)。
-
IronPDF 庫:從IronPDF 官方網站或透過 NuGet 套件管理器取得 IronPDF 庫。
如何在 ASP.NET Core 中顯示 PDF 文件,圖 1:NuGet 套件管理器 NuGet 套件管理器
- .NET Core 應用程式:請確保您已基本了解ASP.NET Core 安裝說明,並將其安裝在您的開發電腦上。
環境設定完成後,讓我們深入了解如何在 ASP.NET Core 應用程式中使用 IronPDF 顯示 PDF 檔案。
建立新專案
-
開啟 Visual Studio 並建立一個新的 ASP.NET Core Web 應用程式專案。
-
選擇"ASP.NET Core Web App"範本。
- 選擇所需的項目設置,然後按一下"建立"以產生新項目。
新增 IronPDF 庫
要在您的專案中使用 IronPDF,您需要新增 IronPDF 庫引用。
-
在解決方案資源管理器中右鍵單擊項目,然後選擇"管理解決方案的 NuGet 套件..."
如何在 ASP.NET Core 中顯示 PDF 文件,圖 4:NuGet 套件管理器 NuGet 套件管理器
-
在 NuGet 套件管理器中搜尋"IronPDF",並安裝該套件的最新版本。
如何在 ASP.NET Core 中顯示 PDF 文件,圖 5:NuGet 套件管理器 - 解決方案資源管理器 NuGet 套件管理器 - 解決方案資源管理器
使用 ASP.NET Core 網頁建立 PDF
若要從伺服器端的 ASP.NET Core 網頁建立 PDF,請依照下列步驟操作:
如何在 ASP.NET Core 中顯示 PDF 文件,圖 6:NuGet 套件管理器 - 解決方案資源管理器 解決方案探索器
步驟 1 新增 IronPDF 命名空間
開啟要轉換為 PDF 的 ASP.NET Core 網頁的來源檔案路徑。 在程式碼隱藏檔案(Index.cshtml.cs)的頂部新增 IronPdf 命名空間:
using IronPdf;
using IronPdf;
Imports IronPdf
步驟 2:將 Razor 頁面轉換為 PDF
在 OnGet 函數內部,新增以下程式碼:
public FileContentResult OnGet()
{
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the current Razor page to a PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
// Add HTTP header to display PDF in the browser
Response.Headers.Add("Content-Disposition", "inline");
// Return the PDF file to the client
return File(pdf.BinaryData, "application/pdf");
}
public FileContentResult OnGet()
{
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the current Razor page to a PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
// Add HTTP header to display PDF in the browser
Response.Headers.Add("Content-Disposition", "inline");
// Return the PDF file to the client
return File(pdf.BinaryData, "application/pdf");
}
Public Function OnGet() As FileContentResult
' Create a new instance of ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the current Razor page to a PDF document
Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)
' Add HTTP header to display PDF in the browser
Response.Headers.Add("Content-Disposition", "inline")
' Return the PDF file to the client
Return File(pdf.BinaryData, "application/pdf")
End Function
只需一行程式碼,即可使用 RenderRazorToPdf 方法將 Razor 頁面轉換為 PDF 文件。
步驟 3 顯示或下載 PDF
預設情況下,程式碼會在瀏覽器中顯示 PDF 文件。 如果您想下載 PDF 文件,請按以下方式修改程式碼:
return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf");
return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf");
Return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf")
這段程式碼會將 ASP.NET 網頁的 PDF 檔案下載到您本地的"下載"資料夾中。
如何在 ASP.NET Core 中顯示 PDF 文件,圖 7:ASPX 頁面轉 PDF Razor Page 轉 PDF
在 ASP.NET Core 中載入和顯示 PDF 文件
接下來,本節將探討使用 IronPDF 產生 PDF 檔案並在 ASP.NET Core 應用程式中顯示它們的不同方法。
從 URL 產生 PDF
IronPDF 透過從 URL(HTTP 服務)產生 HTML 檔案並將其轉換為 PDF,簡化了建立 PDF 文件的過程。 以下程式碼示範如何從 URL 產生 PDF 檔案:
// Render a PDF from a URL
using var pdf = new IronPdf.ChromePdfRenderer().RenderUrlAsPdf("https://www.google.co.in/");
// Read the File as Byte Array
byte[] bytes = pdf.BinaryData;
// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
// Render a PDF from a URL
using var pdf = new IronPdf.ChromePdfRenderer().RenderUrlAsPdf("https://www.google.co.in/");
// Read the File as Byte Array
byte[] bytes = pdf.BinaryData;
// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
' Render a PDF from a URL
Dim pdf = (New IronPdf.ChromePdfRenderer()).RenderUrlAsPdf("https://www.google.co.in/")
' Read the File as Byte Array
Dim bytes() As Byte = pdf.BinaryData
' Convert File to Base64 string and send to Client
Dim base64 As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Return Content(base64)
在上面的程式碼中,IronPDF 的ChromePdfRenderer 類別用於渲染指定 URL 中的 HTML 內容並將其轉換為 PDF 文件。 然後,將 PDF 文件轉換為位元組數組,並以 base64 字串的形式傳送給客戶端。
從 HTML 字串產生 PDF
IronPDF 提供了一種將 HTML 字串轉換為 PDF 文件的有效方法。 以下程式碼片段示範如何從字串產生 PDF 檔案:
// Render a PDF from an HTML string
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
// Render a PDF from an HTML string
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
' Render a PDF from an HTML string
Dim pdf = (New IronPdf.ChromePdfRenderer()).RenderHtmlAsPdf("<h1>Hello world!!</h1>")
在上面的範例中, RenderHtmlAsPdf 方法用於渲染 HTML 字串並將其轉換為 PDF 文件。 產生的 PDF 檔案可根據應用程式的要求進行進一步處理或保存。
從 HTML 檔案產生 PDF
IronPDF 也支援將 HTML 檔案或 CSS 檔案轉換為PDF 文件範例。 以下程式碼展示如何從 HTML 檔案產生 PDF 檔案:
// Render a PDF from an HTML file
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html");
// Read the file as Byte Array
byte[] bytes = pdf.BinaryData;
// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
// Render a PDF from an HTML file
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html");
// Read the file as Byte Array
byte[] bytes = pdf.BinaryData;
// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
' Render a PDF from an HTML file
Dim pdf = (New IronPdf.ChromePdfRenderer()).RenderHtmlFileAsPdf("demo.html")
' Read the file as Byte Array
Dim bytes() As Byte = pdf.BinaryData
' Convert File to Base64 string and send to Client
Dim base64 As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Return Content(base64)
在上面的程式碼片段中, RenderHtmlFileAsPdf 方法用於渲染指定檔案名稱中的 HTML 內容並將其轉換為 PDF 文件。 產生的 PDF 檔案被轉換為位元組數組,並以 base64 字串的形式傳送給客戶端。
使用 IronPDF 從 ASP.NET Web API 將 ASP.NET Web Forms 轉換為 PDF 文件
您只需一行程式碼即可輕鬆地將 ASP.NET Web 表單轉換為 PDF 格式,而無需使用 HTML。 將此程式碼放入頁面程式碼隱藏檔案的 Page_Load 方法中,即可在頁面上顯示它。
導入 IronPdf 命名空間
在程式碼隱藏檔案中使用 using 關鍵字匯入 IronPdf 命名空間。
using IronPdf;
using System;
using System.Web.UI;
using IronPdf;
using System;
using System.Web.UI;
Imports IronPdf
Imports System
Imports System.Web.UI
將 ASP.NET Web 表單轉換為 PDF
在要轉換為 PDF 的頁面的程式碼隱藏檔案中(例如,Default.aspx.cs),新增以下程式碼:
namespace WebApplication7
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Convert the ASPX page to a PDF displayed in the browser
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
}
}
}
namespace WebApplication7
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Convert the ASPX page to a PDF displayed in the browser
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
}
}
}
Namespace WebApplication7
Partial Public Class _Default
Inherits Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Convert the ASPX page to a PDF displayed in the browser
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser)
End Sub
End Class
End Namespace
AspxToPdf 類別的 RenderThisPageAsPdf 方法將透過 Web API 將 Web 表單轉換為 PDF 文件。
應用 HTML 模板
對於企業內部網路和網站開發人員來說,使用範本產生 PDF 檔案通常是常見的需求。 IronPDF 簡化了這個過程,讓您可以產生 HTML 模板並填入資料。
以下範例展示如何使用 HTML 範本和 IronPDF 產生多個自訂 PDF 檔案:
// Define an HTML template with placeholders
string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
// Replace placeholder in template with actual data
string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
// Render HTML to PDF
using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
{
// Save the PDF with the name as filename
Pdf.SaveAs(name + ".pdf");
}
}
// Define an HTML template with placeholders
string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
// Replace placeholder in template with actual data
string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
// Render HTML to PDF
using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
{
// Save the PDF with the name as filename
Pdf.SaveAs(name + ".pdf");
}
}
' Define an HTML template with placeholders
Dim HtmlTemplate As String = "<p>[[NAME]]</p>"
Dim Names() As String = { "John", "James", "Jenny" }
For Each name In Names
' Replace placeholder in template with actual data
Dim HtmlInstance As String = HtmlTemplate.Replace("[[NAME]]", name)
' Render HTML to PDF
Using Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance)
' Save the PDF with the name as filename
Pdf.SaveAs(name & ".pdf")
End Using
Next name
ASP MVC 路由 下載此頁面的 PDF 版本
如果您使用的是 ASP.NET MVC,您可以輕鬆地將使用者引導至 PDF 檔案。以下是原始碼編寫範例:
using IronPdf;
using System;
using System.Web.Mvc;
namespace WebApplication8.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the URL as a PDF
using (var PDF = renderer.RenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
{
// Return the PDF file with a specified filename
return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
}
}
// Other action methods...
}
}
using IronPdf;
using System;
using System.Web.Mvc;
namespace WebApplication8.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the URL as a PDF
using (var PDF = renderer.RenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
{
// Return the PDF file with a specified filename
return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
}
}
// Other action methods...
}
}
Imports IronPdf
Imports System
Imports System.Web.Mvc
Namespace WebApplication8.Controllers
Public Class HomeController
Inherits Controller
Public Function Index() As IActionResult
' Create a new instance of ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the URL as a PDF
Using PDF = renderer.RenderUrlAsPdf(New Uri("https://en.wikipedia.org"))
' Return the PDF file with a specified filename
Return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf")
End Using
End Function
' Other action methods...
End Class
End Namespace
為 PDF 文件新增封面頁
若要為現有 PDF 文件新增封面或封底,可以使用 IronPDF 的合併功能。 以下是一個範例:
using (var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"))
{
// Merge the cover page with the main PDF
using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
{
// Save the combined PDF
Merged.SaveAs("Combined.Pdf");
}
}
using (var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"))
{
// Merge the cover page with the main PDF
using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
{
// Save the combined PDF
Merged.SaveAs("Combined.Pdf");
}
}
Using PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
' Merge the cover page with the main PDF
Using Merged = PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), PDF)
' Save the combined PDF
Merged.SaveAs("Combined.Pdf")
End Using
End Using
為文件添加浮水印
您也可以使用 C# 程式碼為 PDF 文件新增浮水印。 以下是一個範例:
using IronPdf;
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the URL as a PDF
using (var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
// Add watermark text to all pages
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45);
// Save the watermarked PDF
pdf.SaveAs(@"C:\PathToWatermarked.pdf");
}
using IronPdf;
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the URL as a PDF
using (var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
// Add watermark text to all pages
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45);
// Save the watermarked PDF
pdf.SaveAs(@"C:\PathToWatermarked.pdf");
}
Imports IronPdf
' Create a new instance of ChromePdfRenderer
Private renderer As New ChromePdfRenderer()
' Render the URL as a PDF
Using pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
' Add watermark text to all pages
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45)
' Save the watermarked PDF
pdf.SaveAs("C:\PathToWatermarked.pdf")
End Using
使用密碼保護您的 PDF 文件
您可以使用 IronPDF 對 PDF 文件進行加密,並用密碼保護它。 以下是一個範例:
using IronPdf;
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render HTML to PDF
using (var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
// Set a password to protect the PDF
pdfDocument.Password = "strong!@#pass&^%word";
// Save the secured PDF
pdfDocument.SaveAs("secured.pdf");
}
using IronPdf;
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render HTML to PDF
using (var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
// Set a password to protect the PDF
pdfDocument.Password = "strong!@#pass&^%word";
// Save the secured PDF
pdfDocument.SaveAs("secured.pdf");
}
Imports IronPdf
' Create a new instance of ChromePdfRenderer
Private renderer As New ChromePdfRenderer()
' Render HTML to PDF
Using pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>")
' Set a password to protect the PDF
pdfDocument.Password = "strong!@#pass&^%word"
' Save the secured PDF
pdfDocument.SaveAs("secured.pdf")
End Using
除了上述功能外,IronPDF 還提供其他功能,例如使用 OCR 從 PDF 中提取圖像和文字、將圖表渲染到 PDF 、向 PDF 添加條碼、使用密碼和水印技術增強 PDF 文件的安全性,甚至處理和自訂 PDF 表單等等。 使用 IronPDF,您可以簡化建立 PDF 的過程,並提高文件的整體呈現效果。
結論
IronPDF 是一款專為 .NET 開發人員設計的卓越工具,提供廣泛的功能,可輕鬆處理 .NET 專案中的 PDF 操作。 透過 IronPDF,開發人員可以增強工作流程並簡化工作流程。 這款強大的工具提供了眾多功能,可實現無縫的 PDF 文件格式化、頁面刪除、頁面添加等等。 它使開發人員能夠根據自身特定需求有效地管理和自訂 PDF 文件。
IronPDF不僅功能強大,還提供免費的開發用途,這無疑是一大優勢。 這意味著開發人員可以在專案開發階段利用其功能而無需承擔任何成本。 透過使用 IronPDF,開發人員可以提高工作效率,並在與 PDF 相關的任務中取得顯著成果,最終在 .NET 專案中交付高品質、高效率的解決方案。
還有許多其他有用的庫,例如用於處理 PDF 文件的 IronPDF、用於處理 Excel 文件的 IronXL 以及用於處理 OCR 的 IronOCR。 目前,購買完整的 Iron Suite 套件,即可享受僅需兩個庫的價格獲得全部五個庫。請造訪我們的Iron 軟體授權資訊頁面以了解更多詳情。
常見問題解答
如何在 ASP.NET Core Web App 中顯示 PDF 文件?
您可以使用 IronPDF 庫在 ASP.NET Core Web App 中顯示 PDF 文件。首先通過 NuGet 套件管理器安裝 IronPDF 套件,然後使用 RenderRazorToPdf 或 RenderHtmlAsPdf 方法將 Razor 頁面或 HTML 字符串轉換為 PDF 文件以進行顯示。
設置 ASP.NET Core 項目以顯示 PDF 的步驟是什麼?
要設置 ASP.NET Core 項目以顯示 PDF,安裝 Visual Studio,創建新的 ASP.NET Core Web App 項目,通過 NuGet 添加 IronPDF 庫,並使用其方法將 PDF 文件渲染和顯示在您的應用程序中。
如何使用 C# 將 HTML 字符串轉換為 PDF?
要在 C# 中將 HTML 字符串轉換為 PDF,使用 IronPDF 的 RenderHtmlAsPdf 方法。這允許您將 HTML 內容渲染為 PDF 文件,然後可以在 ASP.NET Core 應用中顯示。
我可以將 ASP.NET Razor 頁面轉換為 PDF 嗎?
是的,您可以使用 IronPDF 將 ASP.NET Razor 頁面轉換為 PDF。在您的代碼後置文件中添加 IronPDF 命名空間,並使用 RenderRazorToPdf 方法將 Razor 頁面渲染為 PDF 文件。
如何將封面頁添加到 PDF 文件?
您可以使用 IronPDF 將額外的 HTML 頁面或文件作為 PDF 文件的首頁渲染為封面頁,然後將其與主要 PDF 內容合併。
是否可以使用 C# 合併多個 PDF 文件?
是的,IronPDF 提供了合併多個 PDF 文件的功能。您可以使用 PdfDocument.Merge 方法將多個 PDF 合併為一個文件。
如何將水印應用到 PDF 的所有頁面?
要將水印應用到 PDF 的所有頁面,使用 IronPDF 的 WatermarkAllPages 方法。這使您可以將文本或圖像作為水印疊加在文檔的每一頁。
使用 IronPDF 對 .NET 開發者有何好處?
IronPDF 對 .NET 開發者非常有益,因為它提供了一個強大且靈活的 PDF 操作庫,包括轉換、編輯和在網頁應用中顯示 PDF。它提高了生產力並簡化了工作流程,是開發者工具包中的寶貴工具。
如何在 C# 中使用密碼保護 PDF 文件?
要在 C# 中使用密碼保護 PDF 文件,使用 IronPDF 渲染您的內容,然後在保存前在 PdfDocument 物件上設置密碼。這確保只有授權用戶才能打開文件。
IronPDF支持.NET 10,我如何在.NET 10項目中使用它?
是的,IronPDF完全兼容.NET 10。這個程式庫支持.NET 10(以及.NET 9, 8, 7等),並且可以在網頁、桌面、控制台和雲端環境中使用,無需特殊配置。要使用它,只需在您的.NET 10項目中通過NuGet引用IronPDF,然後像往常一樣調用ChromePdfRenderer().RenderHtmlAsPdf(...)等方法。
.NET 10有什麼新的功能可以提高IronPDF的性能嗎?
是的,.NET 10引入了性能提升,例如減少堆內存分配、結構的逃逸分析和數組接口方法的去虛擬化,這些提升改善了運行時效率。IronPDF從這些改進中受益,特別是在HTML到PDF渲染和多線程或高並發場景中。



