下面是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);
}
我希望幫助!