如何使用 C# 在 ASP.NET MVC 中將視圖轉換為 PDF(HTML轉PDF)
IronPDF可讓您使用 ChromePdfRenderer.RenderView() 方法,只需幾行程式碼即可將ASP.NET MVC 視圖轉換為 PDF 文件。 IronPDF套件提供與ASP.NET MVC 專案的無縫集成,用於將 CSHTML 視圖渲染為 PDF。
View 是ASP.NET框架中的一個元件,用於在 Web 應用程式中產生 HTML 標記。 它是模型-視圖-控制器(MVC)模式的一部分,常用於ASP.NET MVC 和ASP.NET Core MVC 應用程式。 視圖負責透過動態渲染 HTML 內容向使用者呈現資料。 IronPDF 的Chrome PDF 渲染引擎的強大功能可確保您的視圖以像素級精度渲染,並保留所有樣式、佈局和互動元素。
ASP.NET Web 應用程式(.NET Framework)MVC 是微軟提供的 Web 應用程式框架。 它遵循一種稱為模型-視圖-控制器(MVC)的結構化架構模式,以組織和簡化 Web 應用程式的開發。
- 模型:管理資料、業務邏輯和資料完整性。
- 視圖:呈現使用者介面並渲染資訊。
- 控制器:處理使用者輸入、處理請求,並協調模型和視圖之間的互動。
IronPDF簡化了在ASP.NET MVC 專案中從視圖建立 PDF 檔案的過程。 這使得在ASP.NET MVC 中產生 PDF 變得簡單直接。 無論您是從網頁檢視產生發票、報告或任何文檔, IronPDF都能提供專業 PDF 輸出所需的工具。 如需完整的安裝指南,請造訪安裝概述頁面。
快速入門:輕鬆將ASP.NET MVC 視圖轉換為 PDF
了解如何使用IronPDF快速將ASP.NET MVC 視圖轉換為 PDF 文件。 只需幾行程式碼,即可將 CSHTML 視圖渲染成高品質的 PDF,從而增強應用程式的功能。 IronPDF簡化了流程,讓各個層級的開發人員都能輕鬆上手。 首先將IronPDF整合到您的ASP.NET Core專案中,即可輕鬆地從視圖產生 PDF。
最簡工作流程(5個步驟)
- 下載用於在ASP.NET MVC 中將視圖轉換為 PDF 的 C# 程式庫
- 新增一個用於資料的模型類
- 在控制器中建立一個名為"Person"的操作,並使用`RenderView`方法。
- 使用 MVC 5 視圖腳手架新增視圖
- 下載範例項目,快速入門
我需要哪個擴充包?
為什麼IronPDF需要擴充包?
IronPDF套件是IronPDF主包的擴充。 在ASP.NET MVC 中,要將視圖渲染為 PDF 文檔,需要IronPDF和IronPDF套件。 這種分離方式可以針對 MVC 框架最佳化功能,同時保持核心 PDF 渲染功能。
如何安裝擴充包?
Install-PackageIronPDF套件
使用NuGet安裝
Install-PackageIronPDF套件
如何將視圖渲染成 PDF?
我需要哪種類型的項目?
要將視圖轉換為 PDF 文件,您需要一個ASP.NET Web 應用程式 (.NET Framework) MVC 專案。 IronPDF支援各種 MVC 版本,並提供豐富的渲染選項,可根據您的要求自訂 PDF 輸出。
如何新增模型類別?
我應該在哪裡創建模型?
- 導航至"模型"資料夾
- 建立一個名為"Person"的新C#類別檔案。此類用作表示個人資料的模型。 請使用以下程式碼:
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-mvc-framework-model.cs
namespace ViewToPdfMVCSample.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
}
Namespace ViewToPdfMVCSample.Models
Public Class Person
Public Property Id() As Integer
Public Property Name() As String
Public Property Title() As String
Public Property Description() As String
End Class
End Namespace
如何編輯控制器?
我應該在控制器中添加哪些程式碼?
導航至"Controllers"資料夾並開啟"HomeController"檔案。使用以下程式碼新增"Persons"操作:
在提供的程式碼中,首先創建了ChromePdfRenderer類別。 若要使用 RenderView 方法,請提供一個 HttpContext,指定"Persons.cshtml"檔案的路徑,並提供一個包含必要資料的 List<Person>。 在渲染視圖時,您可以利用渲染選項自訂邊距、新增自訂文字和 HTML 頁首和頁腳,以及將頁碼套用至產生的 PDF 文件。
可使用以下程式碼將 PDF 文件下載到電腦: 代碼 433。 PSEG。
using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;
namespace ViewToPdfMVCSample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
// GET: Person
public ActionResult Persons()
{
// Create a list of Person objects
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Define the path to the View file
var viewPath = "~/Views/Home/Persons.cshtml";
// Instantiate the ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the view to a PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
// Set headers to view the PDF in-browser
Response.Headers.Add("Content-Disposition", "inline");
// Return the generated PDF file
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;
namespace ViewToPdfMVCSample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
// GET: Person
public ActionResult Persons()
{
// Create a list of Person objects
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Define the path to the View file
var viewPath = "~/Views/Home/Persons.cshtml";
// Instantiate the ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the view to a PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
// Set headers to view the PDF in-browser
Response.Headers.Add("Content-Disposition", "inline");
// Return the generated PDF file
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Imports IronPdf
Imports System.Collections.Generic
Imports System.Web.Mvc
Imports ViewToPdfMVCSample.Models
Namespace ViewToPdfMVCSample.Controllers
Public Class HomeController
Inherits Controller
Public Function Index() As ActionResult
Return View()
End Function
' GET: Person
Public Function Persons() As ActionResult
' Create a list of Person objects
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
Dim persons_Conflict = New List(Of Person) From {
New Person With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
If HttpContext.Request.HttpMethod = "POST" Then
' Define the path to the View file
Dim viewPath = "~/Views/Home/Persons.cshtml"
' Instantiate the ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the view to a PDF document
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)
' Set headers to view the PDF in-browser
Response.Headers.Add("Content-Disposition", "inline")
' Return the generated PDF file
Return File(pdf.BinaryData, "application/pdf")
End If
Return View(persons_Conflict)
End Function
Public Function About() As ActionResult
ViewBag.Message = "Your application description page."
Return View()
End Function
Public Function Contact() As ActionResult
ViewBag.Message = "Your contact page."
Return View()
End Function
End Class
End Namespace
如何自訂PDF渲染選項?
對於更進階的應用場景,您可以使用各種渲染選項自訂 PDF 輸出。 以下是一個包含自訂邊距、紙張尺寸和其他設定的範例:
// Advanced rendering with custom options
public ActionResult PersonsAdvanced()
{
var persons = GetPersonsList();
if (HttpContext.Request.HttpMethod == "POST")
{
var viewPath = "~/Views/Home/Persons.cshtml";
// Configure the renderer with custom options
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set custom rendering options
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginBottom = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Set custom paper size
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
// Add header and footer
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "{pdf-title}";
renderer.RenderingOptions.TextHeader.Font = IronPdf.Font.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronPdf.Font.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
// Enable JavaScript execution if needed
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.RenderDelay = 500; // Wait for JS to execute
// Render the view to PDF
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
// Optional: Apply compression to reduce file size
pdf.CompressImages(60);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf");
}
return View("Persons", persons);
}
// Advanced rendering with custom options
public ActionResult PersonsAdvanced()
{
var persons = GetPersonsList();
if (HttpContext.Request.HttpMethod == "POST")
{
var viewPath = "~/Views/Home/Persons.cshtml";
// Configure the renderer with custom options
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set custom rendering options
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginBottom = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Set custom paper size
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
// Add header and footer
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "{pdf-title}";
renderer.RenderingOptions.TextHeader.Font = IronPdf.Font.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronPdf.Font.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
// Enable JavaScript execution if needed
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.RenderDelay = 500; // Wait for JS to execute
// Render the view to PDF
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
// Optional: Apply compression to reduce file size
pdf.CompressImages(60);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf");
}
return View("Persons", persons);
}
Imports System.Web.Mvc
Imports IronPdf
' Advanced rendering with custom options
Public Function PersonsAdvanced() As ActionResult
Dim persons = GetPersonsList()
If HttpContext.Request.HttpMethod = "POST" Then
Dim viewPath = "~/Views/Home/Persons.cshtml"
' Configure the renderer with custom options
Dim renderer As New ChromePdfRenderer()
' Set custom rendering options
renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginBottom = 40
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
' Set custom paper size
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait
' Add header and footer
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{pdf-title}"
renderer.RenderingOptions.TextHeader.Font = IronPdf.Font.FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = IronPdf.Font.FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
' Enable JavaScript execution if needed
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.RenderDelay = 500 ' Wait for JS to execute
' Render the view to PDF
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons)
' Optional: Apply compression to reduce file size
pdf.CompressImages(60)
Response.Headers.Add("Content-Disposition", "inline")
Return File(pdf.BinaryData, "application/pdf")
End If
Return View("Persons", persons)
End Function
有關優化利潤率的更多信息,請訪問我們的"設定自訂利潤率"指南。 如果您需要使用特定尺寸的紙張,請查看我們的自訂紙張尺寸文件。
生成的PDF文件可以做什麼?
透過 RenderView 方法取得PdfDocument物件後,您可以對其進行各種改進和調整。 您可以將 PDF 轉換為PDFA或PDFUA格式,對建立的 PDF 套用數位簽名,或根據需要合併和分割PDF 文件。 該庫允許您旋轉頁面、插入註釋或書籤,以及為 PDF 文件添加獨特的浮水印。
為了優化檔案大小,可以考慮使用PDF壓縮技術。 在處理大量 JavaScript 內容時,我們的JavaScript渲染指南提供了有關處理自訂渲染延遲的詳細資訊。 有關各種匯出選項,請參閱我們關於儲存和匯出 PDF 文件的綜合指南。
如何新增視圖?
建立視圖需要遵循哪些步驟?
- 右鍵單擊新新增的"人員"操作,然後選擇"新增視圖"。

- 為新的 Scaffolded 專案選擇"MVC 5 視圖"。

- 選擇"清單"範本和"人員"模型類別。

這將會建立一個名為"Persons"的.cshtml檔案。
如何在視圖中新增列印按鈕?
- 導覽至"Views"資料夾 -> "Home"資料夾 -> "Persons.cshtml"檔案。
若要新增一個可以呼叫"人員"操作的按鈕,請使用以下程式碼:
@using (Html.BeginForm("Persons", "Home", FormMethod.Post))
{
<input type="submit" value="Print Person" />
}
@using (Html.BeginForm("Persons", "Home", FormMethod.Post))
{
<input type="submit" value="Print Person" />
}
如何在頂部導覽列新增版塊?
我應該在哪裡更新導航?
- 在"Views"資料夾中,導覽至"Shared"資料夾 -> "_Layout.cshtml"檔案。將"Person"導覽項目放在"Home"之後。
請確保 ActionLink 方法的值與我們的檔案名稱"Persons"完全相符。
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
<div class="container">
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
<li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
<li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
<li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
</ul>
</div>
</div>
</nav>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
<div class="container">
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
<li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
<li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
<li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
</ul>
</div>
</div>
</nav>
如何運行和測試專案?
運行專案
本文檔將向您展示如何執行專案並產生 PDF 文件。
輸出 PDF
哪裡可以下載完整項目?
範例項目包含哪些內容?
您可以下載本指南的完整程式碼。它以壓縮檔案的形式提供,您可以在 Visual Studio 中將其作為ASP.NET Web 應用程式 (.NET Framework) MVC 專案開啟。 此範例包含了所有必要的配置、模型類別、控制器和視圖,可協助您在 MVC 應用程式中快速上手 PDF 產生。
常見問題解答
如何在 ASP.NET MVC 中將 CSHTML 視圖轉換為 PDF?
您可以在 ASP.NET MVC 中使用 IronPDF 的 ChromePdfRenderer.RenderView() 方法將 CSHTML 視圖轉換為 PDF。只需安裝 IronPDF.Extensions.Mvc.Framework 套件,並使用該渲染方法,僅需幾行程式碼即可將視圖轉化成高品質的 PDF 文件。
將視圖繪製成 PDF 所需的最少程式碼是多少?
將視圖繪製成 PDF 的最小代碼是: var pdf = new IronPDF.ChromePdfRenderer.RenderRazorToPdf(this.ControllerContext); 這一行使用 IronPDF 的代碼就可以將您目前的視圖轉換成 PDF 文件。
ASP.NET MVC PDF 生成需要哪個擴展包?
對於 ASP.NET MVC 應用程式,您需要 IronPDF.Extensions.Mvc.Framework 套件。此擴充套件可與 ASP.NET MVC 專案無縫整合,並與 IronPDF 主套件一起運作,以啟用檢視至 PDF 的轉換功能。
將檢視轉換為 PDF 時,會使用何種渲染引擎?
IronPDF 使用 Chrome PDF 渲染引擎,可確保將視圖轉換為 PDF 時的精確度達到像素級。該引擎可在最終 PDF 輸出中保留原始 CSHTML 視圖中的所有樣式、佈局和互動元素。
我可以從 MVC 視圖產生發票和報告嗎?
是的,IronPDF 非常適合從您的 MVC 視圖中產生發票、報告和任何其他文件。該函式庫提供專業的 PDF 輸出功能,使其成為直接從您的 Web 應用程式檢視建立商業文件的理想選擇。
實現視圖轉換為 PDF 的基本步驟是什麼?
基本實作包括 5 個步驟:1) 下載並安裝 IronPDF 函式庫;2) 為您的資料新增一個模型類別;3) 使用 RenderView 方法建立控制器動作;4) 使用 MVC 5 View Scaffolding 新增 View;5) 使用 IronPDF 的渲染方法執行轉換。
PDF 輸出是否維持原始的檢視樣式?
是的,IronPDF 的 Chrome 渲染引擎可確保您 CSHTML 視圖中的所有 CSS 定義、佈局和互動元素在 PDF 輸出中得以保留。這提供了像素完美的精確度,並維持您原始網頁檢視的視覺完整性。

