【问题标题】:Adding Table of Content with pdfHTML in iText7 [duplicate]在 iText7 中添加带有 pdfHTML 的目录 [重复]
【发布时间】:2020-04-08 03:31:29
【问题描述】:

使用 HTML 文件,我使用 iText pdfHTML 生成 PDF 文件。现在我想将目录(TOC)添加到第二页。我看到了同样的问题adding-toc-dynamically。但对此没有答案。我尝试了与他相同的场景。我想知道如何获取 TOC 的页码? 如何使用 pdfHTML 添加目录? 有可能吗?

【问题讨论】:

  • 如果重复帖子没有答案,请尝试改进。您可能需要联系该库的作者以获得支持。

标签: c# itext7 tableofcontents pdfhtml


【解决方案1】:

重复问题 (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 的上下文中引用它们并跳转到纯链接中的那些元素。

这是一个带有一些辅助 cmets 的示例代码:

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"));

我使用上面的代码和您的示例文件得到的结果的可视化表示:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2021-08-29
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多