如何在 ASP .NET Core Web App 中將 Razor 頁面轉換成 PDF

如何在 ASP.NET Core C## App 中將 Razor 頁面轉換成 PDF。

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

IronPDF 可使用 RenderRazorToPdf 方法在 ASP.NET Core 應用程式中將 Razor 頁面(.cshtml 檔案)無縫轉換為 PDF 文件,簡化從網頁內容生成 PDF 的過程,並完全支援 C# 和 HTML 渲染。

Razor Page 是以 .cshtml 為副檔名的檔案,結合 C# 與 HTML 來產生網頁內容。 在 ASP.NET Core 中,Razor Pages 是組織 Web 應用程式程式碼的一種更簡單的方式,非常適合只讀或做簡單資料輸入的簡單頁面。

ASP.NET Core Web 應用程式是使用 ASP.NET Core 建立的 Web 應用程序,ASP.NET Core 是一個用於開發現代 Web 應用程式的跨平台框架。

IronPDF 簡化了在 ASP.NET Core Web 應用程式專案中從 Razor Pages 建立 PDF 檔案的流程。 這使得在 ASP.NET Core Web Apps 中直接生成 PDF。

快速入門:幾秒鐘內將 Razor Pages 轉換為 PDF

在 ASP.NET Core 應用程式中將您的 Razor 頁面轉換成高品質的 PDF。 透過使用 RenderRazorToPdf 方法,您可以將 CSHTML 檔案轉換為 PDF 文件,優化您的工作流程並加強文件分發。 本指南將教您在幾分鐘內完成所需的簡單步驟。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronPDF

    PM > Install-Package IronPdf

  2. 複製並運行這段程式碼。

    // 安裝 IronPdf.Extensions.Razor 套件
    var pdf = new IronPdf.ChromePdfRenderer().RenderRazorToPdf("Views/Home/Index.cshtml");
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronPDF,免費試用!
    arrow pointer

介紹

<! -- 引言實作示意圖 --> <!--說明:說明程式碼概念的圖表或截圖 -->

Razor Pages 提供了在 ASP.NET Core 應用程式中建立動態網頁內容的強大直覺方式。 當與 IronPDF 的渲染功能結合時,開發人員可以直接從網頁內容建立專業的 PDF 文件。 此方法可移除複雜的 PDF 生成邏輯,並允許您使用現有的 HTML 和 CSS 技能。

IronPdf 與 Razor Pages 的整合對於產生報告、發票、證書以及任何其他需要動態資料呈現的文件特別有價值。 透過使用您已經熟悉的 Razor 語法,您可以保持網頁檢視與 PDF 輸出之間的一致性。

Razor to PDF 轉換需要哪些 NuGet 套件?

IronPdf.Extensions.Razor套件是主IronPdf套件的延伸。 IronPdf.Extensions.RazorIronPdf 兩個套件都需要在 ASP.NET Core Web App 中將 Razor 頁面呈現為 PDF 文件。如需詳細安裝說明,請造訪我們的 安裝概述指南。

# Command to install IronPdf.Extensions.Razor package using NuGet Package Manager
安裝 IronPdf.Extensions.Razor 套件
# Command to install IronPdf.Extensions.Razor package using NuGet Package Manager
安裝 IronPdf.Extensions.Razor 套件
SHELL

<! -- NuGet 函式庫下載指令標籤 ::開始 -->

用於 PDF 的 C# NuGet 庫
### 使用 NuGet 安裝
安裝 IronPdf.Extensions.Razor 套件
(按鈕)

如何在 ASP.NET Core 中將 Razor 頁面轉換成 PDF?

您需要一個 ASP.NET Core Web App 專案來將 Razor Pages 轉換成 PDF 檔案。 這個過程包括為您的資料建立一個模型,設定一個 Razor Page 來顯示該資料,然後使用 IronPDF 的 RenderRazorToPdf 方法來產生 PDF 輸出。

為什麼我需要一個 PDF 產生的模型類別?

模型類別是 Razor 頁面中資料表示的骨幹。 這些工具提供結構化的方式將資料從控制器邏輯傳送到檢視,確保類型的安全性和可維護性。 在生成 PDF 時,這些模型變得更加重要,因為它們定義了將出現在您最終文件中的資料的確切結構。

  • 在專案中建立一個新資料夾,並將其命名為"Models"。
  • 在資料夾中新增一個名為"Person"的標準 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
$vbLabelText   $csharpLabel

如何設定 PDF 轉換的 Razor 頁面?

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

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

下面的程式碼會在瀏覽器中顯示資訊。 請注意 Razor 語法可將 C# 程式碼無縫整合至 HTML 中,因此非常適合產生可轉換為 PDF 的動態內容:

@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

將 Razor Pages 渲染為 PDF

<! -- 輸出顯示 IronPDF 中 render razor pages to pdfs 的結果 --> --> <!--說明:顯示程式碼執行輸出或結果的截圖 -->

接下來,下面的程式碼首先實例化ChromePdfRenderer類別。 將此參數傳遞給RenderRazorToPdf方法即可將此 Razor 頁面轉換為 PDF 文件。

您可以完全使用 RenderingOptions中提供的功能。 這些功能包括將 頁數套用至產生的 PDF、設定 自訂頁邊、新增自訂 文字以及 HTML 頁首和頁尾。 您也可以為 PDF 設定 metadata 以確保正確的文件識別和可搜尋性。

  • 開啟"Persons.cshtml"檔案的下拉式選單,即可看到"Persons.cshtml.cs"檔案。
  • 使用以下程式碼修改"Persons.cshtml.cs"。
using IronPdf.Razor;
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; }

        // Handle GET request to load initial data
        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;
        }

        // Handle POST request to convert Razor page to PDF
        public IActionResult OnPost()
        {
            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);

            // Return the generated PDF file with appropriate content headers
            Response.Headers.Add("Content-Disposition", "inline");
            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // Optionally view the output PDF in browser (uncomment below line if needed)
            // return File(pdf.BinaryData, "application/pdf");
        }
    }
}
using IronPdf.Razor;
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; }

        // Handle GET request to load initial data
        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;
        }

        // Handle POST request to convert Razor page to PDF
        public IActionResult OnPost()
        {
            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);

            // Return the generated PDF file with appropriate content headers
            Response.Headers.Add("Content-Disposition", "inline");
            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // Optionally view the output PDF in browser (uncomment below line if needed)
            // return File(pdf.BinaryData, "application/pdf");
        }
    }
}
Imports IronPdf.Razor
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)

		' Handle GET request to load initial data
		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

		' Handle POST request to convert Razor page to PDF
		Public Function OnPost() 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)

			' Return the generated PDF file with appropriate content headers
			Response.Headers.Add("Content-Disposition", "inline")
			Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")

			' Optionally view the output PDF in browser (uncomment below line if needed)
			' return File(pdf.BinaryData, "application/pdf");
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

RenderRazorToPdf 方法會返回一個 PdfDocument物件,該物件可以進行其他處理和編輯。 您可以將 PDF 匯出為 PDFAPDFUA 的形式,將數位簽章套用至呈現的 PDF 文件,或合併與分割 PDF 文件。 此方法還可讓您旋轉頁面、新增註解或書籤,以及在 PDF 上蓋上自訂水印。

為了強化文件管理,您也可以壓縮 PDF,在不影響品質的情況下縮小檔案大小。 這在處理大型報告或頻寬問題時尤其有用。 此外,IronPDF 提供的廣泛編輯功能已在我們全面的 PDF 編輯教學中作了說明。

如何為 PDF 生成頁面新增導覽?

導覽對 ASP.NET Core 應用程式的使用者體驗至關重要。 透過將 PDF 生成頁面整合到您的主導覽中,使用者可以輕鬆存取功能,而無需手動輸入 URL。

  • 導覽至 Pages 資料夾 -> Shared 資料夾 -> _Layout.cshtml。 將"人物"導覽項目放在"首頁"之後。

確保 asp-page 屬性的值與我們的檔案名稱完全相符,在此例中,檔案名稱為 "Persons"。 這可確保在您的 ASP.NET Core 應用程式中進行正確的路由:

<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 生成時會發生什麼?

這會告訴您如何執行專案並產生 PDF 文件。 當您按一下"人"導覽連結時,您會看到以表格格式顯示的資料。 點選"列印"按鈕會觸發 PDF 產生程序,將目前的 Razor Page 檢視轉換為可下載的 PDF 文件。

Visual Studio showing C# PersonsModel class with OnGet and OnPostAsync methods for PDF generation using IronPDF

生成的 PDF 會保留 Razor 頁面的所有樣式與格式,確保網頁檢視與 PDF 輸出的外觀一致。 這種方法對於產生報告、發票或任何需要應用程式資料庫或商業邏輯資料的文件特別有用。

在哪裡可以下載完整的 ASP.NET Core Web App 範例?

您可以下載本指南的完整程式碼壓縮文件,然後在 Visual Studio 中將其作為 ASP.NET Core Web 應用程式專案開啟。

下載 RazorPageSample.zip ASP.NET Core Web 應用程式項目

常見問題解答

如何在 ASP.NET Core 中將 Razor Pages 轉換為 PDF?

您可以在 ASP.NET Core 中使用 IronPDF 的 RenderRazorToPdf 方法將 Razor Pages 轉換為 PDF。只需安裝 IronPdf.Extensions.Razor 套件,並使用 ChromePdfRenderer 直接將您的 .cshtml 檔案渲染為 PDF 文件。

Razor to PDF 轉換需要哪些 NuGet 套件?

您需要兩個 NuGet 套件:IronPdf.Extensions.Razor (擴充套件) 和 IronPdf (主套件)。在 ASP.NET Core Web Apps 中將 Razor 頁面呈現為 PDF 文件需要這兩個套件。

當轉換成PDF時,我可以在我的Razor Pages中使用動態資料嗎?

是的,IronPDF 完全支援 Razor Pages 中的動態資料。在轉換為 PDF 時,您可以使用 C# 程式碼、模型綁定,以及所有標準的 Razor 語法功能,使其非常適合於產生具有動態內容的報表、發票和證書。

我可以從 Razor Pages 產生哪些類型的文件?

IronPDF 的 Razor to PDF 轉換功能非常適合生成各種類型的文件,包括報告、發票、證書、收據以及任何其他需要動態資料展示的文件,同時還能保持您現有的 HTML 和 CSS 定義。

如何在我的專案中快速實現 Razor 到 PDF 的轉換?

使用 IronPDF,您可以在幾分鐘內實現 Razor 到 PDF 的轉換。最低限度的工作流程僅包含 5 個步驟:安裝函式庫、新增模型類別、建立 Razor 頁面、編輯 .cs 檔案以使用 RenderRazorToPdf 方法,以及執行您的應用程式。

轉換是否會維護我的 HTML 和 CSS 設定?

是的,IronPDF 在將 Razor Pages 轉換為 PDF 時會保留您的 HTML 和 CSS 定義。這允許您使用您已經創建的相同的樣式和佈局來保持您的網頁視圖和 PDF 輸出之間的一致性。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

審核人
Jeff Fritz
Jeffrey T. Fritz
首席計畫經理 - .NET 社群團隊
Jeff 也是 .NET 和 Visual Studio 團隊的首席計畫經理。他是 .NET Conf 虛擬會議系列的執行製作人,並主持「Fritz and Friends」開發人直播串流,每週播出兩次,與觀眾一起討論技術和編寫程式碼。Jeff 為 Microsoft Build、Microsoft Ignite、.NET Conf 和 Microsoft MVP Summit 等大型 Microsoft 開發人員活動撰寫工作坊、簡報和規劃內容。
準備好開始了嗎?
Nuget 下載 17,386,124 | 版本: 2026.2 剛剛發布