WPF – Create PDF document using iText7 Library

  • by

In this post we will see how we can a PDF file in WPF C# form application using iText7 library. We will create a simple and sample invoice order PDF document using this library. The invoice will contain order details, total money value, seller information and the customer details. For this you are required to install iText7 library using nuget package manager in your WPF application.

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 project add iText7 nuget package.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

Also create a folder named files in your project.folder-structure-wpf-pdf-creation-itext7

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

Orders.cs:

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

Open the MainWindow.xaml form and edit it as below:

MainWindow.xaml:

<Window x:Class="MyWPFApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyWPFApp"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">

<StackPanel Orientation="Vertical">
<Button Name="btnCreatePDF" Content="Create PDF Document" Click="BtnCreatePDF_Click" Margin="5,20,5,5" Width="200" />
</StackPanel>

</Window>

This form only contains a single button to create a PDF document itself. Simple. Now edit the MainWindow.xaml.cs code file as below:
MainWindow.xaml.cs:

using iText.IO.Font;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Pdfa;
using MyWPFApp.Models;
using System;
using System.Collections.Generic;
using System.IO;

namespace MyWPFApp
{
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}

private void BtnCreatePDF_Click(object sender, System.Windows.RoutedEventArgs 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 = @"D:\WPF\MyWPFApp\MyWPFApp\PDFResources\sRGB_CS_profile.icm";
string fontFile = @"D:\WPF\MyWPFApp\MyWPFApp\PDFResources\FreeSans.ttf";
string fileName = @"D:\WPF\MyWPFApp\MyWPFApp\files\sample" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".pdf";

PdfADocument pdf = new PdfADocument(
new PdfWriter(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("WPF C# CREATE PDF DOCUMENT USING 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.Diagnostics.Process.Start(fileName);
}
catch (Exception ex)
{

}

}
}
}

I have also copied some part of the code from iText7 official documentation. You can now run this WPF app and click on the button to create the PDF invoice document. The pdf file will be created inside the files folder created earlier and also give windows command to open the pdf file in the default app. This is done by:

System.Diagnostics.Process.Start(fileName);

Output:

wpf-how-to-create-pdf-document-sample-itext7-library

DOWNLOAD SOURCE CODE

Also see:

Using customer fonts in WPF application

Create Login form and integrate with SQL Database in WPF forms.

WPF MVVM DataGrid Bind from SQL Database

WPF MVVM Listbox SelectionChanged Get SelectedItem