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
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();
Follow steps:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With