我编写了这个程序来从ArrayList
读取字符串值并使用pdfbox将它们写入pdf文件。
除了字符串字符串列表之外,没有其他字符串被添加。代码如下:
import java.io.IOException;
import java.util.ArrayList;
import org.apache.pdfbox.contentstream.PDContentStream;
import org.apache.pdfbox.pdmodel.*;
public class pdfBoxTest {
public static void main(String[] args) {
ArrayList<String> r = new ArrayList<String>();
r.add("Jack and ");r.add("Jill ");r.add("Went up");r.add(" the hill");
try{
PDDocument file = new PDDocument();
PDPage page = new PDPage();
file.addPage(page);
PDPageContentStream data = new PDPageContentStream(file, page);
data.beginText();
data.setFont(PDType1Font.HELVETICA, 20);
float x=220,y=750;
data.newLineAtOffset(x, y);
data.showText("List of Strings");
for(int i=0;i<r.size();i++){
String line=r.get(i);
System.out.println(line);
data.newLineAtOffset(x, y);
data.showText(line);
y+=100;
}
data.close();
file.save("res.pdf");
file.close();
}
catch (IOException e) { e.printStackTrace(); }
}
}
最佳答案
当你介绍这一行时:
data.beginText();
您开始在 PDF 中创建文本对象。
但是,您还需要这一行:
data.endText();
这样就完成了文本对象。您没有完整的文本对象,这可能会导致奇怪的结果。
此外,您似乎不了解PDF中的坐标系。请参阅以下常见问题解答条目:
- How should I interpret the coordinates of a rectangle in PDF?
- Where is the origin (x,y) of a PDF page?
更改此行:
y+=100;
对此:
y-=100;
您从 float x=220,y=750;
开始,我不知道 PdfBox 中的默认页面大小,但我们假设它是 A4 页面。在这种情况下,页面尺寸为 595(宽)x 842(高)个用户单位,并且 float x=220,y=750;
或多或少位于中间(水平)和顶部附近(垂直)。
当您将 100 添加到 y
时,最终会得到 y = 850
,这意味着您将离开页面的可见区域(因为 850高于 842)。您正在添加文本,并且文本位于您正在创建的内容流中,但文本不可见,因为它位于页面的 /MediaBox
之外。
最后:newLineAtOffset()
方法不会将内容移动到您定义的坐标,而是开始一个新行并使用参数作为距当前位置的偏移量。 em> 因此,即使您按照我解释的方式更改 y
,您也会将内容移动到与 (x, y)
坐标处的位置完全不同的位置.
底线:PdfBox 要求您了解 PDF 语法。如果您不知道 PDF 语法(从您的问题中可以清楚地看出),您应该考虑使用 iText。 (免责声明:我是 iText Group 的 CTO。)
OP的错误详细信息(由mkl编辑)
与OP期望的相反,方法调用data.newLineAtOffset(x, y)
确实不接受绝对坐标但< strong>相反期望相对于前一行开始的坐标:
/**
* The Td operator.
* Move to the start of the next line, offset from the start of the current line by (tx, ty).
*
* @param tx The x translation.
* @param ty The y translation.
* @throws IOException If there is an error writing to the stream.
* @throws IllegalStateException If the method was not allowed to be called at this time.
*/
public void newLineAtOffset(float tx, float ty) throws IOException
因此,考虑到 OP 尝试使用向下 100 的 y 坐标变化,循环中该方法的调用应该是
data.newLineAtOffset(0, -100);
关于java - 内容未添加到 pdf 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343683/