Reputation: 177
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
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
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
Reputation: 51
Follow steps:
Upvotes: 5
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