// PM > Install-Package IronPdf.Extensions.Mvc.Framework
public ActionResult Persons()
{
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")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
' PM > Install-Package IronPdf.Extensions.Mvc.Framework
Public Function Persons() As ActionResult
'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
' Provide the path to your view file
Dim viewPath = "~/Views/Home/Persons.cshtml"
Dim renderer As New ChromePdfRenderer()
' Render Razor view to PDF document
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)
Response.Headers.Add("Content-Disposition", "inline")
' View the PDF
Return File(pdf.BinaryData, "application/pdf")
End If
Return View(persons_Conflict)
End Function
Install-Package IronPdf
CSHTML 轉 PDF (MVC 框架)
此代码示例说明如何将视图转换为 PDF 文件。
为了实现这一点,我们使用了两个套件:IronPdf.Extensions.Mvc.Framework 和 IronPdf,它们共同促进了将视图渲染为 PDF 的过程。IronPdf.Extensions.Mvc.Framework 包扩展了 IronPdf 的功能,特别是启用了将视图渲染为 PDF 的功能。
要进行转换,请使用 RenderView 方法。此方法需要几个关键输入:HttpContext、“.cshtml” 文件的路径,以及填充 “.cshtml” 模板所需的数据。通过调用 'Persons' 操作,您可以无缝地将当前视图渲染为 PDF 文件。
此外,您还可以访问 RenderingOptions 类提供的一整套功能。这些功能包括添加 頁碼,插入 文本和HTML頁眉和頁腳,並根據您的需求自訂 PDF 的紙張大小。您可以靈活地進行進一步的修改或根據需要匯出所生成的 PDF 文件。