Generate PDF Using Rotative In .NET Core

In this article, we are going to learn how to use Rotativa.AspNetCore tool to generate PDFs from Views in ASP.NET Core.

Rotativa is an open-source package. We can easily generate the pdf using the Rotativa library. Rotativa uses the wkhtmltopdf tool which is used to create a PDF document from HTML that renders in the browser.

The Rotativa framework provides Rotativa namespace. This namespace contains the following classes:
1. ActionAsPdf – accepts a View named as string parameter so that it can be converted into PDF.
2. PartialViewAsPdf – returns partial view as PDF.
3. UrlAsPdf – enables to return any URL as PDF.
4. ViewAsPdf – returns the result as PDF instead of HTML Response.

Let us understand with the help of an example.

First, create a new project.

Then open your project and install the following NuGet package.

Install-Package Rotativa.AspNetCore

Next, we need to add a new Folder in WWW with the name Rotativa and inside this folder, we are going to add

wkhtmltopdf.exe, wkhtmltoimage.exe files.

You can download these files from GitHub if you download the sample solution which I have provided here

Next, open your startup.cs file and add the following line in that.

                                                                                                                                                                                                                                                                                                                    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
     if (env.IsDevelopment())
     {
        app.UseDeveloperExceptionPage();
     }
     RotativaConfiguration.Setup((Microsoft.AspNetCore.Hosting.IHostingEnvironment)env);
     app.UseHttpsRedirection();
     app.UseRouting();
     app.UseAuthorization();
     app.UseEndpoints(endpoints =>
     {
          endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
          endpoints.MapControllers();
     });
}

Then create ExportController and add the following code to it.

using Microsoft.AspNetCore.Mvc;
using Rotativa.AspNetCore;
using RotativeDemo.Models;

namespace RotativeDemo.Controllers
{
    public class ExportController : Controller
    {
        public IActionResult Index()
        {
            return new ViewAsPdf(Invoice.GetOne());
        }
    }
}

Create folder name as Models and create Invoice.cs class paste following code in it.

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

namespace RotativeDemo.Models
{
    public class Invoice
    {
        public string InvoiceNo { get; set; }
        public string CustomerName { get; set; }
        public string CustomerBillingAddress { get; set; }
        public DateTime InvoiceDate { get; set; }
        public DateTime DueDate { get; set; }

        public IList<InvoiceLine> Lines { get; set; }

        public Invoice()
        {
            Lines = new List<InvoiceLine>();
        }
        public decimal Total
        {
            get
            {
                return Lines.Sum(l => l.Total);
            }
        }
        public decimal Vat
        {
            get
            {
                return Lines.Sum(l => l.Vat);
            }
        }
        public static Invoice GetOne()
        {
            var invoice = new Invoice();
            invoice.CustomerBillingAddress = "Wellington str. 2-311, 10113, NY, USA";
            invoice.CustomerName = "Imaginary Corp.";
            invoice.DueDate = DateTime.Now.AddDays(30);
            invoice.InvoiceDate = DateTime.Now.Date;
            invoice.InvoiceNo = "B383810312-2213";

            var line = new InvoiceLine();
            line.Amount = 12;
            line.LineTitle = "Fancy work desks";
            line.UnitPrice = 800;
            line.VatPercent = 20;
            invoice.Lines.Add(line);

            line = new InvoiceLine();
            line.Amount = 5;
            line.LineTitle = "Espresso machines";
            line.UnitPrice = 200;
            line.VatPercent = 20;
            invoice.Lines.Add(line);

            line = new InvoiceLine();
            line.Amount = 30;
            line.LineTitle = "Meeting room whiteboards";
            line.UnitPrice = 50;
            line.VatPercent = 20;
            invoice.Lines.Add(line);

            return invoice;
        }
    }

    public class InvoiceLine
    {
        public string LineTitle { get; set; }
        public decimal UnitPrice { get; set; }
        public int Amount { get; set; }
        public int VatPercent { get; set; }
        public decimal Net
        {
            get
            {
                return UnitPrice * Amount;
            }
        }
        public decimal Total
        {
            get
            {
                return Net * (1 + VatPercent / 100M);
            }
        }
        public decimal Vat
        {
            get
            {
                return Net * (VatPercent / 100M);
            }
        }
    }
}

Add the view of Index and paste the following code to it.

@model RotativeDemo.Models.Invoice
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Invoice @Model.InvoiceNo</title>
    <style>
        body {
            margin: 0px;
            font-family: 'Segoe UI', Arial;
        }
        .invoice-head {
            clear: both;
            display: block;
            padding: 10px;
            margin-bottom: 40px;
        }
        .invoice-title {
            background-color: navy;
            color: white;
            font-size: 20px;
            padding: 10px;
            width: 100%;
        }
        .invoice-to {
            float: left;
        }
        .invoice-details {
            float: right;
        }
        table {
            clear: both;
            border: 1px solid darkgray;
            border-collapse: collapse;
            margin: auto;
        }
        th {
            background-color: navy;
            color: white;
        }
        td, th {
            border: 1px solid darkgray;
            padding: 5px;
        }
        .numeric-cell {
            text-align: right;
        }
        .clearfix::after {
            content: "";
            clear: both;
            display: table;
        } 
    </style>
</head>
<body>
    <div class="invoice-title">
        Invoice @Model.InvoiceNo
    </div>
    <div class="invoice-head clearfix">
        <div class="invoice-to">
            <strong>@Model.CustomerName</strong><br />
            @Model.CustomerBillingAddress
        </div>
        <div class="invoice-details">
            Invoice no: @Model.InvoiceNo<br />
            Date: @Model.InvoiceDate.ToShortDateString()<br />
            Due date: @Model.DueDate.ToShortDateString()
        </div>
    </div>
    <table>
        <tr>
            <th>Item</th>
            <th>Unit price</th>
            <th>Amount</th>
            <th>Net</th>
            <th>VAT (%)</th>
            <th>Total</th>
        </tr>
        @foreach (var line in Model.Lines)
        {
            <tr>
                <td>@line.LineTitle</td>
                <td class="numeric-cell">@line.UnitPrice.ToString("0.00") EUR</td>
                <td class="numeric-cell">@line.Amount</td>
                <td class="numeric-cell">@line.Net.ToString("0.00") EUR</td>
                <td class="numeric-cell">@line.VatPercent%</td>
                <td class="numeric-cell">@line.Total.ToString("0.00") EUR</td>
            </tr>
        }
        <tr>
            <td colspan="4"></td>
            <td><strong>Total:</strong></td>
            <td><strong>@Model.Total.ToString("0.00") EUR</strong></td>
        </tr>
    </table>
</body>
</html>

That’s it.

Let’s run your project.

URL to access:- https://localhost:44393/Export/Index

Output

Also check, Encrypt And Decrypt File Using Key In .NET 5

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories