Here is what I am doing with ITextSharp. 1. Read a list of data from SQL Table 2. Generate table with iTextSharp using the above data 3. Add the table into a PDF
The table is overflow to the next page automatically when I add the table to PDF. Number of pages is unknown until I add the table into the PDF. I would like to add header to each page.
Is there anyway I can add the header in each page?
Below is the code to generate the PDF table.
public bool CreateProductsCoverPage(ProductDataList products, string inFile, string outFile, out string error)
{
error = "";
try
{
var reader = new PdfReader(inFile);
var size = reader.GetPageSizeWithRotation(1);
var document = new Document(size);
var rect = reader.GetBoxSize(1, "trim");
var fs = new FileStream(outFile, FileMode.Create, FileAccess.Write);
var writer = PdfWriter.GetInstance(document, fs);
//Open the document
document.Open();
// the pdf content
var cb = writer.DirectContent;
//Define the fonts for title
var headerFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
, 12
, iTextSharp.text.Font.BOLD
, BaseColor.BLACK
);
//Define the fonts for text
var detailsFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
, 10
, iTextSharp.text.Font.NORMAL
, BaseColor.BLACK
);
PdfPTable PdfTable = new PdfPTable(4);
var pageWdith = reader.GetPageSize(1).Width * 0.95f;
var ratio = pageWdith / 10;
float[] widths = new float[] { 1f * ratio, 2f * ratio, 6f * ratio, 1f * ratio };
Rectangle pSize = new Rectangle(reader.GetPageSize(1).Height * 0.9f, reader.GetPageSize(1).Width * 0.9f);
PdfTable.SetWidthPercentage(widths, reader.GetPageSize(1));
PdfPCell PdfPCell = null;
//Add Header of the pdf table
PdfPCell = new PdfPCell(new Phrase(new Chunk("QTY", headerFont)));
PdfTable.AddCell(PdfPCell);
PdfPCell = new PdfPCell(new Phrase(new Chunk("ISBN", headerFont)));
PdfTable.AddCell(PdfPCell);
PdfPCell = new PdfPCell(new Phrase(new Chunk("AUTHOR/TITLE", headerFont)));
PdfTable.AddCell(PdfPCell);
PdfPCell = new PdfPCell(new Phrase(new Chunk("BAY", headerFont)));
PdfTable.AddCell(PdfPCell);
var recordCount = products.Count;
//How add the data from datatable to pdf table
foreach (var product in products)
{
foreach (var prop in product.GetType().GetProperties())
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(prop.GetValue(product, null).ToString(), detailsFont)));
PdfTable.AddCell(PdfPCell);
}
PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
}
document.Add(PdfTable);
// create the new page and add it to the pdf
var page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}