IronPDF How-Tos Razor View to PDF IronPDF Razor Extension ByChaknith Bin January 25, 2023 Updated June 22, 2025 Share: IronPDF is a PDF library for .NET and .NET Core. It is mostly a free PDF library, as IronPDF is a commercial C# PDF library. It is free for development but must be licensed for commercial deployment. This clearer license model does not require developers to learn the ins and outs of GNU / AGPL license models and can instead focus on their projects.IronPDF enables .NET and .NET Core developers to generate, merge, split, edit, and extract PDF content easily in C#, F#, and VB.NET for .NET Core and .NET Framework as well as create PDFs from HTML, ASPX, CSS, JS, and image files.IronPDF has comprehensive PDF editing and generation functionality via HTML to PDF. How does it work? Well, most of the document design and layout can use existing HTML and HTML5 assets.You can download the C# Razor-to-PDF example project from the IronPDF Razor View to PDF download. View the IronPDF YouTube Playlist How to Render PDF from Razor View Web Download C# library to render PDF from Razor view Configure MVC model and controller Modify the Index.cshtml to trigger the function with button Add Razor page to customize the layout of the output PDF Create new C# class to handle retrieving the HTML content IronPDF features for .NET & .NET Core applications Some fantastic IronPDF PDF library features include: The .NET PDF library can generate PDF documents from HTML, images, and ASPX files Reading PDF text in .NET and .NET Core applications Extracting data and images from PDFs Merging PDF documents Splitting PDFs Manipulating PDFs IronPDF Advantages The IronPDF PDF library is easy to install The IronPDF .NET library has quick and easy licensing options IronPDF outshines most .NET PDF libraries and outperforms most .NET Core PDF libraries IronPDF is the PDF solution you've been looking for. Installing the IronPDF PDF library To install the IronPDF library for PDF in .NET or .NET Core is quite easy. You could install it in the following ways: Use the NuGet package manager and type the following into the command prompt: Install-Package IronPdf Using the NuGet package manager in Visual Studio by opening the "Selecting Manage NuGet Packages" from the project menu and searching for IronPDF, as shown below: Figure 1 - IronPDF NuGet Package This installs the PDF extension. With IronPDF you can use ASP.NET MVC to return a PDF file. A few code examples follow: An example of a method that could be served by your controller as shown below. public FileResult Generate_PDF_FromHTML_Or_MVC(long id) { // Create a PDF document from the HTML using var objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>"); var objLength = objPDF.BinaryData.Length; // Get the length of the binary data for the PDF 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) { // Create a PDF document from the HTML using var objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>"); var objLength = objPDF.BinaryData.Length; // Get the length of the binary data for the PDF 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 ' Create a PDF document from the HTML Dim objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>") Dim objLength = objPDF.BinaryData.Length ' Get the length of the binary data for the PDF Response.AppendHeader("Content-Length", objLength.ToString()) Response.AppendHeader("Content-Disposition", $"inline; filename=PDFDocument_{id}.pdf") Return File(objPDF.BinaryData, "application/pdf;") End Function $vbLabelText $csharpLabel An example of serving an existing PDF in ASP.NET follows. 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() $vbLabelText $csharpLabel Let’s do a quick example in ASP.NET using MVC and .NET Core. Open Visual Studio and create a new ASP.NET Core web application. 1. Create a new ASP.NET Core web project in Visual Studio 2. Create MVC Model Create a new folder and name it "Models" Right-click on the Model folder and add a new class Change the class name to "ExampleModel". Add content to the Model, for example: 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 $vbLabelText $csharpLabel 3. Add MVC Controller Create a new folder and name it "Controllers" Right-click on the Controllers folder and add a new "MVC controller - empty" Add content to the Controller: namespace WebApplication4.Controllers { public class HomeController : Controller { // This method handles the post request, generates HTML from Razor view, and then creates a PDF [HttpPost] public IActionResult ExampleView(ExampleModel model) { // Generate HTML content from Razor view asynchronously var html = await this.RenderViewAsync("_Example", model); // Initialize IronPdf ChromePdfRenderer var ironPdfRender = new IronPdf.ChromePdfRenderer(); // Render PDF from HTML content using var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html); // Return the PDF file to the client return File(pdfDoc.Stream.ToArray(), "application/pdf"); } } } namespace WebApplication4.Controllers { public class HomeController : Controller { // This method handles the post request, generates HTML from Razor view, and then creates a PDF [HttpPost] public IActionResult ExampleView(ExampleModel model) { // Generate HTML content from Razor view asynchronously var html = await this.RenderViewAsync("_Example", model); // Initialize IronPdf ChromePdfRenderer var ironPdfRender = new IronPdf.ChromePdfRenderer(); // Render PDF from HTML content using var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html); // Return the PDF file to the client return File(pdfDoc.Stream.ToArray(), "application/pdf"); } } } Namespace WebApplication4.Controllers Public Class HomeController Inherits Controller ' This method handles the post request, generates HTML from Razor view, and then creates a PDF <HttpPost> Public Function ExampleView(ByVal model As ExampleModel) As IActionResult ' Generate HTML content from Razor view asynchronously Dim html = Await Me.RenderViewAsync("_Example", model) ' Initialize IronPdf ChromePdfRenderer Dim ironPdfRender = New IronPdf.ChromePdfRenderer() ' Render PDF from HTML content Dim pdfDoc = ironPdfRender.RenderHtmlAsPdf(html) ' Return the PDF file to the client Return File(pdfDoc.Stream.ToArray(), "application/pdf") End Function End Class End Namespace $vbLabelText $csharpLabel 4. Modify Index.cshtml Inside the Pages folder, modify the Index.cshtml file to: @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. Add Razor Page Inside the Shared folder of Pages, add a Razor page and name it "_Example.cshtml" Add the code below to _Example.cshtml: @Html.Partial("../Index.cshtml") @Html.Partial("../Index.cshtml") HTML 6. Add a New Class Add a new class name "ControllerPDF" This class will take the HTML from _Example.cshtml with the wrap of _Layout.cshtml and return it to HomeController.cs Add the code below: namespace WebApplication4 { public static class ControllerPDF { public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false) { // If view name is not specified, use action descriptor's action name if (string.IsNullOrEmpty(viewName)) { viewName = controller.ControllerContext.ActionDescriptor.ActionName; } // Set the model for ViewData controller.ViewData.Model = model; using (var writer = new StringWriter()) { // Retrieve the service to find the view 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"; } // Create view context and render the view 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 view name is not specified, use action descriptor's action name if (string.IsNullOrEmpty(viewName)) { viewName = controller.ControllerContext.ActionDescriptor.ActionName; } // Set the model for ViewData controller.ViewData.Model = model; using (var writer = new StringWriter()) { // Retrieve the service to find the view 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"; } // Create view context and render the view 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 view name is not specified, use action descriptor's action name If String.IsNullOrEmpty(viewName) Then viewName = controller.ControllerContext.ActionDescriptor.ActionName End If ' Set the model for ViewData controller.ViewData.Model = model Using writer = New StringWriter() ' Retrieve the service to find the view 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 ' Create view context and render the view 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 $vbLabelText $csharpLabel 7. Modify Program.cs Add the below code to ensure that when the save button has been pressed the page will navigate to the correct 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?}") $vbLabelText $csharpLabel 8. Demonstration From the Index.cshtml, the ExampleView method will activate when the save button is pressed with asp-action="ExampleView". RenderViewAsync method of ControllerPDF class will be called from ExampleView. This method will return the generated HTML of _Example.cshtml wrap with _layout.cshtml. Generate PDF document by passing the return HTML from RenderViewAsync to RenderHtmlAsPdf method of IronPDF. Chaknith Bin Chat with engineering team now Software Engineer Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience. Ready to Get Started? Free NuGet Download Total downloads: 14,143,061 View Licenses