如何解决PDFBox 2.0.9 - 创建多页目录
我正在处理 PDF Toc。它生成了第一页,但是当我有更多元素时,我做了逻辑来为 TOC 创建一个新页面。我正在使用 PDF Box 和 PDPageContentStream。 我必须创建一个函数来计算我需要多少页。然后我在列表中创建确切数量的页面并将它们添加到 PDF 文档中,然后再启动 PDPageContentStream。该流处于循环中,并且仅生成第一页。其他页面变为空白。我不知道究竟出了什么问题。代码如下:
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 页使用此代码设置 Y 偏移量,因为当 i > 0 时不使用 currentYPosition
contentStream.newLineAtOffset(contentMarginLeft,-leading);
所以你的第一个 Y 偏移值为负。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。