10

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
Franken
  • 157
  • 2
  • 9

3 Answers3

11

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();
Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54
  • 2
    Does not properly answer the posed question. Clarify how to add non-breaking spaces and I'll lift my downvote. – Samuel Huylebroeck Oct 27 '17 at 09:48
  • 2
    NBSP cannot be used because it occupy space, but I can prevent left-trim by adding a NULL character before the paragraph. Your advice have been very helpful for me. Thank you for your kind answer. Paragraph p = new Paragraph().add("\u0000").add(new Text(" abc")); – Franken Oct 31 '17 at 05:09
  • 1
    For anyone wanting to add null character (C#): `new Paragraph(char.MinValue + " My test string")` This worked in that it kept left trim of string. – Automate This Mar 11 '20 at 22:54
5

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
tienph
  • 1,239
  • 13
  • 19
2

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.