iTextSharp: Generate a PDF file containing a table (ASP.NET/C#)
Contining on from iTextSharp: Generating a Basic PDF file (ASP.NET/C#), here is a demo of how to generate a PDF document with a table in it.
<%@ WebHandler Language="C#" Class="MyNamespace.TablePDF" %>
using System;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace MyNamespace
{
public class TablePDF: IHttpHandler
{
public bool IsReusable
{
get
{
return true;
}
}
/// <summary>
/// Font used for table headers
/// </summary>
private Font TableHeaderFont
{
get
{
return new Font(Font.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);
}
}
public void ProcessRequest(HttpContext ctx)
{
// make sure it is sent as a PDF
ctx.Response.ContentType="application/pdf";
// make sure it is downloaded rather than viewed in the browser window
ctx.Response.AddHeader("Content-disposition", "attachment; filename=TablePDF.pdf");
// create a MemoryStream (as there may not be write access to any folder on the server)
using(MemoryStream m = new MemoryStream())
{
// create the PDF document
Document document = new Document(PageSize.A4);
PdfWriter.GetInstance(document, m);
// open document to add content
document.Open();
// add table with 3 columns
Table myTable = new Table(3);
myTable.AutoFillEmptyCells = true;
// add padding to table cells
myTable.Cellpadding = 3.5f;
// make sure table fits the width of the page
myTable.WidthPercentage = 100.0f;
// remove borders
//myTable.DefaultCellBorder = Rectangle.NO_BORDER;
//myTable.Border = Rectangle.NO_BORDER;
// create cell
Cell myCell = new Cell();
// add header cell
myCell.Header = true;
myCell.Add(new Chunk("Header 1",TableHeaderFont));
// row 1 column 1
myTable.AddCell(myCell, 0, 0);
// new header
myCell = new Cell();
myCell.Header = true;
myCell.Add(new Chunk("Header 2",TableHeaderFont));
// row 1 column 2
myTable.AddCell(myCell, 0, 1);
// another new header
myCell = new Cell();
myCell.Header = true;
myCell.Add(new Chunk("Header 3",TableHeaderFont));
// row 1 column 3
myTable.AddCell(myCell, 0, 2);
// add some data (6 rows worth)
for (int i=1; i<=6; i++)
{
// on the third iteration, span several columns
if(i == 3)
{
myCell = new Cell();
myCell.Colspan = 3;
myCell.HorizontalAlignment = Element.ALIGN_CENTER;
myCell.Add(new Chunk("R" + (i + 1) + "C1 - " + "R" + (i + 1) + "C3"));
myTable.AddCell(myCell, i, 0);
}
else
{
myCell = new Cell();
myCell.Add(new Chunk("R" + (i + 1) + "C1"));
myTable.AddCell(myCell, i, 0);
myCell = new Cell();
myCell.Add(new Chunk("R" + (i + 1) + "C2"));
myTable.AddCell(myCell, i, 1);
myCell = new Cell();
myCell.Add(new Chunk("R" + (i + 1) + "C3"));
myTable.AddCell(myCell, i, 2);
}
}
// add table
document.Add(myTable);
// close the document
document.Close();
// stream the PDF to the user
ctx.Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
}
ctx.Response.End();
}
}
}
Tags: Web Developer Blog, iTextSharp, PDF, WebHandler, CSharp, ASP.NET
Comments