如何在 ASP.NET Core C# 中將視圖轉換為 PDF

How to Convert Views to PDFs in ASP.NET MVC

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

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

ASP.NET Web Application (.NET Framework) MVC 是微軟提供的一種網頁應用程式框架。 它遵循一種稱為模型-視圖-控制器 (MVC) 的結構架構模式,以組織和簡化網頁應用程式的開發。

  • 模型:管理數據、業務邏輯和數據完整性。
  • 視圖:呈現用戶界面並渲染信息。
  • 控制器:處理用戶輸入、處理請求,並協調模型和視圖之間的交互。

IronPDF 簡化了在 ASP.NET MVC 專案中從視圖創建 PDF 文件的過程。 這使得在 ASP.NET MVC 中的 PDF 生成變得簡單直接。

快速開始:輕鬆將 ASP.NET MVC 視圖轉換為 PDF

了解如何使用 IronPDF 快速將您的 ASP.NET MVC 視圖轉換為 PDF 文檔。 只需使用幾行代碼,您就可以將 CSHTML 視圖渲染為高品質 PDF,增強應用程式的功能。 IronPDF 簡化了這一過程,讓所有級別的開發人員都可以使用。 開始將 IronPDF 集成到您的 ASP.NET Core 項目中,以輕鬆從視圖生成 PDF。

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    // Install-Package IronPdf.Extensions.Razor
    var pdf = new IronPdf.ChromePdfRenderer.RenderRazorToPdf(this.ControllerContext);
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer
class="hsg-featured-snippet">

最小工作流程(5步)

  1. 下載將視圖轉換為 PDF 的 C# 庫,用於 ASP.NET MVC
  2. 為數據添加一個模型類
  3. 在控制器中創建一個“Person”操作並使用RenderView方法
  4. 使用 MVC 5 視圖樣板添加一個視圖
  5. 下載示例項目以快速開始

IronPDF 擴展包

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

Install-Package IronPdf.Extensions.Mvc.Framework
class="products-download-section">
data-modal-id="trial-license-after-download">
class="product-image"> C# NuGet 庫用于 PDF
class="product-info">

使用 NuGet 安裝

data-original-title="單擊以複製">
class="copy-nuget-row">
Install-Package IronPdf.Extensions.Mvc.Framework
class="copy-button">
class="nuget-link">nuget.org/packages/IronPdf.Extensions.Mvc.Framework/

渲染視圖為 PDF

要將視圖轉換為 PDF 文件,您需要一個 ASP.NET Web Application (.NET Framework) MVC 項目。

添加模型類

  • 導航到“模型”文件夾
  • 創建一個名為“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
$vbLabelText   $csharpLabel

編輯控制器

導航到“控制器”文件夾並打開“HomeController”文件。我們將添加“Persons”操作。 請參考下面的代碼以獲取指導:

在提供的代碼中,首先創建了ChromePdfRenderer類。 要使用RenderView方法,需要向其提供 HttpContext,指定“Persons.cshtml”文件的路徑,並提供一個包含所需數據的列表。 When rendering the View, users have the option to utilize RenderingOptions to customize margins, add custom text and HTML headers and footers, and apply page numbers to the resulting PDF document.

請注意The PDF document can be downloaded to the machine using the following code: File(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()
        {
            // 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
$vbLabelText   $csharpLabel

一旦通過RenderView方法獲得PdfDocument對象,您可以對其進行各種改進和調整。 You can convert the PDF to PDFA or PDFUA formats, sign digital signature to the created PDF, or merge and split PDF documents as required. Moreover, the library enables you to rotate pages, insert annotations or bookmarks, and apply distinct watermarks to your PDF files.

添加視圖

  • 右鍵單擊新添加的 Person 動作並選擇 "添加視圖"。

右鍵點擊 Persons 操作

  • 為新的樣板項目選擇“MVC 5 View”。

選擇樣板

  • 選擇 "List" 範本和 "Person" 模型類。

添加視圖

這將創建名為 "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

在頂部導航欄中添加一個部分

  • 在“視圖”文件夾中,導航到“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 Web Application (.NET Framework) MVC 項目打開。

下載 PDF轉換的MVC示例項目

常見問題解答

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

您可以使用 IronPDF 庫在 ASP.NET Core MVC 中將視圖轉換為 PDF。透過 NuGet 安裝 IronPdf.Extensions.Mvc.Framework 套件,然後使用ChromePdfRenderer類別將視圖渲染為 PDF 文件。

在 ASP.NET MVC 中,將視圖渲染成 PDF 文件需要哪些條件?

要在 ASP.NET MVC 中將視圖渲染為 PDF 文檔,您需要 IronPDF 庫和ChromePdfRenderer類,該類需要一個HttpContext 、視圖路徑和一個資料列表來產生 PDF。

如何在 ASP.NET 應用程式中使用 IronPDF 自訂 PDF 輸出?

IronPDF 允許使用RenderingOptions自訂 PDF 輸出。您可以調整頁邊距、新增自訂頁首和頁尾以及包含頁碼,從而根據您的需求自訂 PDF 文件。

在 ASP.NET MVC 中設定用於產生 PDF 的模型類別需要哪些步驟?

要在 ASP.NET MVC 中設定模型類,請導航至「Models」資料夾,建立一個新的 C# 類文件,並定義該類,使其包含表示 PDF 產生所需資料結構的屬性。

如何在 ASP.NET MVC 的視圖中整合 PDF 產生按鈕?

若要在 ASP.NET MVC 的視圖中整合 PDF 產生按鈕,可以在視圖的 HTML 標籤中新增一個按鈕元素,並將其連結到控制器中一個使用 IronPDF 將視圖呈現為 PDF 的操作。

在 ASP.NET MVC 中新增視圖的流程是什麼?

若要在 ASP.NET MVC 中新增視圖,請在控制器中右鍵點選所需的操作,選擇“新增視圖”,選擇“MVC 5 視圖”作為腳手架項,然後選擇對應的範本和模型類別。

哪裡可以找到ASP.NET MVC中View到PDF轉換的範例專案?

您可以從 IronPDF 網站下載完整的 MVC PDF 轉換範例項目,其中包含一個壓縮文件,可在 Visual Studio 中開啟以進行實際實作。

如何在 ASP.NET MVC 專案中安裝 IronPDF?

使用 NuGet 套件管理器,透過以下命令在 ASP.NET MVC 專案中安裝 IronPDF: Install-Package IronPdf.Extensions.Mvc.Framework

ASP.NET MVC 中 PDF 產生失敗時,常見的故障排除步驟有哪些?

如果 ASP.NET MVC 中 PDF 產生失敗,請確保 IronPDF 套件已正確安裝,檢查傳遞給ChromePdfRenderer路徑和上下文,並驗證視圖和資料是否已正確呈現。

IronPDF 是否相容於 .NET 10?升級到 .NET 10 有哪些好處?

是的-IronPDF 與 .NET 10 完全相容。升級後可帶來執行時間改進,例如減少堆疊分配、提高記憶體使用率、增強 HTML 到 PDF 的渲染效能,以及存取新的語言特性和框架增強功能。

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: sections/author_component.php

Line Number: 18

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 18
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: sections/author_component.php

Line Number: 38

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 38
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: sections/author_component.php

Line Number: 48

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 48
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

準備好開始了嗎?
Nuget 下載 16,154,058 | 版本: 2025.11 剛剛發布