首页 > 解决方案 > 为什么我用 Apache PdfBox 创建的 pdf 没有集成新行?

问题描述

我想创建一个多行 pdf 文档。我正在使用来自 Apache 的 PdfBox。

我有这个简单的代码:

        PDDocument document = new PDDocument();
        PDPage page = new PDPage();
        document.addPage(page);

        // Retrieving the pages of the document
        PDPageContentStream contentStream = new PDPageContentStream(document, page);

        contentStream.beginText();
        contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);

        contentStream.showText("blabla");
        contentStream.newLine(); 
        contentStream.showText("blabla");
        contentStream.newLine(); 
        contentStream.showText("blabla");
        contentStream.newLine(); 

我只得到这样一条简单的线:“blablablablablabla”

有人可以帮我吗?

谢谢

标签: javapdfpdfbox

解决方案


我想你忘记使用 setLeading 了?使用前contentStream.newLine()您需要使用contentStream.setLeading(float)

(这里的主要来源:https ://www.javatpoint.com/pdfbox-adding-multiple-lines )

我已经编辑了您的代码的相关部分:

contentStream.beginText();
contentStream.newLineAtOffset(20,600); // set starting position
contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);

contentStream.setLeading(14.5f);  // set the size of the newline to something reasonable

contentStream.showText("blabla");
contentStream.newLine();
contentStream.showText("blabla");
contentStream.newLine();
contentStream.showText("blabla");
contentStream.newLine();

只要其余代码正常工作(正确关闭和打开文件),在我的机器上运行它会产生多行。


推荐阅读