IronPDF Razor Extension

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

IronPDF 是一个适用于 .NET 和 .NET Core 的 PDF 库。它主要是一个免费的 pdf 库,因为 IronPDF 是一个公开商业化的 C# PDF 库。开发是免费的,但商业部署必须获得许可。这种更清晰的许可模式不需要开发人员学习 GNU / AGPL 许可模式的来龙去脉,他们可以专注于自己的项目。

IronPDF 能让 .NET 和 .NET Core 开发人员在 C#、F#和 VB.NET 中轻松生成、合并、分割、编辑和提取 PDF 内容,适用于 .NET Core 和 .NET Framework,还能从 HTML、ASPX、CSS、JS 和图像文件中创建 PDF。

通过 HTML to PDF,IronPDF 拥有全面的 PDF 编辑和生成功能。它是如何工作的?大部分文档设计和布局都可以使用现有的 HTML 和 HTML5 资产。

您可以从以下链接下载文件项目 链接.

适用于 .NET 和 .NET Core 应用程序的 IronPDF 功能

IronPDF pdf 库的一些神奇功能包括

  • .NET pdf 库可以 生成 PDF 从 HTML、图像和 ASPX 文件中提取文档
  • 在 .NET 和 .NET Core 应用程序中读取 PDF 文本
  • 从 PDF 文件中提取数据和图像
  • 合并 PDF 文档
  • 分割 PDF
  • 操作 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 Web 项目

创建 ASP.NET Core 项目

2.创建 MVC 模型

  • 创建新文件夹并命名为 "模型
添加文件夹
  • 右击模型文件夹,添加一个新类
添加班级
  • 将类名改为 "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 控制器

  • 创建新文件夹并命名为 "控制器
  • 右键点击控制器文件夹,添加新的 "MCV 控制器 - 空"。
添加控制器类

为控制器添加内容:

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 页面,并将其命名为"_Example.cshtml"。

添加剃须刀页面

将以下代码添加到 _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。

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.演示

  • 在 Index.cshtml 中,当按下保存按钮时,ExampleView 方法将激活,asp-action="ExampleView"。
  • ExampleView 将调用 ControllerPDF 类的 RenderViewAsync 方法。该方法将返回用 _layout.cshtml 封装的 _Example.cshtml 生成的 html。

  • 通过将 RenderViewAsync 返回的 html 传递给 IronPDF 的 RenderHtmlAsPdf 方法,生成 PDF 文档。
创建 ASP.NET Core 项目