使用HTML文件,我用iText pdfHTML生成了PDF文件。现在我想将目录(TOC)添加到第二页。我看到了同样的问题adding-toc-dynamically。但对此没有答案。我尝试了和他一样的场景。我想知道如何获取TOC的页码?如何使用pdfHTML添加目录?有可能这样做吗?
发布于 2021-04-25 23:40:57
重复问题(HTML to PDF adding a table of contents (TOC) dynamically)中的答案在一段时间后没有获得任何支持,因此我无法将此问题作为重复问题结束,因此请在此处发布答案:
我的答案是使用Java语言,但是您可以很容易地将其转换为.NET,因为我将使用的Jsoup版本嵌入到了iText中,剩下的转换基本上就是更改方法名称,使其以大写字母开头。
现在可以用纯pdfHTML 3.0.3+生成目录,但这自然需要对HTML文件进行一些预处理。
其思想是,我们将遍历标记为data-toc的元素,并创建相应的内容列表元素。最有趣的部分是生成页码,这些页码指示我们所引用的内容所在的页面。为此,我们将使用target-counter CSS函数,并使用唯一ID标记所有具有data-toc属性的元素,以便能够在target-counter上下文中引用它们,也可以跳转到纯链接中的这些元素。
下面是一个带有一些助手注释的示例代码:
Document htmlDoc = Jsoup.parse(new File("path/to/in.html"), "UTF-8");
// This is our Table of Contents aggregating element
Element tocElement = htmlDoc.body().prependElement("div");
tocElement.append("<b>Table of contents</b>");
// We are going to build a complex CSS
StringBuilder tocStyles = new StringBuilder().append("<style>");
Elements tocElements = htmlDoc.select("[data-toc]");
for (Element elem : tocElements) {
// Here we create an anchor to be able to refer to this element when generating page numbers and links
String id = UUID.randomUUID().toString();
elem.attr("id", id);
// CSS selector to show page numebr for a TOC entry
tocStyles.append("*[data-toc-id=\"" + id + "\"] .toc-page-ref::after { content: target-counter(#" + id + ", page) }");
// Generating TOC entry as a small table to align page numbers on the right
Element tocEntry = tocElement.appendElement("table");
tocEntry.attr("style", "width: 100%");
Element tocEntryRow = tocEntry.appendElement("tr");
tocEntryRow.attr("data-toc-id", id);
Element tocEntryTitle = tocEntryRow.appendElement("td");
tocEntryTitle.appendText(elem.attr("data-toc"));
Element tocEntryPageRef = tocEntryRow.appendElement("td");
tocEntryPageRef.attr("style", "text-align: right");
// <span> is a placeholder element where target page number will be inserted
// It is wrapped by an <a> tag to create links pointing to the element in our document
tocEntryPageRef.append("<a href=\"#" + id + "\"><span class=\"toc-page-ref\"></span></a>");
}
tocStyles.append("</style>");
htmlDoc.head().append(tocStyles.toString());
String html = htmlDoc.outerHtml();
HtmlConverter.convertToPdf(html, new FileOutputStream("path/to/out.pdf"));我使用上面的代码和示例文件得到的结果的可视化表示:

https://stackoverflow.com/questions/61092898
复制相似问题