【问题标题】:Apache PDFBox Java library- text not getting renderedApache PDFBox Java 库 - 文本未呈现
【发布时间】:2018-04-12 07:18:55
【问题描述】:

我正在使用 Apache PDFBox java 库来创建 PDF。但是,我在呈现多行文本(换行)时遇到问题:

//Creating PDF document object 
PDDocument doc = new PDDocument();

//Adding the blank page to the document
doc.addPage( new PDPage() );

PDPage page = doc.getPage(0);
PDImageXObject pdImage = PDImageXObject.createFromFile("C:\\Users\\abc\\Desktop\\abc.png", doc);

PDPageContentStream contentStream = new PDPageContentStream(doc, page); 
contentStream.drawImage(pdImage, 10, 720);

//Begin the Content stream 
contentStream.beginText(); 
contentStream.newLineAtOffset(50, 735);

//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
contentStream. showText("ABC Management System");

//Setting the leading
//contentStream.setLeading(14.5f);

//Setting the position for the line
contentStream.newLineAtOffset(25, 600);

String text1 = "This is an example of adding text to a page in the pdf document we can add as many lines";
String text2 = "as we want like this using the ShowText()  method of the ContentStream class";

//Adding text in the form of string
contentStream. showText(text1);
contentStream.newLine();
contentStream. showText(text2);

//Ending the content stream
contentStream.endText();

System.out.println("Content added");

//Closing the content stream
contentStream.close();

//Saving the document
doc.save("my_doc.pdf");

System.out.println("PDF created");  

//Closing the document  
doc.close();

我面临的问题是文本的后半部分(text1、text2)没有在 PDF 文件中呈现。 pdf中只显示图片和第一行ABC Management System

为了生成多行文本,我参考了:PDFBox - Adding Multiple Lines

我不明白 setLeading 做了什么,因此将其注释掉并再次尝试,但文本仍未呈现。

【问题讨论】:

  • @TilmanHausherr 它奏效了。谢谢!
  • @TilmanHausherr 有没有办法改变背景颜色?
  • 您必须以适当的非描边颜色绘制一个矩形。
  • @HBK 更多自动换行,您可能想从this answer 寻找灵感。

标签: java apache pdf graphics pdfbox


【解决方案1】:

newLineAtOffset() 相对于当前文本位置。要从 0 重新开始,最简单的方法是结束当前并开始一个新的文本块。您当前的代码将您置于 y 1335(或略低,取决于前导)。

【讨论】:

  • 有什么捷径可以换行吗?现在,我们必须将一行分成两个字符串来实现。
  • 没有。 PDFBox 是低级的,与 itext 不同。您必须自己进行换行/换页。
猜你喜欢
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
相关资源
最近更新 更多