Generating PDF for report or any document purpose that can be
printable in .NET is a bit cumbersome. But this can be achieved in
ASP.NET MVC very easily and quickly using Rotativa tools
which is available in Nuget package. It gives you the flexibility to
create PDFs directly from Views or Partial Views or URLs too.
Rotativa is an ASP.NET MVC library, which helps to generate PDF from MVC controller.
How to Install
Install using the Nuget package manager (search for Rotativa) or, more conveniently, with the package manager console, typing:
We can do by searching it from Nuget package manager
A folder with a name Rotativa in your project
gets created, along with a Rotativa package folder in project root
directory and also gets the reference to your solution.
After that your project structure in looking like this:
Now create a demo MVC application named as "RotativaPDF", where we will generate a PDF with some content and logo.
The solution is implemented with some classes of Rotativa to generate PDF.
1. ViewAsPdf– This class will generate the PDF based on views.
Here "RotativaViewAsPDF" is the view name i.e., RotativaViewAsPDF.cshtml(Razor view)
2. ActionAsPdf - This will take other action method to generate PDF using view.
Here "GeneratePDF" is the name of other action which will return a view to generate PDF.
3. PartialViewAsPdf - This class will generate the PDF based on partial views.
Here "_RotativaPartialViewAsPdf" is the view name i.e., _RotativaPartialViewAsPdf.cshtml(Razor view)
4. UrlAsPdf - This class will generate the PDF of URL content.
5. One thing that you really need to care about this, you have to make tabular format to get actual output of HTML as PDF. You can also set page Header and page Footer using Rotativa.
- When you want to add Header or Footer then you have to make separate directory to store that file and also you have to make an HTML file for Header or Footer. You can also display images in Header or Footer
- You can get HTML for display Image and Page Number. For that you just have to add following lines in your HTML page.
- HTML for set Image
- You can also set Page Break in Rotativa.
Now implement the above code and run. Yes, now click on each link, you
can see the standard model popup to open as a PDF or save.