Here is the code in C# to further explain what Mark Storer provided above.
This snippet assumes that you are looping over the xmlHeaders to build the table of contents section:
PdfContentByte cb = writer.DirectContent;
MyCustomPageEventHandler pageEventHandler
foreach (string headerStr in xmlHeaders)
{
PdfTemplate currChapTemplate = cb.CreateTemplate(50, 50);
Paragraph titlePhrase = new Paragraph();
titlePhrase.Add(headerStr);
titlePhrase.IndentationLeft = 150f;
pdfDoc.Add(titlePhrase);
float curY = writer.GetVerticalPosition(false);
float x = 450;
//here we add the template to the pdf content byte
cb.AddTemplate(currChapTemplate, x, curY);
//Now we have to send the template object to our custom eventhandler
//method that will store a template for each item in our TOC
pageEventHandler.addChapTemplateList(currChapTemplate);
}
After you have built the TOC protion of the document, the next step is to generate the actualy content that corresponds to the TOC. When you create the actual page each of the headers you will need to create a new Chapter
variable and add it to the document. This will fire the custom code that you will be adding to the OnChapter
eventhandler.
Finally, in the custom page eventhandler we need to add code to the OnChapter
method and we need to create a custom method to store a List of templates.
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++;
}
Array of templates:
List<PdfTemplate> tableOfContentsTemplateList = new List<PdfTemplate>();
public void addChapTemplateList(PdfTemplate chapTemplate)
{
tableOfContentsTemplateList.Add(chapTemplate);
}
I hope that helps!