In this article, we will see how to generate PDF using an Open Source Library provided by Itextsharp
Introduction
Hello Team,
In real world programming we come to a stage where we need to
create PDF from the data we have.
In this article we are going to see how to generate the PDF using
ITextSharp library.
This library is a part of an opensource project available on
www.sourceforge.net.
Objective
Generating the PDF's on the FLY.....
Using the code
Let us start the Code part now.
Create a New Project in Visual Studio -> Select Windows
Application.
Drag a Button and Textbox on the Windows from
Set the textbox to Multi-line property to true.
Now we will have to download the Itextsharp library from the below
link
http://sourceforge.net/projects/itextsharp/
Once you download the Zip File just extract it to a folder in that
you will get multiple zip files.
From the group of multiple zip files extract the Zip File which is
named as itextsharp-dll-core check the Image

Once you extract the Zip you will get a Itextsharp.dll and an xml
file.Check the image

Now go to the project and Right Click on reference and
the Itextsharp.dll to the reference.
We will also have to add name space using system.IO and
System.Diagnostics as well for creating the PDF.
and write the following code on the button click event.
// Code Behind
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace PDF_Generation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPDF_Click(object sender, EventArgs e)
{
try
{
string path = Application.StartupPath;
Document pdfdoc = new Document(PageSize.A4); // Setting the page size for the PDF
PdfWriter.GetInstance(pdfdoc, new FileStream(path + "/Sample.pdf", FileMode.Create)); //Using the PDF Writer class to generate the PDF
pdfdoc.Open(); // Opening the PDF to write the data from the textbox
pdfdoc.Add(new Paragraph(xtxtData.Text)); // Adding the Text to the PDF
pdfdoc.Close();
MessageBox.Show("PDF Generation Successfull");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Output Screen

Adding Text Screen


Checking the PDF in the Debug Folder
Checking the data in the PDF
Reference
http://sourceforge.net/projects/itextsharp/