Announcement

Create Pdf File using C#

Create Pdf File using C#

C# to Pdf

As mentioned in the post Create XML file in C# .net that often we require to create text file, csv file or excel file for reporting purpose, an important format over internet can't be omitted i.e., pdf format.

pdf is Portable Document Format, a file format to present document independent of application software, hardware and operating system. It is widely used format because of it security and flexibility. Hence, we need to know how to create pdf file in C#? Or how to export HTML table to pdf format? So first we need a dll file
which is itextsharp.dll file. You can download this file from itextsharp.dll.

itextsharp is an open source java library and a .net port used for generating documents and reports based on data from an XML file or database, to convert XML to PDF. It enables developers to enhance their applications with PDF Functionality.

Step 1 :Add a reference to itextsharp.dll file in your project.

Step 2 :Browse the itextsharp.dll file and click OK.
Add Reference to itextsharp.dll file
Add Reference to itextsharp.dll file.

Step 3 :Now create a method that will accept an argument of type DataTable and inside this function create a document as pdfDoc using Document class. This class has 3 constructors:

        3.1 Constructor with No Argument. It will create a document with default settings.
        3.2 Constructor with one Argument. It accepts one argument as pageSize.
        3.3 Constructor with five Arguments that accepts PAgeSize, MarginLeft, MarginRight, MarginTop, and MarginBottom.

Step 4 :Now get the instance of PdfWriter class passing the document object create above and Response object's OutputStream of the HttpContext class as PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);

Step 5 :Open the pdf document created above using Document Class i.e., pdfDoc using Open() method. Than create pdf table using PdfPTable class passing the count of the data table as an argument to it to specify the number of columns for the PDF Table.

Step 6 :Set the Table's total width and lock the width of the table. This is done as:


PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
table.TotalWidth = 500f;
table.SpacingBefore = 10f;
table.LockedWidth = true;


Step 7 :Now, for each row in the data table, create a PdfPCell with the required content and set all the required properties like HorizantalAlignment, VerticalAlignment, Font, Width, Colspan, Rowspan etc.

Step 8 :After setting all the required properties now add the cell to the table object that was created in Step 5.

Step 9 :Repeat steps 7 and 8 util you finish all the cells of the data table that you need to present in you pdf file.

Step 10 :Finally add the table to the pdfDoc, the Document object that was created in Step 1.

Step 11 :Close the document using pdfDoc.Close(); method.

Step 12 :Now, set the ContentType of the Response object to 'application/pdf'. Add the header to it specifying the file name. Now, send all currently buffered output to the client using Response.Flush() mehtod and End the Response object using Response.End().


Here is the complete code:


public void ExportToPdf(DataTable myDataTable)
{
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();

DataTable dt = myDataTable;
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table

PdfPTable table = new PdfPTable(4);
table.TotalWidth = 500f;
table.SpacingBefore = 10f;
table.LockedWidth = true;
foreach (DataRow row in dt.Rows)
{
if (row[1].ToString().Equals("INVOICE"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;
PdfPCell header = new PdfPCell(new Phrase(row[1].ToString(), FontFactory.GetFont("Book Antiqua", 14, Font.BOLD)));
header.Colspan = 4;
header.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(header);
}
else if (row[3].ToString().Contains("Terms"))
{
var p = new Paragraph();
string data = row[3].ToString();
string TnC = data.Substring(0, row[3].ToString().IndexOf("Advance")) + "\n";
string Advance = "\n" + data.Substring(row[3].ToString().IndexOf("Advance"));

Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 10);
Font bookAntiquaBold = FontFactory.GetFont("Book Antiqua", 10, Font.BOLD);
Chunk c1 = new Chunk(TnC, bookAntiqua);
Chunk c2 = new Chunk(Advance, bookAntiquaBold);
Phrase phrase = new Phrase();
phrase.Add(c1);
phrase.Add(c2);
p.Add(phrase);

PdfPCell cellText = new PdfPCell(new Paragraph(p));
cellText.Colspan = 4;
cellText.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cellText);
}
else if (row[0].ToString().Contains("Contact"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;
PdfPCell header = new PdfPCell(new Phrase(row[0].ToString(), FontFactory.GetFont("Book Antiqua", 10)));
header.Colspan = 2;
header.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(header);
}
else if (row[3].ToString().Contains("AGREEMENT"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;

var p = new Paragraph();
string data = row[3].ToString();
string BuyersOrders = data.Substring(0, row[3].ToString().IndexOf("AS")) + "\n";
string AsPerAgreement = "\n" + data.Substring(row[3].ToString().IndexOf("AS"));

Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 10f);
Chunk c1 = new Chunk(BuyersOrders, bookAntiqua);
Chunk c2 = new Chunk(AsPerAgreement, bookAntiqua);
Phrase phrase = new Phrase();
phrase.Add(c1);
phrase.Add(c2);
p.Add(phrase);

PdfPCell cellText = new PdfPCell(new Paragraph(p));
cellText.HorizontalAlignment = Element.ALIGN_LEFT;
cellText.Colspan = 2;
table.AddCell(cellText);
}
else if (row[0].ToString().Contains("MVAT"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;

var p = new Paragraph();
string data = row[0].ToString();
string IECode = "\n" + data.Substring(0, row[0].ToString().IndexOf("Pan")) + "\n";
string PanNo = "\n" + data.Substring(row[0].ToString().IndexOf("Pan"), row[0].ToString().IndexOf("S.T No.") - row[0].ToString().IndexOf("Pan")) + "\n";
string STNo = "\n" + data.Substring(row[0].ToString().IndexOf("S.T No."), row[0].ToString().IndexOf("MVAT") - row[0].ToString().IndexOf("S.T No.")) + "\n";
string MVATNo = "\n" + data.Substring(row[0].ToString().IndexOf("MVAT"), row[0].ToString().IndexOf("For") - row[0].ToString().IndexOf("MVAT"));

Font bookAntiquaCodes = FontFactory.GetFont("Book Antiqua", 11, Font.BOLD);
Chunk IeCode = new Chunk(IECode, bookAntiquaCodes);
Chunk pan = new Chunk(PanNo, bookAntiquaCodes);
Chunk stno = new Chunk(STNo, bookAntiquaCodes);
Chunk mvat = new Chunk(MVATNo, bookAntiquaCodes);
Phrase iecodePhrase = new Phrase(IeCode);
Phrase panPhrase = new Phrase(pan);
Phrase stnoPhrase = new Phrase(stno);
Phrase mvatPhrase = new Phrase(mvat);


p.Add(iecodePhrase);
p.Add(panPhrase);
p.Add(stnoPhrase);
p.Add(mvatPhrase);

string ForB4U = " " + data.Substring(row[0].ToString().IndexOf("For"), row[0].ToString().IndexOf("Declaration") - row[0].ToString().IndexOf("For")) + "\n\n";
Chunk forb4u = new Chunk(ForB4U, bookAntiquaCodes);
Phrase forb4uPhrase = new Phrase(forb4u);
p.Add(forb4uPhrase);

string dec = data.Substring(row[0].ToString().IndexOf("Declaration"), row[0].ToString().IndexOf("Authorised") - row[0].ToString().IndexOf("Declaration"));

string AuthorisedSignatory = "\n " + data.Substring(row[0].ToString().IndexOf("Authorised"));
string decContent = dec.Insert(dec.IndexOf("We"), "\n\n").Insert(dec.IndexOf("goods") + 2, "\n");


Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 8f);
Chunk beginning = new Chunk(decContent, bookAntiqua);
Phrase p1 = new Phrase(beginning);
p.Add(p1);

Chunk authorSign = new Chunk(AuthorisedSignatory, bookAntiquaCodes);
Phrase authorSignPhrase = new Phrase(authorSign);
p.Add(authorSignPhrase);

PdfPCell cellText = new PdfPCell(new Paragraph(p));
cellText.Colspan = 4;
table.AddCell(cellText);

}
else if (row[0].ToString().Contains("words"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;
PdfPCell header = new PdfPCell(new Phrase(row[0].ToString(), FontFactory.GetFont("Book Antiqua", 10, Font.BOLD)));
header.Colspan = 3;
header.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(header);

table.TotalWidth = 500f;
table.LockedWidth = true;
PdfPCell header2 = new PdfPCell(new Phrase(row[3].ToString(), FontFactory.GetFont("Book Antiqua", 11)));
header2.HorizontalAlignment = Element.ALIGN_RIGHT;
table.AddCell(header2);
}
else if (row[0].ToString().Contains("EXPORTERS"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;

var exporterPara = new Paragraph();
string exporterData = row[0].ToString();
string Exporter = exporterData.Substring(0, row[0].ToString().IndexOf(":") + 1) + "\n";
string ExporterAddress = "\n" + exporterData.Substring(row[0].ToString().IndexOf(":") + 1) + "\n\n";

Font fontExporter = FontFactory.GetFont("Book Antiqua", 10f, Font.BOLD);
Chunk exporterChunk1 = new Chunk(Exporter, fontExporter);
Chunk exporterChunk2 = new Chunk(ExporterAddress, fontExporter);
Phrase exporterPhrase = new Phrase();
exporterPhrase.Add(exporterChunk1);
exporterPhrase.Add(exporterChunk2);
exporterPara.Add(exporterPhrase);

PdfPCell exporterCellText = new PdfPCell(new Paragraph(exporterPara));
exporterCellText.HorizontalAlignment = Element.ALIGN_LEFT;
exporterCellText.Colspan = 2;
exporterCellText.Rowspan = 2;
table.AddCell(exporterCellText);


var p = new Paragraph();
string data = row[3].ToString();
string InvoiceNo = data.Substring(0, row[3].ToString().IndexOf("DATE")) + "\n";
string Date = "\n" + data.Substring(row[3].ToString().IndexOf("DATE")) + "\n\n";

Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 10f, Font.BOLD);
Chunk c1 = new Chunk(InvoiceNo, bookAntiqua);
Chunk c2 = new Chunk(Date, bookAntiqua);
Phrase phrase = new Phrase();
phrase.Add(c1);
phrase.Add(c2);
p.Add(phrase);

PdfPCell cellText = new PdfPCell(new Paragraph(p));
cellText.HorizontalAlignment = Element.ALIGN_LEFT;
cellText.Colspan = 2;
table.AddCell(cellText);

}
else if (row[0].ToString().Contains("CONSIGNEE"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;

var p = new Paragraph();
string data = row[0].ToString();
string Consignee = data.Substring(0, 9) + "\n";
string ConsigneeName = "\n" + data.Substring(9, row[0].ToString().IndexOf("Tel") - 9);
string Tel = "\n" + data.Substring(row[0].ToString().IndexOf("Tel"), row[0].ToString().IndexOf("Email") - row[0].ToString().IndexOf("Tel"));
string Email = "\n" + data.Substring(row[0].ToString().IndexOf("Email"));

Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 10f);
Font fontConsignee = FontFactory.GetFont("Book Antiqua", 10f, Font.BOLD);
Chunk c1 = new Chunk(Consignee, fontConsignee);
Chunk c2 = new Chunk(ConsigneeName, fontConsignee);
Chunk c3 = new Chunk(Tel, bookAntiqua);
Chunk c4 = new Chunk(Email, bookAntiqua);
Phrase phrase = new Phrase();
phrase.Add(c1);
phrase.Add(c2);
phrase.Add(c3);
phrase.Add(c4);
p.Add(phrase);

PdfPCell cellText = new PdfPCell(new Paragraph(p));
cellText.HorizontalAlignment = Element.ALIGN_LEFT;
cellText.Colspan = 2;
table.AddCell(cellText);


var bankDetails = new Paragraph();
string bankData = row[3].ToString();
string BankDetailsHeader = bankData.Substring(0, row[3].ToString().IndexOf("Company")) + "\n";
string CompanyName = "\n" + bankData.Substring(row[3].ToString().IndexOf("Company"), row[3].ToString().IndexOf("Bank Name") - row[3].ToString().IndexOf("Company"));
string BankName = "\n" + bankData.Substring(row[3].ToString().IndexOf("Bank Name"), row[3].ToString().IndexOf("Branch Name") - row[3].ToString().IndexOf("Bank Name"));
string BranchName = "\n" + bankData.Substring(row[3].ToString().IndexOf("Branch Name"), row[3].ToString().IndexOf("Account") - row[3].ToString().IndexOf("Branch Name"));
string Account = "\n" + bankData.Substring(row[3].ToString().IndexOf("Account"), row[3].ToString().IndexOf("Swift") - row[3].ToString().IndexOf("Account"));
string SwiftCode = "\n" + bankData.Substring(row[3].ToString().IndexOf("Swift"));

Chunk b1 = new Chunk(BankDetailsHeader, fontConsignee);
Chunk b2 = new Chunk(CompanyName, fontConsignee);
Chunk b3 = new Chunk(BankName, fontConsignee);
Chunk b4 = new Chunk(BranchName, bookAntiqua);
Chunk b5 = new Chunk(Account, bookAntiqua);
Chunk b6 = new Chunk(SwiftCode, bookAntiqua);
Phrase bankPhrase = new Phrase();
bankPhrase.Add(b1);
bankPhrase.Add(b2);
bankPhrase.Add(b3);
bankPhrase.Add(b4);
bankPhrase.Add(b5);
bankPhrase.Add(b6);
bankDetails.Add(bankPhrase);

PdfPCell bankCell = new PdfPCell(new Paragraph(bankDetails));
bankCell.HorizontalAlignment = Element.ALIGN_LEFT;
bankCell.Colspan = 2;
bankCell.Rowspan = 2;
table.AddCell(bankCell);
}
else if (row[0].ToString().Contains("Goods"))
{
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 205f, 70f, 90f, 135f };
table.SetWidths(widths);
for (int i = 0; i < dt.Columns.Count; i++)
{
if (row[i].ToString().Contains("AMOUNT"))
{
var p = new Paragraph();
string data = row[i].ToString();
string Amount = data.Substring(0,row[i].ToString().IndexOf("T") + 1) + "\n";
string Currency = data.Substring(row[i].ToString().IndexOf("T") + 1);
Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 10f);
Chunk c1 = new Chunk(Amount, bookAntiqua);
Chunk c2 = new Chunk(Currency, bookAntiqua);
Phrase phrase = new Phrase();
phrase.Add(c1);
phrase.Add(c2);
p.Add(phrase);
PdfPCell cellText = new PdfPCell(new Paragraph(p)); cellText.HorizontalAlignment = Element.ALIGN_CENTER; table.AddCell(cellText);
}
else
{
PdfPCell header = new PdfPCell(new Phrase(row[i].ToString(), FontFactory.GetFont("Book Antiqua", 10)));
header.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(header);
}
}
}
else if (Convert.ToInt32(row[3].ToString()) > 0)
{
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 205f, 70f, 90f, 135f };
table.SetWidths(widths);
for (int i = 0; i < dt.Columns.Count; i++) { table.TotalWidth = 500f;
table.LockedWidth = true;
if (row[i].ToString().Contains("Film")) 
{
var p = new Paragraph();
string data = row[i].ToString();
string Film = data.Substring(0, row[i].ToString().IndexOf("Description")) + "\n";
string Description = "\n" + data.Substring(row[i].ToString().IndexOf("Description"), row[0].ToString().IndexOf("Territory") - row[0].ToString().IndexOf("Description")) + "\n";
string Territory = "\n" + data.Substring(row[i].ToString().IndexOf("Territory")) + "\n\n";
Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 10, Font.BOLD);
Chunk c1 = new Chunk(Film, bookAntiqua);
Chunk c2 = new Chunk(Description, bookAntiqua);
Chunk c3 = new Chunk(Territory, bookAntiqua);
Phrase phrase = new Phrase(); phrase.Add(c1);
phrase.Add(c2); phrase.Add(c3); p.Add(phrase);
PdfPCell cellText = new PdfPCell(new Paragraph(p));
table.AddCell(cellText);
}
else if (row[i].ToString().Equals(""))
{
 PdfPCell header = new PdfPCell(new Phrase(row[i].ToString(), FontFactory.GetFont("Book Antiqua", 8)));
header.HorizontalAlignment = Element.ALIGN_MIDDLE;
table.AddCell(header); 
}
else
{
var p = new Paragraph(); 
string Rupees = "\n" + row[i].ToString();
Font bookAntiqua = FontFactory.GetFont("Book Antiqua", 10f);
Chunk c1 = new Chunk(Rupees, bookAntiqua);
Phrase phrase = new Phrase(); phrase.Add(c1);
p.Add(phrase);
PdfPCell cellText = new PdfPCell(new Paragraph(p));
cellText.HorizontalAlignment = Element.ALIGN_RIGHT;
cellText.VerticalAlignment = Element.ALIGN_MIDDLE;
table.AddCell(cellText);
}
}
}
else
{
table.TotalWidth = 500f;
table.LockedWidth = true; 
float[] widths = new float[] { 205f, 70f, 90f, 135f };
table.SetWidths(widths);
for (int i = 0; i < dt.Columns.Count; i++)
{
PdfPCell header = new PdfPCell(new Phrase(row[i].ToString(), FontFactory.GetFont("Book Antiqua", 8)));
header.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(header);
}
}
}
pdfDoc.Add(table);// add pdf table to the document
}
pdfDoc.Close();
Response.ContentType = "application/pdf"; 
Response.AddHeader("content-disposition", "attachment; filename= Invoice.pdf");
Response.Flush();
Response.End();
}
catch (DocumentException de) 
{
System.Web.HttpContext.Current.Response.Write(de.Message);
}
catch (IOException ioEx)
{
System.Web.HttpContext.Current.Response.Write(ioEx.Message);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}


CONCLUSION


The above code shows how to create a pdf file using C# with the help of itextsharp.dll. Any one can change the above code to suit his/her own requirement. The code was implemented in a web application and we were able to create and download pdf report successfully.

PDF File Creation
PDF File Creation

No comments: