在 ASP.NET Core MVC 中建立 PDF 檢視器 | 教學
開發人員如何在ASP.NET Core中將HTML轉換為PDF?
IronPDF使得在ASP.NET Core中使用Chrome的渲染引擎簡單地將HTML轉換為PDF,以便您只需幾行程式碼就可以將動態網頁內容、報告和發票轉換為精準的PDF,而保留所有CSS樣式和JavaScript功能。
在您的ASP.NET Core應用程式中,掙扎於獲得清晰、像素完美的報告和發票嗎?您並不孤單。
每個開發人員最終都需要將動態網頁內容(如報告或訂單確認)轉換為可靠的、可下載的PDF。 這是生成從發票和詳細報告到安全、可歸檔文件格式的一個基本要求。 挑戰在於將包含所有CSS和JavaScript的複雜HTML完美地渲染為PDF輸出。
那就是IronPDF的用武之地。 它在底層使用Chrome的渲染引擎,因此無論您在瀏覽器中看到什麼,就能在PDF輸出中得到什麼。 無論您是在處理ASPX頁面、現代Razor視圖或原始HTML字串,轉換過程都是一致且可預測的。
本指南將帶您了解最常見的ASP.NET Core HTML到PDF情境——從URL到PDF轉換、HTML字串渲染和HTML文件處理——每種方法都有可用的C#程式碼範例。
開始您的免費試用並今天就開始將HTML轉換為PDF文件。
您如何將PDF程式庫新增到ASP.NET Core專案中?
在NuGet套件管理器控制台中或通過.NET CLI安裝IronPDF只需一個命令。 IronPDF作為NuGet套件提供,並針對.NET 6、7、8和10目標:
Install-Package IronPdf
安裝後,IronPDF提供完整的HTML渲染能力,支持現代HTML元素、CSS樣式和JavaScript執行。 該程式庫可靠地處理複雜的HTML結構和CSS屬性,包括Bootstrap和Flex布局。
IronPDF支持在各種環境中的部署:
| 環境 | 支持級別 | 註釋 |
|---|---|---|
| Windows | 完全 | IIS和自托管,所有版本 |
| Linux | 完全 | Ubuntu、Debian、CentOS、Alpine |
| macOS | 完全 | Arm和x64架構 |
| Azure | 完全 | 應用服務、函式、容器 |
| AWS Lambda | 完全 | 無伺服器PDF生成 |
| Docker | 完全 | 包含遠程IronPDF引擎選項 |
安裝後,ChromePdfRenderer類是您的主要入口點。 它公開一個RenderingOptions屬性,您可以在那裡控制紙張大小、邊距、頁眉、JavaScript執行以及更多。 下面的部分涵蓋了一個典型的ASP.NET Core應用程式中將使用的三種主要轉換方法。
您如何將HTML字串轉換為PDF文件?
直接將HTML字串轉換為PDF文件是最直接的方法,不需要文件系統存取。 這使其成為從動態組裝的HTML(如訂單確證、發票或從資料庫填充的報告範本)生成PDF的理想選擇。
以下程式碼顯示了一個完整的ASP.NET Core控制器操作,使用IronPDF將HTML字串轉換為PDF:
using Microsoft.AspNetCore.Mvc;
using IronPdf;
namespace HtmlToPdf.Controllers
{
public class PdfController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult ConvertHtmlStringToPdf()
{
string htmlContent = @"
<html>
<head>
<title>IronPDF Test</title>
<style>
body { font-family: Arial; margin: 40px; }
h1 { color: #2b5797; }
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
th, td { border: 1px solid #ccc; padding: 8px; }
th { background: #f0f0f0; }
</style>
</head>
<body>
<h1>IronPDF HTML to PDF Test</h1>
<p>This is a simple test of converting an HTML string to PDF using IronPDF.</p>
<table>
<tr><th>Item</th><th>Price</th></tr>
<tr><td>Apples</td><td>$1.50</td></tr>
<tr><td>Bananas</td><td>$0.90</td></tr>
</table>
<p><em>End of test document.</em></p>
</body>
</html>";
// Initialize the PDF converter
var renderer = new ChromePdfRenderer();
// Configure page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 20;
renderer.RenderingOptions.MarginBottom = 20;
// Convert the HTML string to a PDF document
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
// Return the PDF file as a download
return File(pdfDocument.BinaryData, "application/pdf", "output.pdf");
}
}
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;
namespace HtmlToPdf.Controllers
{
public class PdfController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult ConvertHtmlStringToPdf()
{
string htmlContent = @"
<html>
<head>
<title>IronPDF Test</title>
<style>
body { font-family: Arial; margin: 40px; }
h1 { color: #2b5797; }
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
th, td { border: 1px solid #ccc; padding: 8px; }
th { background: #f0f0f0; }
</style>
</head>
<body>
<h1>IronPDF HTML to PDF Test</h1>
<p>This is a simple test of converting an HTML string to PDF using IronPDF.</p>
<table>
<tr><th>Item</th><th>Price</th></tr>
<tr><td>Apples</td><td>$1.50</td></tr>
<tr><td>Bananas</td><td>$0.90</td></tr>
</table>
<p><em>End of test document.</em></p>
</body>
</html>";
// Initialize the PDF converter
var renderer = new ChromePdfRenderer();
// Configure page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 20;
renderer.RenderingOptions.MarginBottom = 20;
// Convert the HTML string to a PDF document
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
// Return the PDF file as a download
return File(pdfDocument.BinaryData, "application/pdf", "output.pdf");
}
}
}
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf
Namespace HtmlToPdf.Controllers
Public Class PdfController
Inherits Controller
Public Function Index() As IActionResult
Return View()
End Function
<HttpGet>
Public Function ConvertHtmlStringToPdf() As IActionResult
Dim htmlContent As String = "
<html>
<head>
<title>IronPDF Test</title>
<style>
body { font-family: Arial; margin: 40px; }
h1 { color: #2b5797; }
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
th, td { border: 1px solid #ccc; padding: 8px; }
th { background: #f0f0f0; }
</style>
</head>
<body>
<h1>IronPDF HTML to PDF Test</h1>
<p>This is a simple test of converting an HTML string to PDF using IronPDF.</p>
<table>
<tr><th>Item</th><th>Price</th></tr>
<tr><td>Apples</td><td>$1.50</td></tr>
<tr><td>Bananas</td><td>$0.90</td></tr>
</table>
<p><em>End of test document.</em></p>
</body>
</html>"
' Initialize the PDF converter
Dim renderer = New ChromePdfRenderer()
' Configure page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 20
renderer.RenderingOptions.MarginBottom = 20
' Convert the HTML string to a PDF document
Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Return the PDF file as a download
Return File(pdfDocument.BinaryData, "application/pdf", "output.pdf")
End Function
End Class
End Namespace
生成的PDF看起來如何?

ChromePdfRenderer類處理整個轉換管道,將您的HTML字串轉換為格式正確的多頁PDF。 生成的文件保留了所有樣式 - 包括內嵌CSS、嵌入式樣式表,甚至是字體規則 - 與來源HTML中定義的一樣。 這種模式特別適合生成發票、報表,以及您從頭到尾通過程式碼控制其佈局的任何文件。
您可以擴展這種模式,在每一頁新增頁眉和頁腳或自定義水印。 IronPDF還支持PDF壓縮,以在不失去視覺質量的情況下減小文件大小。
您如何將HTML文件轉換為PDF文件?
當處理儲存在伺服器上的現有HTML模板文件時,IronPDF可以在保持所有連結資源(例如外部樣式表、本地圖像和JavaScript文件)的同時讀取並轉換它們。 這種方法很適合基於模板的文件生成管道,設計師在應用程式碼以外維護HTML文件:
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;
namespace YourApp.Controllers
{
public class DocumentController : Controller
{
private readonly IWebHostEnvironment _environment;
public DocumentController(IWebHostEnvironment environment)
{
_environment = environment;
}
[HttpGet]
public IActionResult GeneratePdfFromTemplate(string templateName)
{
// Resolve the full path to the HTML template
string htmlFilePath = Path.Combine(_environment.WebRootPath, "templates", $"{templateName}.html");
var renderer = new ChromePdfRenderer();
// Use print media type for print-optimized CSS rules
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
// Add a header to every generated page
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
Height = 25,
HtmlFragment = "<div style='text-align:center'>Company Report</div>"
};
// Convert the HTML file to a PDF document
var pdf = renderer.RenderHtmlFileAsPdf(htmlFilePath);
return File(pdf.BinaryData, "application/pdf", $"{templateName}_generated.pdf");
}
}
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;
namespace YourApp.Controllers
{
public class DocumentController : Controller
{
private readonly IWebHostEnvironment _environment;
public DocumentController(IWebHostEnvironment environment)
{
_environment = environment;
}
[HttpGet]
public IActionResult GeneratePdfFromTemplate(string templateName)
{
// Resolve the full path to the HTML template
string htmlFilePath = Path.Combine(_environment.WebRootPath, "templates", $"{templateName}.html");
var renderer = new ChromePdfRenderer();
// Use print media type for print-optimized CSS rules
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
// Add a header to every generated page
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
Height = 25,
HtmlFragment = "<div style='text-align:center'>Company Report</div>"
};
// Convert the HTML file to a PDF document
var pdf = renderer.RenderHtmlFileAsPdf(htmlFilePath);
return File(pdf.BinaryData, "application/pdf", $"{templateName}_generated.pdf");
}
}
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports System.IO
Namespace YourApp.Controllers
Public Class DocumentController
Inherits Controller
Private ReadOnly _environment As IWebHostEnvironment
Public Sub New(environment As IWebHostEnvironment)
_environment = environment
End Sub
<HttpGet>
Public Function GeneratePdfFromTemplate(templateName As String) As IActionResult
' Resolve the full path to the HTML template
Dim htmlFilePath As String = Path.Combine(_environment.WebRootPath, "templates", $"{templateName}.html")
Dim renderer As New ChromePdfRenderer()
' Use print media type for print-optimized CSS rules
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
' Add a header to every generated page
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.Height = 25,
.HtmlFragment = "<div style='text-align:center'>Company Report</div>"
}
' Convert the HTML file to a PDF document
Dim pdf = renderer.RenderHtmlFileAsPdf(htmlFilePath)
Return File(pdf.BinaryData, "application/pdf", $"{templateName}_generated.pdf")
End Function
End Class
End Namespace
模板轉換的結果如何出現?

這種方法從磁碟中讀取HTML文件並轉換它們,同時維持完整的文件結構。 所有的CSS屬性、圖像引用和複雜的HTML元素(如表格和巢狀容器)在輸出中都得到保留。 IronPDF會根據源文件的位置解析相對資源路徑,因此連結的樣式表和圖像可以無需額外設置地載入。
IronPDF還正確支持CSS列印媒體查詢,這意味著您可以在HTML模板中定義列印特定規則——隱藏導航欄、調整字體大小或啟用分頁提示——這些規則只在PDF生成期間應用,而不是在瀏覽器中載入頁面時。
您如何轉換需要身份驗證的頁面?
ASP.NET Core應用程式通常會保護內容,使用表單身份驗證。 在轉換需要有效會話的頁面時,IronPDF可以將身份驗證Cookie與HTTP請求一同傳遞,使渲染的頁面反映出已身份驗證的使用者所看到的內容:
[Authorize]
public IActionResult ConvertAuthenticatedPage()
{
var renderer = new ChromePdfRenderer();
// Build the URL for the protected resource
string currentUrl = $"{Request.Scheme}://{Request.Host}/SecureContent";
// Forward the authentication cookie to IronPDF
var authCookie = Request.Cookies[".AspNetCore.Cookies"];
if (!string.IsNullOrEmpty(authCookie))
{
renderer.RenderingOptions.CustomCookies = new System.Collections.Generic.Dictionary<string, string>
{
{ ".AspNetCore.Cookies", authCookie }
};
}
// Convert the authenticated page to a PDF file
var pdf = renderer.RenderUrlAsPdf(currentUrl);
return File(pdf.BinaryData, "application/pdf", "secure_document.pdf");
}
[Authorize]
public IActionResult ConvertAuthenticatedPage()
{
var renderer = new ChromePdfRenderer();
// Build the URL for the protected resource
string currentUrl = $"{Request.Scheme}://{Request.Host}/SecureContent";
// Forward the authentication cookie to IronPDF
var authCookie = Request.Cookies[".AspNetCore.Cookies"];
if (!string.IsNullOrEmpty(authCookie))
{
renderer.RenderingOptions.CustomCookies = new System.Collections.Generic.Dictionary<string, string>
{
{ ".AspNetCore.Cookies", authCookie }
};
}
// Convert the authenticated page to a PDF file
var pdf = renderer.RenderUrlAsPdf(currentUrl);
return File(pdf.BinaryData, "application/pdf", "secure_document.pdf");
}
Imports System.Collections.Generic
Imports IronPdf
<Authorize>
Public Function ConvertAuthenticatedPage() As IActionResult
Dim renderer As New ChromePdfRenderer()
' Build the URL for the protected resource
Dim currentUrl As String = $"{Request.Scheme}://{Request.Host}/SecureContent"
' Forward the authentication cookie to IronPDF
Dim authCookie As String = Request.Cookies(".AspNetCore.Cookies")
If Not String.IsNullOrEmpty(authCookie) Then
renderer.RenderingOptions.CustomCookies = New Dictionary(Of String, String) From {
{".AspNetCore.Cookies", authCookie}
}
End If
' Convert the authenticated page to a PDF file
Dim pdf = renderer.RenderUrlAsPdf(currentUrl)
Return File(pdf.BinaryData, "application/pdf", "secure_document.pdf")
End Function
這種技術會捕捉到位於登錄牆後的頁面的完整渲染輸出。 當目標URL屬於同一應用程式時,所有的相對資源路徑都會正確解析,因為渲染器繼承了相同的基本URL上下文。 您還可以配置自定義HTTP請求標頭以進行API鍵身份驗證或其他基於標頭的安全架構。
為了在生成後獲得更強的文件安全性,請考慮應用PDF密碼和權限或數位簽署您的PDF以防止未經授權的修改。 IronPDF還支持PDF/A合規性,以進行長期歸檔和PDF/UA格式以滿足無障礙需求,這對於受規管行業可能很重要。
轉換ASPX文件和動態JavaScript內容又如何呢?
對於舊版ASPX頁面的轉換或依賴於JavaScript在運行時填充內容的文件,IronPDF可以可靠地處理渲染過程。 您可以配置渲染延遲以讓JavaScript完成執行,然後捕捉頁面:
public IActionResult ConvertDynamicContent()
{
var renderer = new ChromePdfRenderer();
// Enable JavaScript so dynamic content renders correctly
renderer.RenderingOptions.EnableJavaScript = true;
// Wait 1 second after page load for JavaScript to complete
renderer.RenderingOptions.WaitFor.RenderDelay(1000);
// Generate your dynamic HTML string
string dynamicHtml = GenerateDynamicHtml();
var pdf = renderer.RenderHtmlAsPdf(dynamicHtml);
return File(pdf.BinaryData, "application/pdf", "dynamic.pdf");
}
public IActionResult ConvertDynamicContent()
{
var renderer = new ChromePdfRenderer();
// Enable JavaScript so dynamic content renders correctly
renderer.RenderingOptions.EnableJavaScript = true;
// Wait 1 second after page load for JavaScript to complete
renderer.RenderingOptions.WaitFor.RenderDelay(1000);
// Generate your dynamic HTML string
string dynamicHtml = GenerateDynamicHtml();
var pdf = renderer.RenderHtmlAsPdf(dynamicHtml);
return File(pdf.BinaryData, "application/pdf", "dynamic.pdf");
}
Imports IronPdf
Public Function ConvertDynamicContent() As IActionResult
Dim renderer As New ChromePdfRenderer()
' Enable JavaScript so dynamic content renders correctly
renderer.RenderingOptions.EnableJavaScript = True
' Wait 1 second after page load for JavaScript to complete
renderer.RenderingOptions.WaitFor.RenderDelay(1000)
' Generate your dynamic HTML string
Dim dynamicHtml As String = GenerateDynamicHtml()
Dim pdf = renderer.RenderHtmlAsPdf(dynamicHtml)
Return File(pdf.BinaryData, "application/pdf", "dynamic.pdf")
End Function
轉換後的動態內容看起來如何?

HTML到PDF轉換中的一個常見難題是不希望的分頁打斷,將標題與其內容分開,或者將表格行切割在行中。 IronPDF通過可配置的分頁控制來解決此問題,使用標準CSS page-break-before 和 page-break-inside 規則以及IronPDF的WaitFor API。 該程式庫還支持異步PDF生成,以提高高流量情況下的吞吐量。
對於進階的JavaScript應用,例如由D3.js渲染的圖表或React組件,您可以在渲染快照拍攝之前注入和執行自訂JavaScript,以確保圖表或組件已完全載入,然後生成PDF。
您如何處理CSS樣式和進階HTML渲染?
IronPDF的渲染引擎通過其完整的渲染選項API支持進階CSS和HTML5功能。 在將HTML轉換為PDF時,該程式庫正確解釋CSS屬性——包括使用Flexbox、CSS Grid和響應式媒體查詢構建的複雜布局。 PDF輸出保持源頁面的視覺效果,包括外部樣式表、內嵌樣式和在頁面捕捉前更改DOM的JavaScript渲染內容。
轉換過程處理多頁文件、空白頁抑制和自動頁面大小調整,無需手動配置。 它還管理專門場景,例如在特定頁上應用不同的頁眉或頁腳,或優雅地處理橫跨幾十頁的報告内容。
值得了解的額外渲染能力:
- 國際文字:對UTF-8編碼和國際語言的全面支持,包括如阿拉伯語和希伯來語等從右到左的文字
- 矢量圖形:原生SVG渲染無需光柵化,因此圖形在任何縮放級別都保持清晰
- 文件結構:目錄生成、書籤支持和PDF元資料編輯,例如作者、標題和關鍵字字段
- 後期處理:合併或拆分PDFs、提取文字和圖像,以及以程式化方式建立可填寫表單
這些功能使IronPDF成為文件密集型應用程式的實際選擇,當基本轉換器的輸出質量不能滿足生產需求時。 對於.NET中不熟悉PDF生成的團隊,Microsoft的ASP.NET Core文件提供了有關控制器操作和中介軟體的良好背景知識,在將任何PDF圖書館整合到web應用程式中時這些知識是有益的。
為什麼這是您.NET專案中合適的PDF程式庫?
IronPDF是一個適用於生產環境的.NET程式庫,用於HTML到PDF轉換,提供較Aspose、iText和Syncfusion更可靠的性能。 與基本的PDF轉換器不同,它完全支持現代Web標準,處理從簡單的HTML字串到包含JavaScript渲染內容和表單驗證的複雜Web應用程式。
該程式庫同樣適用於Blazor應用程式和MAUI專案,除了C#之外還可以與F#一同使用。 對於企業環境,IronPDF支持IIS托管、Azure 函式和Docker容器。
IronPDF在開發期間是免費試用的。 立即下載IronPDF,開始將HTML內容轉換為專業的PDF文件。 探索完整的文件資料、程式碼範例和API參考,充分利用您的ASP.NET Core應用程式中的HTML到PDF轉換。
常見問題
開發者如何能在 ASP.NET Core 中將 HTML 轉換為 PDF?
開發者可以使用 IronPDF 在 ASP.NET Core 中將 HTML 轉換為 PDF,它提供了一個簡單的 API,用於將 HTML 內容渲染為 PDF 文件,這包括將 HTML 字串、檔案,甚至是已認證的網頁轉換為 PDF。
IronPDF 的 HTML 到 PDF 轉換有哪些關鍵特色?
IronPDF 提供了 HTML5、CSS、JavaScript 和複雜頁面佈局的支援。它還可以讓開發者輕鬆將 HTML 字串、URL 和本地 HTML 檔案轉換為 PDF 文件。
IronPDF 能在轉換過程中處理已認證的網頁嗎?
是的,IronPDF 能處理已認證的網頁。它支持轉換需要身份驗證的頁面,確保從受保護的網頁內容生成安全且準確的 PDF。
IronPDF 如何確保轉換的 PDF 質量?
IronPDF 通過準確渲染 HTML 內容(包括樣式、字型和圖像)來確保 PDF 的高品質輸出,使用先進的渲染引擎確保最終 PDF 緊密匹配原始 HTML 佈局。
是否可以使用 IronPDF 將 HTML 字串轉換為 PDF?
是的,IronPDF 可以直接將 HTML 字串轉換為 PDF 文件。此功能對於在網頁應用程式中動態生成 PDF 非常有用。
IronPDF 支援將本地 HTML 檔案轉換為 PDF 嗎?
IronPDF 支援通過指定檔案路徑將本地 HTML 檔案轉換為 PDF。此功能使從儲存在伺服器上的靜態 HTML 檔案生成 PDF 變得容易。
IronPDF 支援哪些編程語言?
IronPDF 是為 C# 和 VB.NET 設計的,這使得它非常適合在 .NET 生態系統中工作的開發者在其應用程式中新增 PDF 生成功能。
IronPDF 能處理複雜的 HTML 佈局和樣式嗎?
是的,IronPDF 能輕鬆處理包括 CSS 和 JavaScript 在內的複雜 HTML 佈局和樣式,保證結果 PDF 維持原始網頁的設計和功能。
在 ASP.NET 應用中將 HTML 轉換為 PDF 有哪些用例?
一些用例包括從網頁頁面生成發票、報告和文件,存檔網頁內容,以及建立網頁的可下載離線使用的 PDF 版本。
IronPDF 與其他 HTML 到 PDF 轉換工具相比如何?
IronPDF 因其易於使用、強大的功能集及對各種 HTML 元素和身份驗證的優秀支援而脫穎而出,為尋求高品質 PDF 生成的開發者提供了一個可靠的解決方案。

