IronPDF Razor 延伸模組

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

IronPDF 是一個適用於 .NET 和 .NET Core 的 PDF 函式庫。IronPDF 是一個公開的商業 C# PDF 函式庫,因此大部分是免費的 PDF 函式庫。開發過程中是免費的,但商業部署必須獲得許可。這種更清晰的許可模式不需要開發者學習 GNU / AGPL 許可模式的細節,而是能夠專注於他們的項目。

IronPDF 讓 .NET 和 .NET Core 開發者能夠輕鬆地在 C#、F# 和 VB.NET 中生成、合併、分割、編輯和提取 PDF 內容,適用於 .NET Core 和 .NET Framework,還可以從 HTML、ASPX、CSS、JS 和圖像文件創建 PDF。

IronPDF 通過 HTML to PDF 擁有全面的 PDF 編輯和生成功能。它怎麼運作呢?大多數的文件設計和布局可以使用現有的 HTML 和 HTML5 資產。

您可以從這裡下載檔案項目。 連結.

IronPDF 特點適用於 .NET 和 .NET Core 應用程序

一些出色的 IronPDF PDF 函式庫特點包括:

  • .NET pdf 圖書館可以 生成PDF 來自 HTML、圖片和 ASPX 文件的文件
  • 在 .NET 和 .NET Core 應用程式中讀取 PDF 文本
  • 從PDF中提取數據和圖像
  • 合併PDF文件
  • 拆分PDFs
  • 操作 PDF

IronPDF 優勢

  • IronPDF PDF 庫易於安裝
  • IronPDF .NET 庫提供快速且簡便的授權選項
  • IronPDF 比大多數 .NET PDF 函式庫更出色,並超越大多數 .NET Core PDF 函式庫的表現

IronPDF 是您一直在尋找的 PDF 解決方案。


安裝 IronPDF pdf 庫

要在 .NET 或 .NET Core 中安裝 IronPDF pdf 庫非常簡單。你可以按照以下方式安裝它:

使用 NuGet 套件管理器,在命令提示字元中輸入以下內容:

Install-Package IronPdf

使用 Visual Studio 中的 NuGet 套件管理器,從專案選單中選擇「管理 NuGet 套件」,然後搜索 IronPDF,如下所示:

圖 1 - IronPDF NuGet 套件

圖1 - IronPDF NuGet 套件

這會安裝 PDF 擴充功能。

使用 IronPDF,你可以使用 ASP.NET MVC 返回 PDF 檔案。以下是一些代碼範例:

以下顯示的是可以由您的控制器提供的示例方法。

public FileResult Generate_PDF_FromHTML_Or_MVC(long id) {

  using var objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>"); //Create a PDF Document 
  var objLength = objPDF.BinaryData.Length; //return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString());
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" + id + ".pdf");

  return File(objPDF.BinaryData, "application/pdf;");
}
public FileResult Generate_PDF_FromHTML_Or_MVC(long id) {

  using var objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>"); //Create a PDF Document 
  var objLength = objPDF.BinaryData.Length; //return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString());
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" + id + ".pdf");

  return File(objPDF.BinaryData, "application/pdf;");
}
Public Function Generate_PDF_FromHTML_Or_MVC(ByVal id As Long) As FileResult

  Dim objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>") 'Create a PDF Document
  Dim objLength = objPDF.BinaryData.Length 'return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString())
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" & id & ".pdf")

  Return File(objPDF.BinaryData, "application/pdf;")
End Function
VB   C#

以下是一個在 ASP.NET 中提供現有 PDF 的範例。

Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"));
Response.Flush();
Response.End();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"));
Response.Flush();
Response.End();
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition","attachment;filename=""FileName.pdf""")
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"))
Response.Flush()
Response.End()
VB   C#

讓我們來做一個使用 MVC 和 .NET Core 的 ASP.NET 簡單範例。打開 Visual Studio,並創建一個新的 ASP.NET Core 網頁應用程式。

1. 在 Visual Studio 中創建一個新的 ASP.NET Core 網頁專案

創建 ASP.NET Core 專案

2. 創建 MVC 模型

  • 創建一個新資料夾並命名為 "Models"
新增資料夾
  • 右鍵單擊 Model 資料夾並新增一個類別
新增類別
  • 將類別名稱更改為 "ExampleModel"。向模型添加內容,例如:
namespace WebApplication4.Models
{
    public class ExampleModel
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
}
namespace WebApplication4.Models
{
    public class ExampleModel
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
}
Namespace WebApplication4.Models
	Public Class ExampleModel
		Public Property Name() As String
		Public Property Surname() As String
		Public Property Age() As Integer
	End Class
End Namespace
VB   C#

3. 添加 MVC 控制器

  • 建立一個新資料夾並命名為「Controllers」
  • 右鍵點擊 Controllers 資料夾並新增一個新的「MVC controller - empty」
新增控制器類別

將內容新增到控制器:

namespace WebApplication4.Models
{
    public class HomeController : Controller
    {
        [HttpPost]
        public IActionResult ExampleView(ExampleModel model)
        {
            var html = this.RenderViewAsync("_Example", model);
            var ironPdfRender = new IronPdf.ChromePdfRenderer();
            using var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);

            return File(pdfDoc.Stream.ToArray(), "application/pdf");
        }
    }
}
namespace WebApplication4.Models
{
    public class HomeController : Controller
    {
        [HttpPost]
        public IActionResult ExampleView(ExampleModel model)
        {
            var html = this.RenderViewAsync("_Example", model);
            var ironPdfRender = new IronPdf.ChromePdfRenderer();
            using var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);

            return File(pdfDoc.Stream.ToArray(), "application/pdf");
        }
    }
}
Namespace WebApplication4.Models
	Public Class HomeController
		Inherits Controller

		<HttpPost>
		Public Function ExampleView(ByVal model As ExampleModel) As IActionResult
			Dim html = Me.RenderViewAsync("_Example", model)
			Dim ironPdfRender = New IronPdf.ChromePdfRenderer()
			Dim pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result)

			Return File(pdfDoc.Stream.ToArray(), "application/pdf")
		End Function
	End Class
End Namespace
VB   C#

4. 修改 Index.cshtml

在 Pages 資料夾內,修改 Index.cshtml 檔案為:

@page
@model WebApplication4.Models.ExampleModel
@{
    ViewBag.Title = "Example Index View";
}
<h2>Index</h2>
<form asp-action="ExampleView" enctype="multipart/form-data">
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>
        <button type="submit">Save</button>
    </div>
}
</form>
@page
@model WebApplication4.Models.ExampleModel
@{
    ViewBag.Title = "Example Index View";
}
<h2>Index</h2>
<form asp-action="ExampleView" enctype="multipart/form-data">
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>
        <button type="submit">Save</button>
    </div>
}
</form>
HTML

5. 添加 Razor 頁面

在 Pages 的 Shared 資料夾中,新增一個 Razor 頁面並命名為 "_Example.cshtml"

新增 Razor 頁面

將以下代碼新增至 _Example.cshtml:

@Html.Partial("../Index.cshtml")
@Html.Partial("../Index.cshtml")
HTML

6. 新增一個新類別

  • 新增一個名為 "ControllerPDF" 的類別

這個類別會將 _Example.cshtml 裡的 HTML 包含在 _Layout.cshtml 中,然後返回給 HomeController.cs

  • 新增以下程式碼:
namespace WebApplication4
{
    public static class ControllerPDF
    {
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }
            controller.ViewData.Model = model;
            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
                if (viewResult.Success == false)
                {
                    return $"A view with the name {viewName} could not be found";
                }
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
                await viewResult.View.RenderAsync(viewContext);
                return writer.GetStringBuilder().ToString();
            }
        }
    }
}
namespace WebApplication4
{
    public static class ControllerPDF
    {
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }
            controller.ViewData.Model = model;
            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
                if (viewResult.Success == false)
                {
                    return $"A view with the name {viewName} could not be found";
                }
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
                await viewResult.View.RenderAsync(viewContext);
                return writer.GetStringBuilder().ToString();
            }
        }
    }
}
Namespace WebApplication4
	Public Module ControllerPDF
		<System.Runtime.CompilerServices.Extension> _
		Public Async Function RenderViewAsync(Of TModel)(ByVal controller As Controller, ByVal viewName As String, ByVal model As TModel, Optional ByVal As Boolean = False) As Task(Of String)
			If String.IsNullOrEmpty(viewName) Then
				viewName = controller.ControllerContext.ActionDescriptor.ActionName
			End If
			controller.ViewData.Model = model
			Using writer = New StringWriter()
				Dim viewEngine As IViewEngine = TryCast(controller.HttpContext.RequestServices.GetService(GetType(ICompositeViewEngine)), ICompositeViewEngine)
				Dim viewResult As ViewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, Not partial)
				If viewResult.Success = False Then
					Return $"A view with the name {viewName} could not be found"
				End If
				Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, New HtmlHelperOptions())
				Await viewResult.View.RenderAsync(viewContext)
				Return writer.GetStringBuilder().ToString()
			End Using
		End Function
	End Module
End Namespace
VB   C#

7. 修改 Program.cs

將以下代碼添加到以確保當按下保存按鈕時,頁面將導航到正確的 URL。

// Add your code block here
// Add your code block here
' Add your code block here
VB   C#
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(name:= "default", pattern:= "{controller=Home}/{action=Index}/{id?}")
VB   C#

8. 演示

  • 當按下具有 asp-action="ExampleView" 的儲存按鈕時,Index.cshtml 中的 ExampleView 方法將被啟動。
  • 將從 ExampleView 調用 ControllerPDF 類的 RenderViewAsync 方法。此方法將返回由 _layout.cshtml 包裹的 _Example.cshtml 生成的 html。
  • 通過將 RenderViewAsync 返回的 html 傳遞給 IronPDF 的 RenderHtmlAsPdf 方法來生成 PDF 文件。
創建 ASP.NET Core 專案