Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to keep whitespaces before text in iText7?

Tags:

java

itext

itext7

I've added a Text object that start with whitespaces to the Paragraph object,

but the whitespace of paragraph is removed in iText7(7.0.4).

It looks like left trim. Is this a specification of Paragraph?

Is there any way to keep whitespaces before text?

Paragraph p = new Paragraph().add(new Text("  abc")); // Only "abc" appears in pdf
like image 811
Franken Avatar asked Oct 27 '17 08:10

Franken


3 Answers

iText will trim spaces.
But it will not remove non-breaking spaces.

File outputFile = new File(System.getProperty("user.home"), "output.pdf");
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outputFile));
Document layoutDocument = new Document(pdfDocument);

layoutDocument.add(new Paragraph("\u00A0\u00A0\u00A0Lorem Ipsum"));
layoutDocument.add(new Paragraph("Lorem Ipsum"));
layoutDocument.close();
like image 118
Joris Schellekens Avatar answered Nov 19 '22 01:11

Joris Schellekens


Follow steps:

  1. Extend TextRenderer class
  2. Override trimFirst method(but do nothing in it)
  3. Pass an object of this class to Text.setTextRenderer method
like image 45
anirban banerjee Avatar answered Nov 19 '22 00:11

anirban banerjee


I found a solution based on anirban banerjee's answer. I made the following class:

import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.renderer.*;

public class CodeRenderer extends TextRenderer {

    public CodeRenderer(Text textElement) {
        super(textElement);
    }

    @Override
    public IRenderer getNextRenderer() {
        return new CodeRenderer((Text) getModelElement());
    }

    @Override
    public void trimFirst() {}
}

Then I use it like this:

Text text = new Text(string);
text.setNextRenderer(new CodeRenderer(text));
document.add(new Paragraph(text));

The result is that all whitespaces are kept.

like image 1
Wouter Wijsman Avatar answered Nov 19 '22 00:11

Wouter Wijsman