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?
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 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: ")); document.Add(new Paragraph($"Date: ")); document.Add(new Paragraph($"Customer Name: ")); document.Add(new Paragraph($"Payment Mode: ")); // 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: ") .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< 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()

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

@ < ViewData["Title"] = "DownloadPDF"; >

Download PDF

Download Invoice
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?

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.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.