我正在开发一个工具,用于生成表示评估结果的PDF文档。这些文档的结构和一些文本和图像是由非技术用户定义的(这就是为什么Apache和XSL不是一个选项的原因之一)。
对于这一点,OpenPDF似乎是一个很有希望的库(除了Apache PDFBox,它太低了)。但是,生成的文档必须包含一个目录。
预期的文件结构如下:
1. Cover
2. Abstract
3. Table of Contents
4. Chapter 1 .. n由于我无法知道文档最终将有多少页,或者不同章节将在哪一页上开始,所以在将每个章节添加到文档之前,我无法定义目录表。
由于OpenPDF直接将元素写入文档,因此似乎不可能在添加所有章节之后保留对示例性内容表元素的引用并添加其内容。
发布于 2020-05-15 09:16:44
我已经找到了一种解决方案,可以通过使用reorderPages(int[])方法com.lowagie.text.pdf.PdfWriter来处理预期的结构。
首先,我保留目录的第一页(摘要后的第一页):
int intendedTocFirstPage = pdfWriter.getCurrentPageNumber() - 1; // - 1 because of a necessary `document.newPage();` before that在将所有章节添加到文档中之后,我将最后添加目录,并保留其中的第一页和最后一页(因为根据章节和分章的数量,可能需要多页):
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变量的页面的新顺序:
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;
}最后,我正在重新排序文件的页数:
int[] reorderedPages = getReorderedPagesForTableOfContents(targetedTocFirstPage, tocFirstPage, tocLastpage);
pdfWriter.reorderPages(reorderedPages);这是可行的,但它产生了另一个问题:
使用页脚显示页码将不再正常工作,因为重新排序之前的数字将保持不变。
一个可能的解决方案是首先创建完整的文档,包括页面的重新排序,然后使用PdfReader添加页码,如下所示:https://stackoverflow.com/a/759972/10551549
如果有人有一个更好的解决方案,我会很高兴听到它(因为这个有点混乱,在我看来)。:)
https://stackoverflow.com/questions/61815826
复制相似问题