Export ASP.Net MVC View to PDF in 3 Quick steps

I often come across questions related to generating PDF file from HTML or converting ASP.Net MVC page to PDF at runtime. These days I do see the frequency of these queries increased and decided to write a small solution to this problem. Most of the solutions around this topic involves lot of code using components like ITextSharp. Even if we invest such an effort and solve the problem, it will still be (sometimes) a non-generic solution and will land up refactoring the code for achieving reusability. In this tutorial, I am going to share a quick solution that is flexible (at least in my perspective) and mostly reusable.

Step 1 – Create an ASP.Net MVC5 Solution using VS 2013. Create the following model and controller action in the solution.

image

Create Person model (Person.cs) in Models folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication2.Models
{
    public class Person
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
    }
}

Create GetPersons action in Home Controller.

        public ActionResult GetPersons()
        {
            List<Person> persons = new List<Person>();
            persons.Add(new Person() { Age = 29, Name = "Rami1", Email = "Rami1@abc.com" });
            persons.Add(new Person() { Age = 28, Name = "Rami2", Email = "Rami2@abc.com" });
            return View(persons);
        }

Create a strongly typed View for GetPersons Action with model being IEnumerable<Person>.

 

@model IEnumerable<WebApplication2.Models.Person>

@{
    ViewBag.Title = "GetPersons";
}

<h2>GetPersons</h2>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
    </tr>
}

</table>

 

 

Step 2 – Download Rotativa PDF nuget.

image

Add the following action to home controller which we need to invoke to generate PDF. We do need to specify the target Action to generate PDF so that it will be processed and its corresponding view will be generated as PDF.

        public ActionResult GeneratePDF()
        {
            return new Rotativa.ActionAsPdf("GetPersons");
        }

Step 3 – Test the application. Press F5 and start the application, navigate to /Home/GeneratePDF. That will download the PDF to the client side which can be saved.

image

That’s it, we got our PDF generation completed. This approach can be extended to any view in an ASP.Net MVC project including to the views holding images. One gotcha which needs to be remembered is to check out the rendered width of the views, there can be distortions in the generated PDF if the width is too wider. Advantage of this approach is that PDF generation can now be taken out of burden from developers and offload it to UI designers who are good at making things pretty.

Happy Coding!!!

You may also like...

  • vijo

    i am using rotativa pdf generator but it is working in localhost but it is not working in live server

  • Kiran Gupta

    Great tips…..persons who are not very tech familiar they can use carious software available online. Expert PDF is one of best software i used for converting html to pdf asp.net.

  • JellyBean

    this one works to create the pdf. however it does not show the information on the page. only time it shows anything is when i have an error

  • vishy

    How to upload the same in Azure.

    I want to publish this in azure but error comes as exe cannot execute.
    Please help.

  • RamiVemula

    @Vishy – I will try to compose one more article on the same topic. Stay tuned.

  • RamiVemula

    @Vijo – Please check permissions on the folder.

  • Hadi

    So nice. I greate fully happy for learning this article

  • Secret22

    hi, i am new to .net and mvc 5. how to add a button so as when you click it you see the pdf instead of having to surf to it via url … Thanks in advance

  • ramiramilu

    Hi Secret22, Do you mean to download PDF file? If so, please check this resource – http://www.intstrings.com/ramivemula/asp-net/how-to-download-files-from-server-to-client-using-a-generic-handler/

  • Scanner

    I tried a lot of tutorials of how to generate MVC View to PDF, including other tutorials that use Rotavita, but this is the best example tutorial that I have found. Everything is clearly described and guides the user along effortlessly, great job!!!

  • dlkSoftware

    I am not getting much support from Rotativa. Does anyone on here know if this project is still ongoing?

  • ramiramilu

    No, I will give it a try and will let you guys know.

  • pchaudhary2000

    Hi Rami,

    This is really a job well done but this code only work on my localhost but when I deploy the code on windows Azure platform this trick does not work and I am not able to create or download PDF at client side. Please help.

  • bala

    what do you mean by permissions

  • ramiramilu

    Can you give me more details on what error you got on Azure?

  • ramiramilu

    On shared environments, there might be less privileges for User account under which apppool is executing. In such scenarios custom 3rd party DLLs or EXEs will not be able work on that specific environment.

  • mona hassan

    Hello Rami ,
    Thank you so much for this amazing tutorial ,
    but i want to ask if possible to add a button to download the PDF file instead of write the URL http://localhost:61111/Home/GeneratePDF ??

  • ramiramilu

    Hi Mona, Definitely you can have a button and make it download PDF. For that you need to start with AsResultBase and get the bytes and use Response stream to make it downloadable.

  • ramiramilu

    Sure Lee, will do it some days.

  • ramiramilu

    what was the error?

  • mahii

    its not working in localhost give me solution that given solution like ”

    Unhandled Execution Error

  • ramiramilu

    Kindly debug and share more information.

  • Ari Lishu

    Error: Failed loading page http://localhost:37841/ (sometimes it will work just to ignore this error with –load-error-handling ignore)
    Exit with code 1, due to unknown error.

  • Anju

    Can I use this code in mvc4.

  • ramiramilu

    Yes you can use.

  • ramiramilu

    Can you share more details?

  • Anju

    Thank you, It’s working.

  • Anju

    Its working in my local, not working in Dev server and the error is msvcp120.dll is missing

  • ramiramilu

    Please check if that DLL is present in Dev server or not, if not present then make the DLL copy local to true and deploy it again.

  • Rashika

    i have asked this question few days back also bit i have not received any answer for that. I have write mvc using angular. view got all variables in angular. for those variables ur method not working. Is there any other i can achieve it .

  • Rashika

    how to remove @2014 MyASP.NET Application text from footer.

  • ramiramilu

    Simple way to remove the footer is to create a new Layout and specify the new layout at runtime probably through ActionFilter. In ActionFilter identify if the request is for PDF, in that case assign new layout than regular layout.

  • ramiramilu

    I am afraid you dont have that much support to create PDFs based on client side UI changes. What is the best bet you can have is to make the client side UI computational logic run, then post the values to the controller action. Then you can use third party Libraries and generate PDF of your interest and return File() bytes to the client.

  • ramiramilu

    I am afraid you dont have much support to create PDFs based on client side UI changes. What is the best bet you can have is to make the client side UI computational logic run, then post the values to the controller action. Then you can use third party Libraries and generate PDF of your interest and return File() bytes to the client.

  • Sarang

    I need pdf bytes to store it on server. In one comment you mention “start with AsResultBase and get the bytes and use Response stream to make it downloadable”. I am not getting it clear. Can you put the sample code lines to get byts?

  • ramiramilu

    @disqus_K5rfszpx0C:disqus Will give a try and will post the solution.

  • ramiramilu

    You can use CSS to apply watermark, check this solved SO thread – http://stackoverflow.com/questions/33317194/watermark-in-pdf-using-css-or-rotativa-pdf-generater

  • ramiramilu

    @Saania, You need to populate your ViewModel with only Search results. In that case PDF will be having only search results.

  • E. Bjorn

    You can use a free html to pdf converter for .net to convert MVC views to PDF. There is a C# code there you can use.

  • ramiramilu

    @disqus_RMIJyOBs2K:disqus , you can create a printable view with the content which you want to export to PDF and then use Rotativa.

  • ramiramilu

    I think you enabled authentication on your application. Make sure you are logged into the application before you provide an option to export to PDF.

  • ramiramilu

    Are you getting this error when you hosted the application? Please check permissions and whether the hosting provider allowed to run the external applications like rotativa.