首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用OpenPDF添加目录

如何使用OpenPDF添加目录
EN

Stack Overflow用户
提问于 2020-05-15 09:16:44
回答 1查看 978关注 0票数 1

我正在开发一个工具,用于生成表示评估结果的PDF文档。这些文档的结构和一些文本和图像是由非技术用户定义的(这就是为什么Apache和XSL不是一个选项的原因之一)。

对于这一点,OpenPDF似乎是一个很有希望的库(除了Apache PDFBox,它太低了)。但是,生成的文档必须包含一个目录。

预期的文件结构如下:

代码语言:javascript
复制
 1. Cover
 2. Abstract
 3. Table of Contents
 4. Chapter 1 .. n

由于我无法知道文档最终将有多少页,或者不同章节将在哪一页上开始,所以在将每个章节添加到文档之前,我无法定义目录表。

由于OpenPDF直接将元素写入文档,因此似乎不可能在添加所有章节之后保留对示例性内容表元素的引用并添加其内容。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-15 09:16:44

我已经找到了一种解决方案,可以通过使用reorderPages(int[])方法com.lowagie.text.pdf.PdfWriter来处理预期的结构。

首先,我保留目录的第一页(摘要后的第一页):

代码语言:javascript
复制
int intendedTocFirstPage = pdfWriter.getCurrentPageNumber() - 1; // - 1 because of a necessary `document.newPage();` before that

在将所有章节添加到文档中之后,我将最后添加目录,并保留其中的第一页和最后一页(因为根据章节和分章的数量,可能需要多页):

代码语言:javascript
复制
int tocFirstPage = pdfWriter.getCurrentPageNumber();
document.add(new Paragraph("TBA: Actual Table of Contents")); // TODO replace with the table of contents based on the existing chapters and sections
document.newPage();
int tocLastpage = pdfWriter.getCurrentPageNumber();

然后,我将创建一个数组,该数组表示基于三个int变量的页面的新顺序:

代码语言:javascript
复制
private int[] getReorderedPagesForTableOfContents(int intendedTocFirstPage, int tocFirstPage, int tocLastpage) {
    int[] pages = IntStream
            .range(1, tocLastpage)
            .toArray();

    /*
     * Reorder the pages array by placing the toc page numbers at
     * the indexes starting from targetedTocFirstPage (should be
     * the page directly after the summary)
     */
    int numberOfTocPages = tocLastpage - tocFirstPage;
    if (numberOfTocPages >= 0) {
        System.arraycopy(pages, tocFirstPage - 1, pages, intendedTocFirstPage, numberOfTocPages);
    }

    /* Shift the page numbers of all pages after the last toc page */
    for (int i = intendedTocFirstPage + numberOfTocPages; i < pages.length; i++) {
        pages[i] = i - numberOfTocPages + 1; // `+ 1` because page numbers start with 1 not 0
    }

    return pages;
}

最后,我正在重新排序文件的页数:

代码语言:javascript
复制
int[] reorderedPages = getReorderedPagesForTableOfContents(targetedTocFirstPage, tocFirstPage, tocLastpage);
pdfWriter.reorderPages(reorderedPages);

这是可行的,但它产生了另一个问题:

使用页脚显示页码将不再正常工作,因为重新排序之前的数字将保持不变。

一个可能的解决方案是首先创建完整的文档,包括页面的重新排序,然后使用PdfReader添加页码,如下所示:https://stackoverflow.com/a/759972/10551549

如果有人有一个更好的解决方案,我会很高兴听到它(因为这个有点混乱,在我看来)。:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61815826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档