Generating PDF Files With iTextSharp
I recently had the need to generate a PDF file containing a table where some of the cells included images. Of course, I used iTextSharp to do it. Because it has some obscure parts, I decided to publish a simplified version of the code I used.
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
//...
protected void OnGeneratePdfClick()
{
String text = "Multi\nline\ntext";
String name = "Some Name";
String number = "12345";
Int32 rows = 7;
Int32 cols = 3;
Single headerHeight = 47f;
Single footerHeight = 45f;
Single rowHeight = 107.4f;
String pdfName = String.Format("Labels - {0}", name);
PdfPTable table = new PdfPTable(3) { WidthPercentage = 100, HeaderRows = 1 };
PdfPCell headerCell = new PdfPCell(new Phrase("Header")) { Colspan = cols, FixedHeight = headerHeight, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 0f };
table.AddCell(headerCell);
FontFactory.RegisterDirectory(@"C:\WINDOWS\Fonts"); //required for the Verdana font
Font cellFont = FontFactory.GetFont("Verdana", 6f, Font.NORMAL);
for (Int32 r = 0; r < rows; ++r)
{
for (Int32 c = 0; c < cols; ++c)
{
PdfPCell cell = new PdfPCell() { HorizontalAlignment = Element.ALIGN_LEFT, FixedHeight = rowHeight, PaddingLeft = 20f, BorderWidth = 0f };
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(String.Concat(this.Server.MapPath("~/Images/"), number, ".gif"));
image.ScalePercent(75, 75);
foreach (String part in text.Split('\n'))
{
cell.AddElement(new Phrase(part, cellFont));
}
cell.AddElement(image);
table.AddCell(cell);
}
}
PdfPCell footerCell = new PdfPCell(new Phrase("Footer")) { Colspan = cols, FixedHeight = footerHeight, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 0f };
table.AddCell(footerCell);
Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
this.Response.Clear();
this.Response.ContentType = "application/pdf";
this.Response.ContentEncoding = Encoding.Default;
this.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.pdf", pdfName));
PdfWriter writer = PdfWriter.GetInstance(doc, this.Context.Response.OutputStream);
doc.Open();
doc.Add(table);
doc.Close();
}