How to generate PDF from MVC page in asp.net development

banner

How to generate PDF from MVC page in asp.net development

Technoligent professionals have shared many tutorials to make the job of asp.net developers easy. In this article, they will explain how to generate PDF file from MVC page and send email using generated PDF as attachment. Read and learn step-by-step in this tutorial and make best practices for asp.net development. They have also shared the things you may need before commencing the project.

For this task I will create one partial view in MVC 4 project that contains one text box and some questions with two options. Also, I am using Rotativa library to convert .cshtml page to PDF, you can get this library from NuGet package.

First start with MVC project, create a MVC 4 project. Add one model as below and name it “GeneratePDFModel”.

PDF from MVC

Add following code to GeneratePDFModel class as below and inherit PartialViewAsPdf class from Rotativa library. It is a main class which generate PDF file from .cshtml page. Main purpose of this code is the PartialViewAsPdf will return a PDF file, but we want a byte array to create attachment file for email.

PDF from MVC

To include Rotativa library in your project execute following command to Package Manager Console.

INSTALL PACKAGE ROTATIVA

Next step is to add following key values to in webconfig file.

PDF from MVC

Add Index view as below and update design as per requirement.

PDF from MVC

Then add Partial view to Home folder and design as below.

PDF from MVC

Now, create ActionResult which execute HttpPost method for Index page in Home Controller with model as input parameter.

PDF from MVC

Above code will get content from Partial view and generate PDF file using ViewAsPdf2 method then send email to specified email address with newly generated PDF file as attachment.

Following is the output of index view.

PDF from MVC

And following is the pdf file screenshot sent as attachment with email

PDF from MVC

You can update partial view design as per your requirement which effects content of pdf file. All the steps shared by Technoligent experts are essential to create PDF file from MVC page. You also need the things required for preparing PDFs (that is also mentioned in the post). You may share your review for this tutorial or ask query related to the subject from ASP.Net development services. Don’t forget to comment in the below section.

An Aegis Group Company