如何將 Razor 頁面轉換為 PDF,在 ASP.NET Core Web 應用程式中

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

查克尼思·賓

Razor Page 是一個擁有 .cshtml 副檔名的文件,結合了 C# 和 HTML 來生成網頁內容。在 ASP.NET Core 中,Razor Pages 是組織網站應用程式代碼的一種較簡單的方法,適合用於只讀的簡單頁面或執行簡單數據輸入的頁面。

ASP.NET Core Web App 是使用 ASP.NET Core 框架構建的網頁應用程式,這是一個跨平台的框架,用於開發現代網頁應用程式。

IronPDF 簡化了從 Razor Pages 中生成 PDF 文件的過程,適用於 ASP.NET Core Web App 專案。這使得在 ASP.NET Core 網頁應用程式中生成 PDF 文件變得簡單且直接。



IronPDF 擴展包

IronPdf.Extensions.Razor 套件 是主套件 IronPdf 的擴展。要在 ASP.NET Core Web 應用程式中將 Razor Pages 轉換成 PDF 文件,所需的套件包括 IronPdf.Extensions.Razor 和 IronPdf。

Install-Package IronPdf.Extensions.Razor
用於 PDF 的 C# NuGet 程式庫

安裝與 NuGet

Install-Package IronPdf.Extensions.Razor

將 Razor 頁面渲染為 PDF

您需要一個 ASP.NET Core Web 應用程序項目來將 Razor 頁面轉換為 PDF 文件。

建立模型類別

  • 在專案中建立一個新資料夾,並命名為 "Models"。
  • 新增一個標準的 C# 類別到該資料夾,並命名為 "Person"。此類別將作為個別數據的模型。請使用以下代碼片段:
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Public Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class
VB   C#
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-razor-model.cs
namespace RazorPageSample.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 RazorPageSample.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#

新增一個 Razor 頁面

在 "Pages" 資料夾中新增一個空白的 Razor 頁面,並將其命名為 "persons.cshtml"。

  • 使用以下提供的範例程式碼修改新創建的 "Persons.cshtml" 檔案。

以下程式碼將在瀏覽器中顯示資訊。

@page
@using RazorPageSample.Models;
@model RazorPageSample.Pages.PersonsModel
@{
}

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    @foreach (var person in ViewData ["personList"] as List<Person>)
    {
        <tr>
            <td>@person.Name</td>
            <td>@person.Title</td>
            <td>@person.Description</td>
        </tr>
    }
</table>

<form method="post">
    <button type="submit">print</button>
</form>
@page
@using RazorPageSample.Models;
@model RazorPageSample.Pages.PersonsModel
@{
}

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    @foreach (var person in ViewData ["personList"] as List<Person>)
    {
        <tr>
            <td>@person.Name</td>
            <td>@person.Title</td>
            <td>@person.Description</td>
        </tr>
    }
</table>

<form method="post">
    <button type="submit">print</button>
</form>
HTML

接下來,以下的代碼首先實例化 ChromePdfRenderer 類。將 this 傳遞給 RenderRazorToPdf 方法即可將此 Razor Page 轉換為 PDF 文件。

用戶可以完全訪問 RenderingOptions 中提供的功能。這些功能包括應用的能力 頁碼 到生成的 PDF,設定自訂邊距,並添加自訂 文本以及 HTML 標頭和頁尾- 打開 "Persons.cshtml" 文件的下拉菜單以查看 "Persons.cshtml.cs" 文件。

  • 使用以下代碼修改 "Persons.cshtml.cs"。

請注意
可以使用以下程式碼在瀏覽器中查看PDF文件: 檔案(pdf.BinaryData, "application/pdf")然而,在瀏覽器中檢視後下載PDF文件會導致PDF文件損壞。

using IronPdf.Razor.Pages;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPageSample.Models;

namespace RazorPageSample.Pages
{
    public class PersonsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public List<Person> persons { get; set; }

        public void OnGet()
        {
            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" }
            };

            ViewData ["personList"] = persons;
        }
        public IActionResult OnPostAsync()
        {
            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" }
            };

            ViewData ["personList"] = persons;

            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render Razor Page to PDF document
            PdfDocument pdf = renderer.RenderRazorToPdf(this);

            Response.Headers.Add("Content-Disposition", "inline");

            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // View output PDF on broswer
            return File(pdf.BinaryData, "application/pdf");
        }
    }
}
using IronPdf.Razor.Pages;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPageSample.Models;

namespace RazorPageSample.Pages
{
    public class PersonsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public List<Person> persons { get; set; }

        public void OnGet()
        {
            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" }
            };

            ViewData ["personList"] = persons;
        }
        public IActionResult OnPostAsync()
        {
            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" }
            };

            ViewData ["personList"] = persons;

            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render Razor Page to PDF document
            PdfDocument pdf = renderer.RenderRazorToPdf(this);

            Response.Headers.Add("Content-Disposition", "inline");

            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // View output PDF on broswer
            return File(pdf.BinaryData, "application/pdf");
        }
    }
}
Imports IronPdf.Razor.Pages
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc.RazorPages
Imports RazorPageSample.Models

Namespace RazorPageSample.Pages
	Public Class PersonsModel
		Inherits PageModel

		<BindProperty(SupportsGet := True)>
		Public Property persons() As List(Of Person)

		Public Sub OnGet()
			persons = 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"
				}
			}

			ViewData ("personList") = persons
		End Sub
		Public Function OnPostAsync() As IActionResult
			persons = 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"
				}
			}

			ViewData ("personList") = persons

			Dim renderer As New ChromePdfRenderer()

			' Render Razor Page to PDF document
			Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)

			Response.Headers.Add("Content-Disposition", "inline")

			Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")

			' View output PDF on broswer
			Return File(pdf.BinaryData, "application/pdf")
		End Function
	End Class
End Namespace
VB   C#

RenderRazorToPdf 方法返回一個 PdfDocument 對象,可進行額外的處理和編輯。您可以導出 PDF 為 PDFAPDFUA, 應用一個 數位簽名 至渲染的PDF文件,或 合併與拆分 PDF 文件。此方法還允許您旋轉頁面、添加 註解書籤,和 打印自訂浮水印 到您的 PDF。

將部分添加到頂部導航欄

  • 瀏覽到 Pages 資料夾 -> Shared 資料夾 -> _Layout.cshtml。將 "Person" 導航項目放在 "Home" 之後。

請確保 asp-page 屬性的值與我們的文件名完全匹配,在這種情況下是 "Persons"。

<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPageSample</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>
<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPageSample</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>
HTML

運行項目

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

執行 ASP.NET Core 網頁應用程式專案

下載 ASP.NET Core Web App 專案

您可以下載本指南的完整代碼。它以壓縮文件形式提供,您可以在 Visual Studio 中將其打開為 ASP.NET Core Web App 專案。

點擊這裡下載專案。

查克尼思·賓

軟體工程師

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