Вот код на C # для дальнейшего объяснения того, что Марк Сторер предоставил выше.
В этом фрагменте предполагается, что вы перебираете xmlHeaders для построения раздела оглавления:
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);
}
После того, как вы построите содержание документа, следующим шагом будет создание фактического содержимого, соответствующего содержанию. Когда вы создаете фактическую страницу для каждого из заголовков, вам нужно будет создать новую переменную Chapter
и добавить ее в документ. Это запустит пользовательский код, который вы добавите в обработчик событий OnChapter
.
Наконец, в обработчике событий пользовательской страницы нам нужно добавить код к методу OnChapter
и создать собственный метод для хранения списка шаблонов.
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++;
}
Массив шаблонов:
List<PdfTemplate> tableOfContentsTemplateList = new List<PdfTemplate>();
public void addChapTemplateList(PdfTemplate chapTemplate)
{
tableOfContentsTemplateList.Add(chapTemplate);
}
Надеюсь, это поможет!