How to Convert Views to PDFs in ASP.NET MVC

A View is a component in the ASP.NET framework used for generating HTML markup in web applications. It is a part of the Model-View-Controller (MVC) pattern, commonly used in ASP.NET MVC and ASP.NET Core MVC applications. Views are responsible for presenting data to the user by rendering HTML content dynamically.

ASP.NET Web Application (.NET Framework) MVC is a web application framework provided by Microsoft. It follows a structured architectural pattern known as Model-View-Controller (MVC) to organize and streamline the development of web applications.

  • Model: Manages data, business logic, and data integrity.
  • View: Presents the user interface and renders information.
  • Controller: Handles user input, processes requests, and orchestrates interactions between the Model and View.

IronPDF simplifies the process of creating PDF files from Views within an ASP.NET MVC project. This makes PDF generation easy and direct in ASP.NET MVC.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet

    PM > Install-Package IronPdf

  2. Copy the code

    new IronPdf.ChromePdfRenderer().RenderView(HttpContext, "Views/Home/Report.cshtml", model).SaveAs("report.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

IronPDF Extension Package

The IronPdf.Extensions.Mvc.Framework package is an extension of the main IronPdf package. Both the IronPdf.Extensions.Mvc.Framework and IronPdf packages are required to render Views to PDF documents in an ASP.NET MVC.

Install-Package IronPdf.Extensions.Mvc.Framework
C# NuGet Library for PDF

Install with NuGet

Install-Package IronPdf.Extensions.Mvc.Framework

Render Views to PDFs

To convert Views into PDF files, you will need an ASP.NET Web Application (.NET Framework) MVC project.

Add a Model Class

  • Navigate to the "Models" folder
  • Create a new C# class file named "Person." This class will serve as a model to represent individual data. Use the following placeholder for guidance:
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-mvc-framework-model.cs
namespace ViewToPdfMVCSample.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}
Namespace ViewToPdfMVCSample.Models
	Public Class Person
		Public Property Id() As Integer
		Public Property Name() As String
		Public Property Title() As String
		Public Property Description() As String
	End Class
End Namespace
$vbLabelText   $csharpLabel

Edit the Controller

Navigate to the "Controllers" folder and open the "HomeController" file. We are going to add the "Persons" action. Please refer to the code below for guidance:

In the provided code, the ChromePdfRenderer class is first created. To use the RenderView method, you'll need to provide it with an HttpContext, specify the path to the "Persons.cshtml" file, and provide a List containing the necessary data. When rendering the View, users have the option to utilize RenderingOptions to customize margins, add custom text and HTML headers and footers, and apply page numbers to the resulting PDF document.

Please noteThe PDF document can be downloaded to the machine using the following code: File(pdf.BinaryData, "application/pdf", "viewToPdfMVC.pdf").

using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;

namespace ViewToPdfMVCSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // GET: Person
        public ActionResult Persons()
        {
            // Create a list of Person objects
            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")
            {
                // Define the path to the View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                // Instantiate the ChromePdfRenderer
                ChromePdfRenderer renderer = new ChromePdfRenderer();

                // Render the view to a PDF document
                PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);

                // Set headers to view the PDF in-browser
                Response.Headers.Add("Content-Disposition", "inline");

                // Return the generated PDF file
                return File(pdf.BinaryData, "application/pdf");
            }
            return View(persons);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;

namespace ViewToPdfMVCSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // GET: Person
        public ActionResult Persons()
        {
            // Create a list of Person objects
            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")
            {
                // Define the path to the View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                // Instantiate the ChromePdfRenderer
                ChromePdfRenderer renderer = new ChromePdfRenderer();

                // Render the view to a PDF document
                PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);

                // Set headers to view the PDF in-browser
                Response.Headers.Add("Content-Disposition", "inline");

                // Return the generated PDF file
                return File(pdf.BinaryData, "application/pdf");
            }
            return View(persons);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
Imports IronPdf
Imports System.Collections.Generic
Imports System.Web.Mvc
Imports ViewToPdfMVCSample.Models

Namespace ViewToPdfMVCSample.Controllers
	Public Class HomeController
		Inherits Controller

		Public Function Index() As ActionResult
			Return View()
		End Function

		' GET: Person
		Public Function Persons() As ActionResult
			' Create a list of Person objects
'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
				' Define the path to the View file
				Dim viewPath = "~/Views/Home/Persons.cshtml"

				' Instantiate the ChromePdfRenderer
				Dim renderer As New ChromePdfRenderer()

				' Render the view to a PDF document
				Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)

				' Set headers to view the PDF in-browser
				Response.Headers.Add("Content-Disposition", "inline")

				' Return the generated PDF file
				Return File(pdf.BinaryData, "application/pdf")
			End If
			Return View(persons_Conflict)
		End Function

		Public Function About() As ActionResult
			ViewBag.Message = "Your application description page."
			Return View()
		End Function

		Public Function Contact() As ActionResult
			ViewBag.Message = "Your contact page."
			Return View()
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Once you obtain the PdfDocument object through the RenderView method, you can make various improvements and adjustments to it. You can convert the PDF to PDFA or PDFUA formats, sign digital signature to the created PDF, or merge and split PDF documents as required. Moreover, the library enables you to rotate pages, insert annotations or bookmarks, and apply distinct watermarks to your PDF files.

Add a View

  • Right-click on the newly added Person action and select "Add View."

Right-click on Persons action

  • Choose "MVC 5 View" for the new Scaffolded item.

Select scaffold

  • Select the "List" template and the "Person" model class.

Add view

This will create a .cshtml file named "Persons."

  • Navigate to the "Views" folder -> "Home" folder -> "Persons.cshtml" file.

To add a button that invokes the "Persons" action, use the code below:

@using (Html.BeginForm("Persons", "Home", FormMethod.Post))
{
    <input type="submit" value="Print Person" />
}
@using (Html.BeginForm("Persons", "Home", FormMethod.Post))
{
    <input type="submit" value="Print Person" />
}
HTML

Add a Section to the Top Navigation Bar

  • In the "Views" folder, navigate to the "Shared" folder -> "_Layout.cshtml" file. Place the "Person" navigation item after "Home."

Ensure that the values for the ActionLink method match exactly with our file name, which in this case is "Persons."

<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
    <div class="container">
        @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
            </ul>
        </div>
    </div>
</nav>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
    <div class="container">
        @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
            </ul>
        </div>
    </div>
</nav>
HTML

Run the Project

This will show you how to run the project and generate a PDF document.

Execute ASP.NET MVC Project

Output PDF

Download ASP.NET MVC Project

You can download the complete code for this guide. It comes as a zipped file that you can open in Visual Studio as a ASP.NET Web Application (.NET Framework) MVC project.

Download the MVC sample project for PDF conversion

Frequently Asked Questions

How can I convert Views to PDFs in ASP.NET Core MVC?

You can convert Views to PDFs in ASP.NET Core MVC using the IronPDF library. Install the IronPdf.Extensions.Mvc.Framework package via NuGet and use the ChromePdfRenderer class to render views into PDF documents.

What is necessary to render Views into PDF documents in ASP.NET MVC?

To render Views into PDF documents in ASP.NET MVC, you need the IronPDF library and the ChromePdfRenderer class, which requires an HttpContext, the view path, and a data list to generate the PDF.

How can I customize the PDF output using IronPDF in an ASP.NET application?

IronPDF allows customization of PDF output using RenderingOptions. You can adjust margins, add custom headers and footers, and include page numbers to tailor the PDF document to your needs.

What steps are involved in setting up a model class in ASP.NET MVC for PDF generation?

To set up a model class in ASP.NET MVC, navigate to the 'Models' folder, create a new C# class file, and define the class with properties that represent the data structure you need for PDF generation.

How do I integrate a PDF generation button into a View in ASP.NET MVC?

To integrate a PDF generation button into a View in ASP.NET MVC, you can add a button element in the HTML markup of your View and link it to an action in your controller that uses IronPDF to render the View as a PDF.

What is the process to add a View in ASP.NET MVC?

To add a View in ASP.NET MVC, right-click on the desired action in the controller, select 'Add View,' choose 'MVC 5 View' as the scaffolded item, and select the appropriate template and model class.

Where can I find a sample project for View to PDF conversion in ASP.NET MVC?

You can download a complete MVC sample project for PDF conversion from the IronPDF website, which includes a zipped file to open in Visual Studio for practical implementation.

How do I install IronPDF for use in an ASP.NET MVC project?

Install IronPDF in an ASP.NET MVC project by using NuGet Package Manager with the command: Install-Package IronPdf.Extensions.Mvc.Framework.

What are some common troubleshooting steps if PDF generation fails in ASP.NET MVC?

If PDF generation fails in ASP.NET MVC, ensure that the IronPDF package is correctly installed, check the paths and context passed to ChromePdfRenderer, and verify that the view and data are correctly rendered.

Chaknith Bin
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.