PDF格式允許換行,但PDFBox沒有內置換行功能。
要在PDF中使用換行符,您必須定義要與TL
操作員一起使用的前導符。 T*
-operator進行換行。 '
-operator將給定的文本寫入下一行。 (有關更多詳細信息,請參閱PDF-spec,「文本」一章。沒有那麼多)。
以下是兩個代碼片段。兩者都是一樣的,但第一個代碼段使用'
,第二個代碼段使用T*
。
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);
contentStream.drawString(lines.get(0));
for (int i = 1; i < numberOfLines; i++) {
contentStream.appendRawCommands(escapeString(lines.get(i)));
contentStream.appendRawCommands(" \'\n");
}
contentStream.endText();
}
private String escapeString(String text) throws IOException {
try {
COSString string = new COSString(text);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
string.writePDF(buffer);
return new String(buffer.toByteArray(), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// every JVM must know ISO-8859-1
throw new RuntimeException(e);
}
}
使用T*
爲換行符:
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();
}
可以獲得字體的高度,你可以使用這個命令:
fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight()/1000 * fontSize;
您可能要乘以白衣一些行間距因子。
@Erik:但是'T *'和'''-operator是什麼? pdf-spec對T *說:「移動到下一行的開始處」。並':「移到下一行並顯示一個文本字符串」。但我找不到在pdfBox中使用T *或'的方法。 (而且我不確定我是否理解規範是否正確。) – Lukas