Franken
Franken

Reputation: 177

Is there any way to keep whitespaces before text in 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

Upvotes: 11

Views: 5564

Answers (4)

gab06
gab06

Reputation: 610

What worked for me is adding a "ghost" character (white font) after the white spaces. Like this:

p = new Paragraph("Text: ").setFontSize(10);
        p.add(new Text("some text    ").setUnderline());
        p.add(new Text(".").setFontColor(whiteColor));
        document.add(p);

Upvotes: 0

Wouter Wijsman
Wouter Wijsman

Reputation: 21

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.

Upvotes: 2

anirban banerjee
anirban banerjee

Reputation: 51

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

Upvotes: 5

Joris Schellekens
Joris Schellekens

Reputation: 9022

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

Upvotes: 12

Related Questions