// 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和IronPDF,它們共同作用以方便將視圖渲染為 PDF。 IronPDF套件擴充了IronPDF的功能,特別是實現了將視圖渲染成 PDF 的功能。
若要執行轉換,請使用 RenderView 方法。 此方法需要幾個關鍵輸入:一個 HttpContext、".cshtml"檔案的路徑以及填入".cshtml"範本所需的資料。 透過呼叫 Persons 操作,您可以將目前視圖無縫渲染為 PDF 文件。
此外,您還可以使用RenderingOptions類別提供的一系列全面功能。 這些功能包括使用IronPDF添加頁碼、插入IronPDF和 HTML 頁首和頁腳,以及根據您的要求自訂 PDF 紙張大小。 您可以根據需要靈活地進行進一步修改或匯出生成的 PDF 文件。