【发布时间】:2021-10-05 19:13:39
【问题描述】:
我正在处理 PDF 目录。它生成第一页,但是当我有更多元素时,我做了逻辑来为 TOC 创建一个新页面。我正在使用 PDF Box 和那个 PDPageContentStream。 我必须创建一个函数来计算我需要多少页。然后我在列表中创建确切数量的页面,并在启动 PDPageContentStream 之前将它们添加到 PDF 文档中。该流处于循环中,并且仅生成第一页。其他页面为空白。我不知道到底出了什么问题。代码如下:
PDDocument pdf = new PDDocument();
int numberOfTocPages = calculateTocPages(50, tocStyle, _height, currentYPosition, leading);
List<PDPage> tocPages = new ArrayList<PDPage>();
for (int i = 0; i < numberOfTocPages; i++) {
PDPage toc = new PDPage(new PDRectangle(_width, _height));
tocPages.add(toc);
}
float numberingXPosition = _width - (contentMarginLeft + contentMarginRight) - 100;
int j = 0;
PDDocument temp = new PDDocument();
for (int i = 0; i < numberOfTocPages; i++) {
PDPage toc = tocPages.get(i);
pdf.addPage(toc);
try {
PDPageContentStream contentStream = new PDPageContentStream(pdf, toc, PDPageContentStream.AppendMode.APPEND, true, false);
contentStream.beginText();
if (i == 0) {
contentStream.setFont(font, fontSize);
contentStream.setNonStrokingColor(tocStyle.getHeaderFontColor());
contentStream.newLineAtOffset(headerMarginLeft, currentYPosition);
contentStream.showText(StylingEnums.TABLE_OF_CONTENTS);
}
fontSize = tocStyle.getContentFontSize();
leading = 1.5f * fontSize;
contentStream.setFont(PDType1Font.HELVETICA, fontSize);
contentStream.setNonStrokingColor(tocStyle.getContentFontColor());
contentStream.newLineAtOffset(contentMarginLeft, -leading);
currentYPosition -= leading;
contentStream.setLeading(leading);
// List<TocContentData> tocItems = _tocData.getTocItems();
while (j < 50) {
if (currentYPosition >= 2 * tocStyle.getContentMarginBottom()) {
// TocContentData item = tocItems.get(i);
contentStream.showText("Item " + j);
contentStream.newLineAtOffset(numberingXPosition, 0);
int pageNumber = j;
contentStream.showText(Integer.toString(pageNumber + 1));
contentStream.newLineAtOffset(-numberingXPosition, 0);
contentStream.newLine();
currentYPosition -= leading;
j++;
} else {
System.out.println("New page!!!");
currentYPosition = initialPosition;
break;
}
}
contentStream.endText();
contentStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream out;
try {
out = new FileOutputStream(fileName + ".pdf");
pdf.save(out);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
【问题讨论】:
-
我不想重置,因为其余内容需要转到下一页。在第 2 页中,它应该以 j = 22 开头。
-
您为什么使用 2.0.9 而不是当前的 2.0.24?那个版本有什么特别之处吗?
标签: java pdf pdfbox tableofcontents