【问题标题】:I'm unable to add new pages using Pdfbox我无法使用 Pdfbox 添加新页面
【发布时间】:2020-04-06 03:44:20
【问题描述】:
public static void main(String[] args) {
    try {
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        document.addPage(page);
        addText(document, page);
        document.save("C:/Java/cda.pdf");
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static void addText(PDDocument document, PDPage page) {

    try {

        PDPageContentStream contentStream = new PDPageContentStream(document, page,
                PDPageContentStream.AppendMode.APPEND, true);
        float sY = 750;
        contentStream.beginText();
        contentStream.setFont(PDType1Font.HELVETICA, 12);
        contentStream.newLineAtOffset(60, sY);
        for (int i = 1; i <= 50; i++) {
            contentStream.showText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
            contentStream.newLineAtOffset(0, -18);
            System.out.println(sY - 18);
            sY = sY - 18;
            if (sY - 18 < 18) {
                contentStream.endText();
                contentStream.close();
                contentStream = new PDPageContentStream(document, new PDPage(PDRectangle.LETTER),
                        PDPageContentStream.AppendMode.APPEND, true);
                contentStream.setFont(PDType1Font.HELVETICA, 12);
                contentStream.beginText();
                sY = 750;
            }
        }
        contentStream.endText();
        contentStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 单页代码工作正常,但是当内容超过第一页时,它不会添加新的 页面
  • 找不到我缺少的东西
  • 我认为问题出在 addText() 的“if”块中

【问题讨论】:

  • 如果答案有帮助,请点击复选标记使其成为接受的答案。如果答案没有帮助,请发表评论,解释发生了什么/没有发生什么。

标签: java pdf-generation pdfbox


【解决方案1】:

你需要打电话

document.addPage(page);

也是第二次。您在问题中的代码在“孤立”PDPage 对象中创建了第二个页面内容流,并且不会将其添加到文档中。

我没有重写代码,因为您需要进行一些重构,因为 addText() 已经有一个 PDPage 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多