如何在 ASP.NET MVC 中將視圖轉換為 PDF

This article was translated from English: Does it need improvement?
Translated
View the article in English

查克尼思·賓

View 是 ASP.NET 框架中用於在網頁應用程序中生成 HTML 標記的組件。 這是模型-視圖-控制器的一部分(MVC)模式,常用於 ASP.NET MVC 和 ASP.NET Core MVC 應用程式中。 視圖負責通過動態渲染HTML內容來向用戶展示數據。



ASP.NET 網頁應用程式(.NET框架)MVC 是由 Microsoft 提供的網路應用程式框架。 它遵循一種稱為模型-視圖-控制器的結構化架構模式。(MVC)組織和優化網絡應用程式的開發。

IronPDF 擴充套件包

IronPdf.Extensions.Mvc.Framework 套件是主要 IronPdf 套件的擴展。 在ASP.NET MVC中,需要IronPdf.Extensions.Mvc.Framework和IronPdf這兩個套件才能將視圖渲染為PDF文件。

PM > Install-Package IronPdf.Extensions.Mvc.Framework
用於 PDF 的 C# NuGet 程式庫

安裝與 NuGet

Install-Package IronPdf.Extensions.Mvc.Framework

將視圖轉換為PDFs

要將視圖轉換為PDF文件,您將需要一個ASP.NET網絡應用程序。(.NET框架)MVC 專案。

添加模型類別

  • 導航至“Models”文件夾
  • 創建一個名為「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
VB   C#

編輯控制器

導航至「Controllers」文件夾並打開「HomeController」檔案。我們將要添加「Persons」動作。 請參考以下代碼以獲得指導:

在提供的程式碼中,首先創建了ChromePdfRenderer類。 要使用 RenderView 方法,您需要提供一個 HttpContext,指定 "Persons.cshtml" 文件的路徑,並提供一個包含所需數據的列表。 在渲染視圖時,用戶可以使用RenderingOptions來自定義邊距、添加自訂文本和HTML頁眉和頁腳,並應用頁碼到結果的PDF文件中。

請注意
可以使用以下代碼將 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
VB   C#

一旦您通過 RenderView 方法獲得 PdfDocument 物件,您可以對其進行各種改進和調整。 您可以將PDF轉換為PDFAPDFUA格式, 簽署數位簽名到已建立的 PDF,或合併與拆分根據需要的 PDF 文件。 此外,該庫允許您旋轉頁面、插入註解書籤,和應用不同的水印到您的 PDF 檔案中。

新增視圖

  • 右鍵點擊新添加的Person操作並選擇“添加視圖”。

    右键单击 Persons 操作

  • 選擇“MVC 5視圖”作為新的腳手架項目。

    選擇腳手架

  • 選擇“列表”模板和“人員”模型類。

    新增檢視

    這將創建一個名為「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" />
}
HTML

將一個部分添加到頂部導航欄

  • 在 "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>
HTML

執行專案

這將向您展示如何運行項目並生成PDF文檔。

執行 ASP.NET MVC 專案

輸出 PDF

下載 ASP.NET MVC 專案

您可以下載本指南的完整代碼。它是一個壓縮檔,您可以在 Visual Studio 中將其打開為一個 ASP.NET 網頁應用程序。(.NET框架)MVC 專案。

下載用於 PDF 轉換的 MVC 示例項目

Chaknith related to 下載 ASP.NET MVC 專案

查克尼思·賓

軟體工程師

Chaknith 是開發者界的夏洛克福爾摩斯。他第一次意識到自己可能有個軟體工程的未來,是在他為了娛樂而參加程式挑戰的時候。他的重點是 IronXL 和 IronBarcode,但他也引以為豪的是,他幫助客戶解決所有產品的問題。Chaknith 利用他與客戶直接對話中獲得的知識,以進一步改進產品。他的實際反饋超越了 Jira 工單,並支持產品開發、文件撰寫和行銷,以提升客戶的整體體驗。不在公司時,他通常在學習機器學習、寫程式和徒步旅行。