How to Generate PDF in ASP.NET Core MVC

How to Generate PDF in ASP.NET Core MVC

In this article, I will discuss How to Generate PDFs in ASP.NET Core MVC Application with Examples. Please read our previous article discussing How to Import Excel Data to a Database in an ASP.NET Core MVC Application with Examples. Let’s continue with the application we worked on in previous articles.

Generate PDF in ASP.NET Core MVC

Several libraries are available for generating PDFs in ASP.NET Core, such as iText, iTextSharp, DinkToPdf, and Rotativa.AspNetCore. Each has its own set of features and ways of working. 

What is a PDF?

PDF stands for “Portable Document Format.” It is a file format used to present documents independently of application software, hardware, and operating systems. Here are some key characteristics and uses of PDF:

  • Multi-Dimensional: PDFs can contain text, images, hyperlinks, embedded fonts, video, and more.
  • Consistent Format: One of the primary benefits of a PDF is that it maintains the document’s formatting regardless of what device or software it is viewed on. This means that a PDF will look the same on any device.
  • Widely Used: It’s a standard format for documents in many fields because it maintains consistency across different platforms.
  • Security: PDFs can be encrypted and digitally signed, making them a secure option for sensitive documents. They also support watermarks and passwords for added protection.
  • Compression: PDFs support efficient data compression, making them relatively smaller than other formats with similar content.
  • Standardization: The International Organization for Standardization (ISO) standardizes the format. PDF/A, for instance, is a version of PDF meant for archiving and long-term preservation of electronic documents.
  • Versatility: PDFs are used in various applications, from business documents, legal forms, research papers, and eBooks to application forms and more.
  • Creation and Editing: Originally created by Adobe Systems, PDFs can now be created and edited by many different software tools, including Adobe Acrobat, Microsoft Office, and various other PDF editing and creation tools.
Generate PDF in ASP.NET Core MVC Using iText Library.

Let us see an example of how to generate a PDF in ASP.NET Core MVC using iTextSharp. Here, we are going to create an invoice PDF using iText.

Install iTextS Package:

First, you need to install the iText library. You can do this through the NuGet Package Manager. In Visual Studio, go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution. Search for iText7 and install it as shown in the below image.

Install iTextS Package

Create Models

Create a model to represent your invoice data. So, create a class file named InvoiceModel.cs and then copy and paste the following code.

namespace FileUploadInMVC.Models
{
    public class Invoice
    {
        public string InvoiceNumber { get; set; }
        public DateTime Date { get; set; }
        public string CustomerName { get; set; }
        public List<InvoiceItem> Items { get; set; }
        public decimal TotalAmount { get; set; }
        public string PaymentMode { get; set; }
    }

    public class InvoiceItem
    {
        public string ItemName { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalPrice => Quantity * UnitPrice;
    }
}
Create a PDF Generation Service

Create a service class that will handle PDF generation. So, add a class file named PDFService.cs and then copy and paste the following code. The following code is self-explained, so please go through the comment line for a better understanding.

using iText.Kernel.Pdf;
using iText.Layout.Properties;
using iText.Layout;
using iText.Layout.Element;
using FileUploadInMVC.Models;

namespace FileUploadInMVC.Models
{
    public class PDFService
    {
        public byte[] GeneratePDF(Invoice invoice)
        {
            //Define your memory stream which will temporarily hold the PDF
            using (MemoryStream stream = new MemoryStream())
            {
                //Initialize PDF writer
                PdfWriter writer = new PdfWriter(stream);

                //Initialize PDF document
                PdfDocument pdf = new PdfDocument(writer);

                // Initialize document
                Document document = new Document(pdf);

                // Add content to the document
                // Header
                document.Add(new Paragraph("Invoice")
                    .SetTextAlignment(TextAlignment.CENTER)
                    .SetFontSize(20));

                // Invoice data
                document.Add(new Paragraph($"Invoice Number: {invoice.InvoiceNumber}"));
                document.Add(new Paragraph($"Date: {invoice.Date.ToShortDateString()}"));
                document.Add(new Paragraph($"Customer Name: {invoice.CustomerName}"));
                document.Add(new Paragraph($"Payment Mode: {invoice.PaymentMode}"));

                // Table for invoice items
                Table table = new Table(new float[] { 3, 1, 1, 1 });
                table.SetWidth(UnitValue.CreatePercentValue(100));
                table.AddHeaderCell("Iten Name");
                table.AddHeaderCell("Quantity");
                table.AddHeaderCell("Unit Price");
                table.AddHeaderCell("Total");

                foreach (var item in invoice.Items)
                {
                    table.AddCell(new Cell().Add(new Paragraph(item.ItemName)));
                    table.AddCell(new Cell().Add(new Paragraph(item.Quantity.ToString())));
                    table.AddCell(new Cell().Add(new Paragraph(item.UnitPrice.ToString("C"))));
                    table.AddCell(new Cell().Add(new Paragraph(item.TotalPrice.ToString("C"))));
                }

                //Add the Table to the PDF Document
                document.Add(table);

                // Total Amount
                document.Add(new Paragraph($"Total Amount: {invoice.TotalAmount.ToString("C")}")
                    .SetTextAlignment(TextAlignment.RIGHT));

                // Close the Document
                document.Close();

                return stream.ToArray();
            }
        }
    }
} 
Create the PDF Generation Action Method

Now, we need to call the PDF Generation service in our controller to handle a route that generates the PDF. Please add the following method within the FileUpload Controller. This action method is going to generate and return the PDF.

//Generate Invoice PDF using iText
public IActionResult GenerateInvoicePDF()
{
    // Sample invoice data
    // Here, we have hardcoded the data,
    // In Real-time you will get the data from the database
    var invoice = new Invoice
    {
        InvoiceNumber = "INV-DOTNET-1001",
        Date = DateTime.Now,
        CustomerName = "Pranaya Rout",
        Items = new List<InvoiceItem>
                {
                    new InvoiceItem { ItemName = "Item 1", Quantity = 2, UnitPrice = 15.0m },
                    new InvoiceItem { ItemName = "Item 2", Quantity = 3, UnitPrice = 10.0m },
                    new InvoiceItem { ItemName = "Item 3", Quantity = 1, UnitPrice = 35.0m }
                },
        PaymentMode = "COD"
    };

    //Set the Total Amount
    invoice.TotalAmount = invoice.Items.Sum(x => x.TotalPrice);

    //Create an Instance of PDFService
    PDFService pdfService = new PDFService();

    //Call the GeneratePDF method passing the Invoice Data
    var pdfFile = pdfService.GeneratePDF(invoice);

    //Return the PDF File
    return File(pdfFile, "application/pdf", "Invoice.pdf");
}
Create a View to Trigger PDF Generation

You can create a simple view with a link or a button to trigger the PDF generation. So, let us first add the following action method within the FileUpload controller.

public IActionResult DownloadPDF()
{
    return View();
}

Next, add a view named DownloadPDF.cshtml within the Views/FileUpload folder and then copy and paste the following code.

@{
    ViewData["Title"] = "DownloadPDF";
}

<h1>Download PDF</h1>
<a href="@Url.Action("GenerateInvoicePDF", "FileUpload")">Download Invoice</a>
Run and Test

Run your application and navigate to the URL FileUpload/DownloadPDF, which should open the following page. Clicking on the Download Invoice link, as shown in the image below, triggers the PDF generation and download.

How to Generate a PDF in the ASP.NET Core MVC Application

Once you click on the Download Invoice link, it will generate and download the Invoice as shown in the below image:

How to Generate a PDF in the ASP.NET Core MVC Application with Examples

Why PDF in ASP.NET Core MVC?
  • Consistent Formatting: PDFs maintain consistent formatting regardless of the device or PDF reader used. This consistency is crucial for official documents where layout, spacing, and fonts need to remain unchanged.
  • Client-Side Independence: Generating a PDF server-side ensures that the document’s appearance is not dependent on client-side factors like browser type, installed fonts, or screen resolution.
  • Security and Read-Only Nature: PDFs can be made secure and read-only. This is important for sensitive documents as it prevents unauthorized editing.
  • Offline Accessibility: PDFs can be easily saved, emailed, and accessed offline, making them convenient for users who need to access documents without an internet connection.
  • Legal and Compliance Requirements: In many industries, documents need to be stored or transmitted in a widely recognized and accepted format. PDF is a universally accepted format in many legal, educational, and corporate environments.
  • Integration with Other Systems: PDFs are often used in integrations with other systems (like email, document management systems, or cloud storage) because of their wide acceptance and compatibility.
  • Print-Ready Format: PDF is a preferred format for documents that need to be printed, such as legal contracts or tickets, as it preserves the layout and formatting when printed.

In the next article, I will discuss How to Generate Password Protected PDF in ASP.NET Core MVC Application with examples. In this article, I try to explain How to Generate a PDF in the ASP.NET Core MVC Application with Examples. I hope you enjoy this article on How to Generate a PDF in the ASP.NET Core MVC.

Leave a Reply

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