下面是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);
}
你已经建立的文档TOC protion后,下一步就是生成actualy内容对应于TOC。当您创建的实际页面的每个标题的,你需要创建一个新的变量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);
}
我希望帮助!