【问题标题】:PDFBox: How to create a new page and position text after the current page is fullPDFBox:如何在当前页面已满后创建新页面并定位文本
【发布时间】:2018-08-24 11:20:16
【问题描述】:
//for writing filenames           
PDDocument doc = PDDocument.load(this.getClass().getResourceAsStream("/Vorlagen/Analyze/ReportTemplate.pdf"));
PDPage curFileNamePage = new PDPage(PDRectangle.A4);
doc.addPage(curFileNamePage);

contentStream = new PDPageContentStream(doc, curFileNamePage, PDPageContentStream.AppendMode.APPEND, true, true);
contentStream.setFont(pdfFont, 12);
contentStream.beginText();
float curYVal = 650f;
contentStream.newLineAtOffset(20, curYVal);

for (int idx = 0; idx < 377; idx++) {
    if (curYVal - 15f > 0) {
        curYVal = curYVal - 15f;
        contentStream.newLineAtOffset(0, curYVal);
        contentStream.showText("" + idx);
    } else {
        contentStream.endText();
        contentStream.close(); // close writing area
        curFileNamePage = new PDPage(PDRectangle.A4);
        doc.addPage(curFileNamePage);

        contentStream = new PDPageContentStream(doc, curFileNamePage, PDPageContentStream.AppendMode.APPEND, true, true);
        contentStream.setFont(pdfFont, 12);
        contentStream.beginText();
        curYVal = 650f;
        contentStream.newLineAtOffset(0, curYVal);
        contentStream.showText("" + idx);
            }

}
contentStream.endText();
contentStream.close(); // close writing area

doc.save("C:\\Users\\noname\\Desktop\\765.pdf");//Saving the document
doc.close();

所以我有许多索引(在本例中为 377)。我的目标是创建一个pdf,其中索引一个接一个地打印出来。 (在这种情况下,它应该沿 y 轴向下移动 15f)。如果到达页面的末尾,它应该创建一个新页面并从头开始。

现在您可能会猜到,代码的行为并不正常。在我执行代码后,pdf 文件被创建为 9 页,但有趣的是每页只包含一个数字(第一页除外)。号码是:43,87,131,175,219,263,307,351

我做错了什么?

这是输出的样子:

这是我当前的输出:

【问题讨论】:

  • 通过附上预期和您得到的屏幕截图来详细说明问题
  • @NiranjanKumar 好的,请稍等
  • @NiranjanKumar 我添加了图片

标签: java pdf-generation pdfbox


【解决方案1】:

改变第一个(不是第二个)

contentStream.newLineAtOffset(0, curYVal);

contentStream.newLineAtOffset(0, -15f);

因为这是一个相对位置。因此,大值仅在文本段中的第一次(相对于 0,0 时)才有意义。第一次定位后,减去偏移量即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多