use*_*591 1 java pdf string pdfbox
我正在使用PDF Box格式化问题.我的目标是以表格样式打印PDF作为报告.内容格式类似于
Name Code Description Value
Run Code Online (Sandbox Code Playgroud)
我检索我的数据库结果集并拥有一个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());
Run Code Online (Sandbox Code Playgroud)
输出:
|This is some text with mo|Some text with less. |Some other text. |
Run Code Online (Sandbox Code Playgroud)
我打印出这个列表多次到屏幕:)并通过System.out或logger格式完全按照我的预期,甚至块.
但是,当我发送到PDFBox打印到文件时,格式变为"已损坏",并且"表格格式"不受尊重.我作为x,y co-ords传递100和700.
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 + " TL\n");
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();
}
Run Code Online (Sandbox Code Playgroud)
要获得字体的高度,可以使用以下命令:
fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
Run Code Online (Sandbox Code Playgroud)
用于打印的样本列表:这是在打印到屏幕时使用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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
任何帮助非常感谢!
| 归档时间: |
|
| 查看次数: |
1245 次 |
| 最近记录: |