使用itextsharp生成内容表

我正在做的是从数据库生成pdf小册子。 我需要生成一个包含页码的内容表。 例如,有两章页码如:

=============================

内容表

第1章—– 3

第2章—– 17

=============================

“第1章—–”是正常段落。 但页码“3”必须使用PdfTemplate生成,因为它只能在以后知道。 但pdfTemplate绝对定位。 我怎么知道PdfTemplate的位置? 我对吗? 我怎么能弄清楚这个或者我应该使用其他方法?

我已经提取了一些代码来帮助您解决问题。此代码允许您使用x和y将文本放在页面的任何位置。 您可能实际上想要使用iTextSharp的内置段落和保证金支持,但这将非常有用,只需要转换为C#

Dim stamper As PdfStamper Dim templateReader As PdfReader = New PdfReader(yourFileName) Dim currentPage As PdfImportedPage = stamper.GetImportedPage(templateReader, 1) stamper.InsertPage(1, PageSize.A4) Dim cb As PdfContentByte = stamper.GetOverContent(1) cb.AddTemplate(currentPage, 0, 0) 

对于要添加的每个元素,请查看下一位。

 cb.BeginText() cb.SetFontAndSize(bf, 12) cb.SetColorFill(color) 'create a color object to represent the colour you want cb.ShowTextAligned(1, "Content Table", x, y, 0) 'pass in the x & y of the element cb.EndText()