I’ve a requirement where I need to generate a PDF file with Index along with Page numbers. I'm using ItextSharp for generating PDF. The Document may contains hundreds of pages. The data in the PDF document will be the dynamic data. Here is my Code to generate the PDF :
Rectangle rec2 = new Rectangle(PageSize.A4);
using (FileStream fs = new FileStream("D:/Sample1.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
using (Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f))
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
{
PdfPageEventHelper pageEventHelper = new PdfPageEventHelper();
writer.PageEvent = pageEventHelper;
doc.SetMargins(20, 20, 50, 50);
doc.NewPage();
doc.Open();
var Content = writer.DirectContent;
var pageBorderRect = new Rectangle(doc.PageSize);
………..
………………..
………………..
………..
doc.Close();
}
And to add the page numbers to generated document I used the following method
public void AddPageNumber(string BidNumber)
{
byte[] bytes = System.IO.File.ReadAllBytes(@"D:\Sample1.pdf");
Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
Font boldfont = FontFactory.GetFont("Arial", 14, Font.BOLD, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int j = 2; j <= pages; j++)
{
ColumnText.ShowTextAligned(stamper.GetUnderContent(j), Element.ALIGN_RIGHT, new Phrase((j - 1).ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
System.IO.File.WriteAllBytes(@"D:\newPDF.pdf", bytes);
}
Now, I need to create and add the Index with page numbers for this document. Here my problem is the index content also is dynamic data which will be some data in the document. While searching for my requirement, I found this,
int chapTemplateCounter = 0;
public override void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
{
base.OnChapter(writer, document, paragraphPosition, title);
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
tableOfContentsTemplateList[chapTemplateCounter].BeginText();
tableOfContentsTemplateList[chapTemplateCounter].SetFontAndSize(bfTimes, 12);
tableOfContentsTemplateList[chapTemplateCounter].SetTextMatrix(0, 0);
tableOfContentsTemplateList[chapTemplateCounter].ShowText("" + writer.PageNumber);
tableOfContentsTemplateList[chapTemplateCounter].EndText();
chapTemplateCounter++;
}
I think it is useful for the static headers. How can I add index with page numbers in document with this code or Is it the correct way to generate PDF using Itextsharp
Thanks in Advance.