我在PDF Box中遇到格式问题。我的目标是以表格格式打印PDF作为报告。内容格式将类似于
Name Code Description Value
我检索我的DB结果集,并有一个Java对象列表。我提取所需的信息,并将它们格式化为字符串列表,如下所示。我循环遍历这些对象,构造一个字符串并添加到arrayList中。我的想法是创建一个长度/样式完全相同的字符串列表,以强制pdf格式。
代码参考
for(MyObject obj: dbresults){
//format as below and add to list
}
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format("%-25.25s", "This is some text with more than 25 characters.");
formatter.format("%-25.25s", "Some text with less.");
formatter.format("%-25.25s", "Some other text.");
System.out.println(formatter.toString());
输出:
|This is some text with mo|Some text with less. |Some other text. |
我多次将此列表打印到屏幕上:),通过System.out或logger,格式与我预期的完全一样,甚至是块。
然而,当我发送到PDFBox以打印到文件时,格式会"损坏",并且"表格式"不会得到遵守。我把100和700作为x,y的单词。
代码参考
private void printMultipleLines(
PDPageContentStream contentStream,
List<String> lines,
float x,
float y) throws IOException {
if (lines.size() == 0) {
return;
}
final int numberOfLines = lines.size();
final float fontHeight = getFontHeight();
contentStream.beginText();
contentStream.appendRawCommands(fontHeight + " TLn");
contentStream.moveTextPositionByAmount( x, y);
for (int i = 0; i < numberOfLines; i++) {
contentStream.drawString(lines.get(i));
if (i < numberOfLines - 1) {
contentStream.appendRawCommands("T*n");
}
}
contentStream.endText();
}
要获得字体的高度,可以使用以下命令:
fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
打印示例列表:这是在打印到屏幕时使用java格式化程序类后的样子,一切看起来都很好,但当我打印到PDFBox时,格式不符合
Tom Thumb 555-ddd Good 23
Tom Thumb 666-ggg Good 45
CHARLES DICKENS 777-jjj Good 32
CHARLES DICKENS 666-hhh Bad 11
W Yeats 888-hhh Ok 12
R Whitely 444-999 Terrible 44
PDF输出看起来像
Tom Thumb 555-ddd Good 23
Tom Thumb 666-ggg Good 45
CHARLES DICKENS 777-jjj Good 32
CHARLES DICKENS 666-hhh Bad 11
W Yeats 888-hhh Ok 12
R Whitely 444-999 Terrible 44
非常感谢您的帮助!
您在PDF中使用等宽字体吗(作为Courier)?它可以解释你在控制台中得到了好的输出,而在PDF 中得到了坏的输出
关于