Thursday 29 December 2011

Pdf in Asp.net using iTextSharp(Gridview to Pdf)

Most of the computer users(Clients) are likely to have used PDF Documents. This tutorial is based on creating pdfs in asp.net(C#)





1.0 Introduction:
Most of the computer users(Clients) are likely to have used PDF Documents. This tutorial is based on creating pdfs in asp.net(C#)

2.0 Using the Code
PdfWriter.GetInstance(doc, new FileStream("c:/pdf1.pdf",FileMode.Create));
3.0 Steps to fallow
3.1 Step 1:
Create an instance of the iTextSharp.text.Document by writing code
iTextSharp.text.Document doc = new iTextSharp.text.Document();
3.2 Step 2:
Create a writer that listen the document you have created and write it to your Stream.
PdfWriter.GetInstance(doc, new FileStream("c:/pdf1.pdf", FileMode.Create));
3.3 Step 3:
Open the Document so that you can write your data to it.
doc.Open();
//you can add
Authors, header, subject to your pdf by methods
//Not recommended

doc.AddAuthor("Bill");
doc.AddSubject("Billings");
doc.AddHeader("BY jay", "BigInt");
3.4 Step 4:
Add Content to the document.


doc.Add(new Paragraph("Hello this is my first pdf");

3.5 Step 5:
Close the document.
doc.Close();


3.6 Now result is stored at the location you specified..check it.



4.0 Classes and methods provided by iTextSharp

4.1 iTextSharp.text.Document.
public Document();
public Document(Rectangle Size);
public Document(Rectangle Size,int Left,int Right,int Top, int Bottom);
Size object sets the Pagesize of Pdf Document
You can create your Rectangle object with certain Borders, Backgroundcolor,
Rectangle Size = new Rectangle(144,720);
Size.BackgroundColor = new Color(123, 12, 210);
Document document = new Document(Size);
4.2 PdfWriter
Once the document object is created, we need to create PdfWriter object
PdfWriter.GetInstance(doc, new FileStream("c:/pdf1.pdf", FileMode.Create));
4.3. Before writing actual data, you might wish to add some metadata like author, title, subject. Document has few methods to add medata are as fallows.

doc.AddAuthor("Bill");
doc.AddSubject("Billings");
doc.AddHeader("BY jay", "BigInt");
doc.AddCreationDate();
doc.AddCreator("name");
doc.AddProducer();
doc.AddKeywords("Keywords");
4.4. Adding Watermark to report.
Watermark watermark = new Watermark(Image.getInstance("image.jpg"),
400, 600);


4.5. Cell.
Cell can be add by creating a object of Cell class and add to document using add() method of document object



Cell cell = new Cell(new Phrase("BigInt Technologies.. ", FontFactory.GetFont(FontFactory.HELVETICA_BOLD,
24)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.Colspan = 3;
cell.Border = 1;
cell.BackgroundColor =
iTextSharp.text.Color.LIGHT_GRAY; //System.Drawing.Color.Silver;
not work
tableLayout.AddCell(cell);

Another merhod to add cell is
Document.AddCell("Cell Value");

5.0 Examples

5.1 Example which shows a simple pdf with Rectangle and cell values as shown in Figure 1.0
public void ExportSimplePdf()
{
iTextSharp.text.Document doc = new iTextSharp.text.Document();
PdfWriter.GetInstance(doc, new FileStream("c:/pdf1.pdf", FileMode.Create));
doc.AddAuthor("Bill");
doc.AddSubject("Billings");
doc.AddHeader("BY jay", "BigInt");
doc.Open();

iTextSharp.text.Table tableLayout = new iTextSharp.text.Table(3);
float[] headers = { 10, 70, 40 };
tableLayout.Widths = headers;
tableLayout.WidthPercentage = 100;
Cell cell = new Cell(new Phrase("BigInt Technologies.. ", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 24)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.Colspan = 3;
cell.Border = 1;
cell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY; //System.Drawing.Color.Silver; not work
tableLayout.AddCell(cell);
tableLayout.DefaultColspan = 3;
StringBuilder strInfo = new StringBuilder();
strInfo.Append(" ID Name : Jayant Bramhankar");
strInfo.Append(Environment.NewLine);
strInfo.Append(" Phone : 9923748199");
strInfo.Append(Environment.NewLine);
strInfo.Append(" Adress : Nagpure");
strInfo.Append(Environment.NewLine);
strInfo.Append(" Date of Birth : 14/4/1986 Date: ");
strInfo.Append(DateTime.Now.ToShortDateString());
strInfo.Append(Environment.NewLine);
strInfo.Append(" ");
tableLayout.AddCell(strInfo.ToString());
tableLayout.DefaultColspan = 1;
tableLayout.AddCell("Sr.No");
Cell cInc = new Cell(new Phrase("Incentive Types", FontFactory.GetFont(FontFactory.HELVETICA, 12)));
cInc.HorizontalAlignment = Element.ALIGN_CENTER;
cInc.VerticalAlignment = Element.ALIGN_MIDDLE;
tableLayout.AddCell(cInc);
// another method to add cell is
// tableLayout.AddCell("Incentive Types");
tableLayout.AddCell("Amount");
tableLayout.AddCell("2");
tableLayout.AddCell("Silver Zone Incentive");
tableLayout.AddCell("2000");
tableLayout.AddCell("3");
tableLayout.AddCell("Golden Zone Incentive");
tableLayout.AddCell("3000");
tableLayout.AddCell("4");
tableLayout.AddCell("Diamond Incentive");
tableLayout.AddCell("4000");
// doc.Add(new Paragraph("Hello World"));
doc.Add(tableLayout);
doc.Close();
}


5.2 Example which shows exporting data to grid and grid to Pdf



protected void Test2_Click(object sender, EventArgs e)
{
// data to gridview from database
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\Desktop\pdf blog\mlm\App_Data\TestPdf.mdf;Integrated Security=True;User Instance=True");
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee", connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
da.Fill(data);
gridDataToExport.DataSource = data.Tables[0];
gridDataToExport.DataBind();
Button2.Visible = true;
}
catch (SqlException ex) { Response.WriteFile(ex.Message); }
}
protected void Button2_Click(object sender, EventArgs e)
{
iTextSharp.text.Document doc = new iTextSharp.text.Document();
PdfWriter.GetInstance(doc, new FileStream("c:/pdf2.pdf", FileMode.Create));
doc.AddAuthor("Bill");
doc.AddSubject("Billings");
doc.AddHeader("BY jay", "BigInt");
doc.Open();
doc.Add(ExportGridToPdf());
doc.Close();
}
public PdfPTable ExportGridToPdf()
{
iTextSharp.text.pdf.PdfPTable tableLayout = new iTextSharp.text.pdf.PdfPTable(4);
float[] headers = { 10, 50, 40, 40 };
tableLayout.SetWidths(headers);
tableLayout.WidthPercentage = 100;
//Create header
PdfPCell cellSr = new PdfPCell(new Phrase("Sr. No ", new Font(Font.HELVETICA, 12, 1, Color.BLUE)));
PdfPCell cellName = new PdfPCell(new Phrase("Name ", new Font(Font.HELVETICA, 12, 1, Color.BLUE)));
PdfPCell cellQua = new PdfPCell(new Phrase("Qualifiaction ", new Font(Font.HELVETICA, 12, 1, Color.BLUE)));
PdfPCell cellOcc = new PdfPCell(new Phrase("Occupation ", new Font(Font.HELVETICA, 12, 1, Color.BLUE)));
//add headers to report
tableLayout.AddCell(cellSr);
tableLayout.AddCell(cellName);
tableLayout.AddCell(cellQua);
tableLayout.AddCell(cellOcc);
tableLayout.DefaultCell.BorderWidth = 1;
try{

int index=1;
foreach(GridViewRow row in gridDataToExport.Rows)
{
if (index % 2 == 0)
{
tableLayout.DefaultCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY;
}
else{tableLayout.DefaultCell.BackgroundColor = iTextSharp.text.Color.WHITE;}
tableLayout.AddCell(row.Cells[0].Text);
tableLayout.AddCell(row.Cells[1].Text);
tableLayout.AddCell(row.Cells[2].Text);
tableLayout.AddCell(row.Cells[3].Text);
index++;
}
return tableLayout;
}
catch (SqlException ex)
{
Response.Write(ex.Message);
return tableLayout;
}

}http://www.assoc-amazon.com/e/ir?t=csharpingsall-20&l=bil&camp=213689&creative=392969&o=1&a=1590598849http://www.assoc-amazon.com/e/ir?t=csharpingsall-20&l=bil&camp=213689&creative=392969&o=1&a=1590599543

6.0 Future Enhancements

We have just covered a very basic implementation of the pdf using iTextSharp. I’ll try to add advanced features of the iTextSharp application in next post

7.0 References

Download iTextSharp.dll version 5.0 from
http://sourceforge.net/projects/itextsharp/files/itextsharp/iTextSharp-5.0.0/itextsharp-5.0.0- dll.zip/download

No comments:

Post a Comment