Wednesday, 15 October 2014

Easy and quick PDF generation using Rotativa

Here are the steps to gerenarte a PDF file in MVC application using Rotativa.
 
1. Install Rotativa from NuGet package. Search it in NuGet or install from Package Manager Console by the following command -
Install-Package Rotativa
 
2. Write an action method in controller that will return a View that will contain the contents you want to have in your PDF. For example, if you want to have a static text in your PDF like "Hello World", the view will have the text into it. In the conventional way you can use ViewModels to bind data to view and create your dynamic View. The ultimate aim is to generate a View as you want to have the PDF.
 
public ActionResult PDFView()
{
   var customViewModel = new CustomViewModel();
   
   // Code to populate the ViewModel with data..

   return View(customViewModel);
}
 
3. Set href of the action link (which is clicked to generate PDF) as an action method which will inturn call the previous action (PDFView) written and return the previous action as PDF. Here is the code sample -
 
public ActionResult ExportPDF()
{
  return new ActionAsPdf("PDFView") {FileName = "GeneratedPDFName.pdf"};
 
The FileName is the generated PDF file name.
 
This is all and you will get the PDF generated and downloaded to the browser.

No comments:

Post a Comment