CSHTML to PDF (MVC Framework)

This code example illustrates how to convert Views into PDF documents.

To achieve this, we utilize two packages: IronPdf.Extensions.Mvc.Framework and IronPdf, which work to facilitate the rendering of Views as PDFs. The IronPdf.Extensions.Mvc.Framework package extends the capabilities of IronPdf, specifically enabling the rendering of Views into PDFs.

To perform the conversion, use the RenderView method. This method requies a few key inputs: a HttpContext, the path to the ".cshtml" file, and the necessary data to populate the ".cshtml" template. By invoking the 'Persons' action, you can seamlessly render the current View into a PDF document.

Additionally, you have access to a comprehensive set of functionalities offered by the RenderingOptions class. These include the ability to add page numbers, insert text and HTML headers and footers, and customize the PDF paper size to your requirements. You have the flexibility to make further modifications or export the resulting PDF document as necessary.

How to Convert CSHTML Files to PDFs in C#

  1. Install the C# library for converting CSHTML files to PDFs in the ASP.NET MVC Framework
  2. Prepare the model and data to be displayed
  3. Instantiate the ChromePdfRenderer class
  4. Pass the current HttpContext and the CSHTML file path to the RenderView method
  5. View the PDF document in the browser or download it to the desktop