如何在 ASP.NET MVC 中將視圖轉換為 PDF
View 是 ASP.NET 框架中的一個元件,用於在網頁應用程式中生成 HTML 標記。它是模型-視圖-控制器 (Model-View-Controller) 架構的一部分。 (MVC) 在 ASP.NET MVC 和 ASP.NET Core MVC 應用程序中常用的模式。視圖負責通過動態渲染 HTML 內容向用戶展示數據。
ASP.NET 網路應用程式 (.NET框架) MVC 是由 Microsoft 提供的網頁應用程式框架。它遵循稱為 Model-View-Controller(模型-視圖-控制器)的結構化架構模式。 (MVC) 組織和簡化網頁應用程式的開發。
- 模型(Model):管理數據、業務邏輯和數據完整性。
- 視圖(View):呈現用戶界面並渲染資訊。
- 控制器(Controller):處理用戶輸入,處理請求,並協調模型和視圖之間的互動。
IronPDF 簡化了從 ASP.NET MVC 專案中的視圖生成 PDF 文件的流程。這使在 ASP.NET MVC 中生成 PDF 簡單且直接。
如何在 ASP.NET MVC 中將視圖轉換為 PDF
IronPDF 擴展包
IronPdf.Extensions.Mvc.Framework 套件 是主要 IronPdf 套件的擴展。為了在 ASP.NET MVC 中將視圖呈現為 PDF 文件,同時需要 IronPdf.Extensions.Mvc.Framework 和 IronPdf 套件。
PM > Install-Package IronPdf.Extensions.Mvc.Framework
安裝與 NuGet
Install-Package IronPdf.Extensions.Mvc.Framework
將視圖渲染為 PDF
若要將視圖轉換為 PDF 檔案,您將需要一個 ASP.NET 網頁應用程式 (.NET框架) MVC 專案。
添加模型類別
- 導航到 "Models" 資料夾
- 建立一個新的 C# 類別檔命名為 "Person"。這個類別將作為代表個別資料的模型。使用以下程式碼片段:
: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
編輯控制器
按導航到「控制器」文件夾並打開「HomeController」文件。我們將添加「Persons」操作。請參考下面的代碼進行指導:
在提供的代碼中,首先創建了 ChromePdfRenderer 類。要使用 RenderView
方法,您需要為其提供一個 HttpContext,指定 "Persons.cshtml" 文件的路徑,並提供包含必要數據的列表。在渲染 View 時,使用者可以選擇使用 RenderingOptions 來自定義邊距,添加 自訂文本和HTML頁眉和頁腳,並應用 頁碼 至產生的 PDF 文件。
請注意
檔案(pdf.BinaryData, "application/pdf", "viewToPdfMVC.pdf")
.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()
{
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")
{
// Provide the path to your View file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
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()
{
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")
{
// Provide the path to your View file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
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
'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
' Provide the path to your View file
Dim viewPath = "~/Views/Home/Persons.cshtml"
Dim renderer As New ChromePdfRenderer()
' Render View to PDF document
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)
Response.Headers.Add("Content-Disposition", "inline")
' View the PDF
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
一旦您通過 RenderView
方法獲取 PdfDocument 對象,您可以對其進行各種改進和調整。您可以將 PDF 轉換為 PDFA 或 PDFUA 格式, 簽署 數位簽名 到已建立的 PDF,或 合併與拆分 PDF文件時所需。此外,該庫還允許您旋轉頁面,插入 註解 或 書籤,和 應用不同的水印 到您的 PDF 檔案中。
添加視圖
- 右鍵點擊新添加的 Person 動作,然後選擇「添加視圖」。
選擇“MVC 5 View”作為新增的 Scaffolded 項目。
- 選擇「清單」模板和「人」模型類。
這將創建一個名為 "Persons" 的 .cshtml 檔案。
- 瀏覽到 "Views" 資料夾 -> "Home" 資料夾 -> "Persons.cshtml" 檔案。
要添加一個調用 "Persons" 動作的按鈕,請使用以下代碼:
@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文檔。
下載 ASP.NET MVC 專案
您可以下載此指南的完整代碼。它是壓縮文件形式,您可以在 Visual Studio 中作為 ASP.NET Web 應用程序打開。 (.NET框架) MVC專案。