El formato PDF permite saltos de línea, pero PDFBox no tiene función de compilación para saltos de línea.
Para usar saltos de línea en PDF, debe definir la guía que desea usar con el operador TL
. El operador T*
hace un salto de línea. El operador '
escribe el texto dado en la siguiente línea. (Consulte la especificación PDF para obtener más información, capítulo "Texto". No es mucho).
Aquí hay dos fragmentos de código. Ambos hacen lo mismo, pero el primer fragmento usa '
y el segundo fragmento usa 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);
}
}
Uso T*
de salto de línea:
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();
}
para obtener la altura de la fuente que puede utilizar este comando:
fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight()/1000 * fontSize;
Es posible que desee multiplicarlo pizca de algún paso de línea factor.
@Erik: ¿Pero qué pasa con el operador 'T *' - y '' '? pdf-spec dice a T *: "Mover al inicio de la siguiente línea". Y a ': "Mover a la siguiente línea y mostrar una cadena de texto". Pero no pude encontrar una forma de usar T * o 'en pdfBox. (Y no estoy seguro de si entendí la especificación correcta o no). – Lukas