In this article, we are going to learn how to use Rotativa.AspNetCore tool to create PDFs from Views in ASP.NET Core. If you have worked with ASP.NET MVC, the Rotativa tool is already available there, which we can use for generating pdfs.
Source code
Icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY
This tool was created by Italian Giorgio Bozio. He had a requirement for generating pdf in ASP.NET MVC and a recurring task was to set up a way to create PDF docs, for business flow or reporting.
In the past, I used a lot of Crystal Reports. It had a very nice editor that users who weren't programmers could use with ease. Sometimes, though, it was problematic when installing on new servers and it was expensive, especially for projects where the requirements did not involve producing new layouts frequently.
Then, I found the wkhtmltopdf command line tool, tried it, and looked at opinions on the web. The first experiences were great. It was fast and the PDF docs came out pretty nice. And, most importantly, it was free.
History of Rotativa referred from - http://letsfollowtheyellowbrickroad.blogspot.in/
What is wkhtmltopdf (wkhtmltopdf.exe)?
wkhtmltopdf is a C library.
wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt Web Kit rendering engine.
Definition referred to- https://wkhtmltopdf.org/
Tool to use with ASP.NET MVC
If you want a tool for creating pdf in ASP.NET MVC then you can download it from NuGet.
Command: - Install-Package Rotativa -Version 1.7.4-rc
Do not use 1.7.3, it has issues.
Find it on GitHub:- https://github.com/webgio/Rotativa
Prerequisite
- Visual Studio 2017 with ASP.NET CORE 2.0
- AspNetCore 1.0.6 version
Creating ASP.NET Core MVC Application
Now let’s start with creating a simple application in ASP.NET MVC Core.
Open New Visual Studio 2017 IDE.
After opening IDE, next, we are going to create ASP.NET MVC Core project. For doing that, just click File - New - Project.
After choosing a project, a new dialog will pop up with the name "New Project". In that, we are going to choose Visual C# Project Templatesà.NET Coreà ASP.NET Core Web Application. Then, we are going to name the project as "DemoRotativa".
After configuring the project, next, we are going to see project structure.
After creating the project next, we are going to install Rotativa.AspNetCore to the project.
Installing Rotativa.AspNetCore to project
We are going to install Rotativa.AspNetCore 1.0.6 version which needs dependency of AspNetCore MVC 2.o. We already have created ASP.NET CORE 2.0 project; we do not need to worry.
We can install it via package manager console or via Manage package solution Windows.
Let’s install it using package manager console.
After installing Rotativa.AspNetCore next, we need to do configuration.
Configuration Rotativa.AspNetCore setting in a startup.cs class
We add this setting in a startup.cs class inside Configure method to set a relative path to the wkhtmltopdf.exe file to access.
RotativaConfiguration.Setup(env);
Next, we need to add a new Folder in WWW with name “Rotativa” and inside this folder, we are going to add
wkhtmltopdf.exe, wkhtmltoimage.exe files.
You can download this files from GitHub if you download sample solution which I have provided
https://github.com/webgio/Rotativa.AspNetCore
Note
Download the solution and you will get this exe files.
Next, after adding exe files, we are going to add Controller.
Adding DemoController
For adding controller just right click on controller folder then choose "Add," inside that, choose to Add New item. A new dialog will popup with Add New item, inside that choose "MVC Controller Class" and Name your controller as "DemoController" and click on Add button to create a Demo controller.
After adding controller, next, we are going to Add Action to this Controller.
Adding [HttpGet] DemoViewAsPDF Action Method
We are going to add action method with name DemoViewAsPDF and this action method will return ViewAsPdf result.
Complete Code Snippet of DemoViewAsPDF
- using Microsoft.AspNetCore.Mvc;
- using Rotativa.AspNetCore;
-
-
- namespace DemoRotativa.Controllers
- {
- public class DemoController : Controller
- {
- public IActionResult DemoViewAsPDF()
- {
- return new ViewAsPdf("DemoViewAsPDF");
- }
- }
- }
After adding Action Method, next, we are going to add “DemoViewAsPDF” View.
Adding DemoViewAsPDF View
On this View, we have added simple Billing Invoice.
Code snippet of DemoViewAsPDF View
- @{
- Layout = null;
- }
-
- <html>
- <head>
- <meta charset="utf-8">
- <title>Demo</title>
- <link rel="stylesheet" href="style.css">
- <link rel="license" href="https://www.opensource.org/licenses/mit-license/">
- <script src="script.js"></script>
- <link href="~/css/demo.css" rel="stylesheet" />
-
- </head>
- <body>
- <header>
- <h1>Invoice</h1>
- <address contenteditable>
- <p>Jonathan Neal</p>
- <p>101 E. Chapman Ave<br>Orange, CA 92866</p>
- <p>(800) 555-1234</p>
- </address>
- <span><img src="D:\DemoRotativa\DemoRotativa\DemoRotativa\wwwroot\images\Invoice.jpg" /><input type="file" accept="image/*"></span>
- </header>
- <article>
- <h1>Recipient</h1>
- <address contenteditable>
- <p>Demo Company<br>c/o Saineshwar</p>
- </address>
- <table class="meta">
- <tr>
- <th><span contenteditable>Invoice #</span></th>
- <td><span contenteditable>000001</span></td>
- </tr>
- <tr>
- <th><span contenteditable>Date</span></th>
- <td><span contenteditable>January 1, 2018</span></td>
- </tr>
- <tr>
- <th><span contenteditable>Amount Due</span></th>
- <td><span id="prefix" contenteditable>र </span><span>600.00</span></td>
- </tr>
- </table>
- <table class="inventory">
- <thead>
- <tr>
- <th><span contenteditable>Item</span></th>
- <th><span contenteditable>Description</span></th>
- <th><span contenteditable>Rate</span></th>
- <th><span contenteditable>Quantity</span></th>
- <th><span contenteditable>Price</span></th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td><a class="cut">-</a><span contenteditable>Front End Consultation</span></td>
- <td><span contenteditable>Experience Review</span></td>
- <td><span data-prefix>र </span><span contenteditable>150.00</span></td>
- <td><span contenteditable>4</span></td>
- <td><span data-prefix>र </span><span>600.00</span></td>
- </tr>
- </tbody>
- </table>
-
- <table class="balance">
- <tr>
- <th><span contenteditable>Total</span></th>
- <td><span data-prefix>र </span><span>600.00</span></td>
- </tr>
- <tr>
- <th><span contenteditable>Amount Paid</span></th>
- <td><span data-prefix>र </span><span contenteditable>0.00</span></td>
- </tr>
- <tr>
- <th><span contenteditable>Balance Due</span></th>
- <td><span data-prefix>र </span><span>600.00</span></td>
- </tr>
- </table>
- </article>
-
- <aside>
- <h1><span contenteditable>Additional Notes</span></h1>
- <div contenteditable>
- <p>A finance charge of 1.5% will be made on unpaid balances after 30 days.</p>
- </div>
- </aside>
- </body>
- </html>
Now we have completed with all settings so let’s save this application and access your First Pdf.
URL to access:- http://localhost:#####/demo/DemoViewAsPDF
Snapshot of Pdf
Setting Margin to Pdf
For displaying a demo of Margin we are going to add another Action Method with name “DemoPageMarginsPDF” and along with this we are also going to add View with the same name “DemoPageMarginsPDF”.
Code snippet for setting Margin to Pdf
- public IActionResult DemoPageMarginsPDF()
- {
- var report = new ViewAsPdf("DemoPageMarginsPDF")
- {
- PageMargins = { Left = 20, Bottom = 20, Right = 20, Top = 20 },
- };
- return report;
- }
Output
Setting Orientation to Pdf
- Landscape
- Portrait
Code snippet for setting Orientation to Pdf
- public IActionResult DemoOrientationPDF(string Orientation)
- {
- if (Orientation == "Portrait")
- {
- var demoViewPortrait = new ViewAsPdf("DemoViewAsPDF")
- {
- FileName = "Invoice.pdf",
- PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
- };
- return demoViewPortrait;
- }
- else
- {
- var demoViewLandscape = new ViewAsPdf("DemoViewAsPDF")
- {
- FileName = "Invoice.pdf",
- PageOrientation = Rotativa.AspNetCore.Options.Orientation.Landscape,
- };
- return demoViewLandscape;
- }
- }
Output - Orientation Portrait
Url to access :- http://localhost:60042/demo/DemoOrientationPDF?Orientation=Portrait
Output - Orientation Landscape
Url to access :- http://localhost:60042/demo/DemoOrientationPDF?Orientation=Landscape
Notes :- https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
Setting Page number to Pdf
The customization of the pdf files can be done using Custom Switches.
Options
Arguments | Description |
--page-offset <offset> | Set the starting page number (default 0) |
--footer-center <text> | Centered footer text |
[page] | Replaced by the number of the pages currently being printed |
--footer-font-size <size> | Set footer font size (default 12) |
For adding a Page number at the footer of the page we are going to use Custom Switches.
Code snippet for setting Page Number to Pdf
- public IActionResult DemoPageNumberPDF()
- {
- return new ViewAsPdf("DemoPageNumberPDF")
- {
- CustomSwitches = "--page-offset 0 --footer-center [page] --footer-font-size 12"
- };
- }
Output
Setting Page Size to Pdf
We can set various page sizes of pdf, such as “A0”, “A1”, “A2”, “A3”, “A4”, “A5”. etc.
For the demo, we are going to set “A6” Size.
Code snippet for setting Page Size to Pdf
- public IActionResult DemoPageSizePDF()
- {
- return new Rotativa.AspNetCore.ViewAsPdf("DemoPageSizePDF")
- {
- PageSize = Rotativa.AspNetCore.Options.Size.A6,
- };
- }
Output
Setting Page Number in different format to PDF
For adding a Page number at the footer of the page, we are going to use Custom Switches.
In this part, we display current date with current page number and last page number in the footer.
e.g.:
Current Date “18/02/2018” Page: Current page / Last Page
Options
Arguments | Description |
–footer-center | This aligns the footer at the center foot of the page. |
Page:[page]/[toPage] | The [page] to [toPage] marks the current page and the total number of pages in the file |
–footer-font-size | Displays line above the footer |
–footer-spacing | Sets the spacing between the footer-line and the text |
–footer-line | Displays line above the footer |
–footer-font-name | Sets the font family/style of text |
Code snippet
- public IActionResult DemoPageNumberwithCurrentDate()
- {
- var pdfResult = new ViewAsPdf("DemoPageNumberwithCurrentDate")
- {
- CustomSwitches =
- "--footer-center \" Created Date: " +
- DateTime.Now.Date.ToString("dd/MM/yyyy") + " Page: [page]/[toPage]\"" +
- " --footer-line --footer-font-size \"12\" --footer-spacing 1 --footer-font-name \"Segoe UI\""
- };
-
- return pdfResult;
- }
Converting Model-based View to Pdf
In this part, we are going to send the model to view and then we are going to convert view to pdf, for doing that first we need to add Model, we are going to add a simple model with name “Customer”.
Customer Model
- public class Customer
- {
- public int CustomerID { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public string Country { get; set; }
- public string City { get; set; }
- public string Phoneno { get; set; }
- }
Adding New Action Method DemoModelPDF
In this action method, we are going create a list of customers and send this collection to DemoModelPDF View.
Code snippet
- public IActionResult DemoModelPDF()
- {
- List<Customer> customerList = new List<Customer>()
- {
- new Customer { CustomerID = 1, Address = "Taj Lands Ends 1", City = "Mumbai" , Country ="India", Name ="Sai", Phoneno ="9000000000"},
- new Customer { CustomerID = 2, Address = "Taj Lands Ends 2", City = "Mumbai" , Country ="India", Name ="Ram", Phoneno ="9000000000"},
- new Customer { CustomerID = 3, Address = "Taj Lands Ends 3", City = "Mumbai" , Country ="India", Name ="Sainesh", Phoneno ="9000000000"},
- new Customer { CustomerID = 4, Address = "Taj Lands Ends 4", City = "Mumbai" , Country ="India", Name ="Saineshwar", Phoneno ="9000000000"},
- new Customer { CustomerID = 5, Address = "Taj Lands Ends 5", City = "Mumbai" , Country ="India", Name ="Saibags", Phoneno ="9000000000"}
-
- };
-
- return new ViewAsPdf("DemoModelPDF", customerList);
- }
DemoModelPDF View
On View, we just iterate Customer collection.
Code snippet of DemoModelPDF View
- @model List<DemoRotativa.Models.Customer>
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>Bootstrap Example</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- </head>
- <body>
- <div class="container">
- <h2>Customer</h2>
- <p>Customer Details</p>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>CustomerID</th>
- <th>Name</th>
- <th>Address</th>
- <th>Country</th>
- <th>City</th>
- <th>Phoneno</th>
- </tr>
- </thead>
- <tbody>
-
- @foreach (var item in Model)
- {
- <tr>
- <td>@item.CustomerID</td>
- <td>@item.Name</td>
- <td>@item.Address</td>
- <td>@item.Country</td>
- <td>@item.City</td>
- <td>@item.Phoneno</td>
- </tr>
- }
-
- </tbody>
- </table>
- </div>
- </body>
- </html>
Output
Conclusion
In this article, we have learned how to use Rotativa.AspNetCore with ASP.NET Core in a step by step way. First we started with creating Project then controller after that we have added NuGet package of Rotativa.AspNetCore and further we have created PDF of View in various ways.
Note
Do not use ViewData and TempData to display data on View because it has some issues which will resolve soon; use Model which works perfectly.