How to Insert a Linefeed with PDFBox drawString

前端 未结 3 1471
暖寄归人
暖寄归人 2020-12-06 12:05

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


        
3条回答
  •  被撕碎了的回忆
    2020-12-06 12:37

    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 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 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.

提交回复
热议问题