java - Apache PDFBox Java 库 - 文本未渲染

标签 java apache pdf graphics pdfbox

我正在使用 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 的作用,因此将其注释掉并重试,但文本仍然没有渲染。

最佳答案

newLineAtOffset() 相对于当前文本位置。要从 0 重新开始,最简单的方法是结束当前文本 block 并开始新的文本 block 。您当前的代码将您置于 y 1335(或稍低,具体取决于行距)。

关于java - Apache PDFBox Java 库 - 文本未渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47030025/

相关文章:

java - 与 HttpClient 状态 CLOSE_WAIT 的连接泄漏

apache - MaxKeepAliveRequests 和 MaxConnectionsPerChild 之间的交互

pdf - PDF文本字符串的编码

pdf - 摆脱 matlab 图的 pdf 输出周围的空白

java - 在 Android 中打开 PDF 文件

java - Maven资源过滤未执行

java - Spring Batch - 循环读取器/处理器/写入器步骤

django - 使用 Django 和 Apache 进行非根路由

java - 使用源代码创建并运行 jar 文件

apache - 通过 Apache 的 Tomcat