Site icon ParallelCodes

ASP.NET C# – Create PDF Invoice using iText7 Library

ASP.NET Creating PDF Invoice document using iText7 library:

Today we will create a pdf invoice document (a sample invoice pdf file) in ASP.NET. For this you will require iText7 library to be installed in your project. PDF will contain seller information, customer info and product details along with prices and its quantity.

About iText7 library:

iText7 is a library for creating PDF files in Java and .NET. It was developed by Bruno Lowagie. It was initially published as an open-sourced library under the Mozilla Public License or the GNU Library General Public License open source licenses. As of today, iText7 core is an open source library.

Install iText7 nuget package:

In your ASP.NET project add iText7 nuget package.

Create a folder named PDFResources and add following resources to it:

FreeSans.ttf, FreeSansBold.ttf (both are true type font face file), sRGB_CS_profile.icm (this is a color profile file from official documentation), kid.jpg (you can use any image you like).

This files are available on iText official tutorial document or you can also directly download source code from below link: DOWNLOAD SOURCE CODE

Create a folder named Models and add a class with name Orders.cs

Orders.cs:

namespace AspTutorial.Models
{
public class Orders
{
public int productId { get; set; }
public string product { get; set; }
public int qty { get; set; }
public double price { get; set; }
}
}

Edit your Default.aspx page as below:

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AspTutorial.Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET PDF Invoice Sample</title>
<style>

</style>
</head>
<body style="font-family:Arial, Helvetica, sans-serif">
<form id="form1" runat="server">
<div>
<asp:Button ID="btnCreatePDF" runat="server" OnClick="btnCreatePDF_Click" Text="Create PDF"/>

</div>
</form>
</body>
</html>

This form only contains one button to create PDF file:

And edit the code as below:

Default.asxp.cs:

using AspTutorial.Models;
using iText.IO.Font;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Pdfa;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI;

namespace AspTutorial
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnCreatePDF_Click(object sender, EventArgs e)
{
try
{
List<Orders> orders = new List<Orders>();

orders.Add(new Orders { productId = 1045, product = "Acer Aspire E575", price = 45999, qty = 1 });
orders.Add(new Orders { productId = 7561, product = "Logitech", price = 799, qty = 2 });
orders.Add(new Orders { productId = 5785, product = "Logitech MK270r", price = 1599, qty = 1 });

string filePath = Server.MapPath("PDFResources/sRGB_CS_profile.icm");
string fontFile = Server.MapPath("PDFResources/FreeSans.ttf");
string fileName = "sample" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".pdf";
PdfADocument pdf = new PdfADocument(new PdfWriter(Server.MapPath(fileName)), PdfAConformanceLevel.PDF_A_1B,
new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1",
new FileStream(filePath, FileMode.Open, FileAccess.Read)));

PdfFont font = PdfFontFactory.CreateFont(fontFile, PdfEncodings.WINANSI,
PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);
Document document = new Document(pdf);

document.SetFont(font);

Paragraph header = new Paragraph("ORDER DETAIL").SetTextAlignment(TextAlignment.CENTER).SetFontSize(20);
document.Add(header);

Paragraph subheader = new Paragraph("PDF CREATED USING ASP.NET C# WITH iTExT7 LIBRARY").SetTextAlignment(TextAlignment.CENTER).SetFontSize(10);
document.Add(subheader);

LineSeparator ls = new LineSeparator(new SolidLine());
document.Add(ls);

Paragraph sellerHeader = new Paragraph("Sold by:").SetBold().SetTextAlignment(TextAlignment.LEFT);
Paragraph sellerDetail = new Paragraph("Seller Company").SetTextAlignment(TextAlignment.LEFT);
Paragraph sellerAddress = new Paragraph("Mumbai, Maharashtra India").SetTextAlignment(TextAlignment.LEFT);
Paragraph sellerContact = new Paragraph("+91 1000000000").SetTextAlignment(TextAlignment.LEFT);

document.Add(sellerHeader);
document.Add(sellerDetail);
document.Add(sellerAddress);
document.Add(sellerContact);

Paragraph customerHeader = new Paragraph("Customer details:").SetBold().SetTextAlignment(TextAlignment.RIGHT);
Paragraph customerDetail = new Paragraph("Customer ABC").SetTextAlignment(TextAlignment.RIGHT);
Paragraph customerAddress1 = new Paragraph("R783, Rose Apartments, Santacruz (E)").SetTextAlignment(TextAlignment.RIGHT);
Paragraph customerAddress2 = new Paragraph("Mumbai 400054, Maharashtra India").SetTextAlignment(TextAlignment.RIGHT);

Paragraph customerContact = new Paragraph("+91 0000000000").SetTextAlignment(TextAlignment.RIGHT);

document.Add(customerHeader);
document.Add(customerDetail);
document.Add(customerAddress1);
document.Add(customerAddress2);
document.Add(customerContact);

Paragraph orderNo = new Paragraph("Order No:15484659").SetBold().SetTextAlignment(TextAlignment.LEFT);
Paragraph invoiceNo = new Paragraph("Invoice No:MH-MU-1077").SetTextAlignment(TextAlignment.LEFT);
Paragraph invoiceTimestamp = new Paragraph("Date: 30/05/2021 04:25:37 PM").SetTextAlignment(TextAlignment.LEFT);

document.Add(orderNo);
document.Add(invoiceNo);
document.Add(invoiceTimestamp);

Table table = new Table(5, true);

table.SetFontSize(9);
Cell headerProductId = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Code"));
Cell headerProduct = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Product"));
Cell headerProductPrice = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Price"));
Cell headerProductQty = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Qty"));
Cell headerTotal = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Total"));

table.AddCell(headerProductId);
table.AddCell(headerProduct);
table.AddCell(headerProductPrice);
table.AddCell(headerProductQty);
table.AddCell(headerTotal);

double grandTotalVal = 0;
foreach (Orders c in orders)
{
Cell productid = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.productId.ToString()));
Cell product = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.product));
Cell price = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.price.ToString()));
Cell qty = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.qty.ToString()));
var value = c.price * c.qty;
Cell total = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(value.ToString()));

grandTotalVal += value;
table.AddCell(productid);
table.AddCell(product);
table.AddCell(price);
table.AddCell(qty);
table.AddCell(total);
}

Cell grandTotalHeader = new Cell(1, 4).SetTextAlignment(TextAlignment.RIGHT).Add(new Paragraph("Total: "));
Cell grandTotal = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(" "+grandTotalVal.ToString()));

table.AddCell(grandTotalHeader);
table.AddCell(grandTotal);

document.Add(table);
table.Flush();
table.Complete();
document.Close();

System.Threading.Thread.Sleep(1000);
var httpContext = HttpContext.Current;
httpContext.Response.Clear();
httpContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
httpContext.Response.BinaryWrite(GetFileAsByteArray(Server.MapPath(fileName)));
httpContext.Response.Flush();
httpContext.Response.SuppressContent = false;
httpContext.ApplicationInstance.CompleteRequest();

}
catch (Exception ex)
{

}
}

byte[] GetFileAsByteArray(string fileName)

{
try
{
FileStream fs;
fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
return buffer;
}
catch(Exception ex)
{
return null;
}

}
}
}

The code is self explanatory. I have also copied some part of the code from iText7 official documentation. Now run the project and open Default.aspx form, press on create PDF button. A sample invoice pdf file will be created in your project root folder which will be like below the image.

Output:

DOWNLOAD SOURCE CODE

Also see:

ASP.NET – Uploading multiple files using FileUpload control

ASP.NET – Create and Write Text to file

ASP.NET – Insert data using SQL Stored Procedures

Create ASP.NET Login page with SQL Database

 


Exit mobile version