How to Insert a Linefeed with PDFBox drawString

Francesco picture Francesco · Sep 29, 2011 · Viewed 20.1k times · Source

I have to make a PDF with a Table. So far it work fine, but now I want to add a wrapping feature. So I need to insert a Linefeed.

contentStream.beginText();  
contentStream.moveTextPositionByAmount(x, y);  
contentStream.drawString("Some text to insert into a table.");  
contentStream.endText();  

I want to add a "\n" before "insert". I tried "\u000A" which is the hex value for linefeed, but Eclipse shows me an error.

Is it possible to add linefeed with drawString?

Answer

Lukas picture Lukas · Mar 4, 2013

The PDF format allows line breaks, but PDFBox has no build in feature for line breaks.

To use line breaks in PDF you have to define the leading you want to use with the TL-operator. The T*-operator makes a line break. The '-operator writes the given text into the next line. (See PDF-spec for more details, chapter "Text". It´s not that much.)

Here are two code snippets. Both do the same, but the first snippet uses ' and the second snippet uses 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);
  }
}

Use T* for line break:

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();
}

To get the height of the font you can use this command:

fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;

You might want to multiply it whit some line pitch factor.