I have an issue with the itext library that can be described as follow :
I want to put a vertical space between two paragraphs by using the spacingBefore property on the second paragraph.
The problem is that from a certain value of space units (by default point unit), itext causes the second paragraph to be displayed on a new page even though there is obviously enough space to put the 2 paragraphs on the same page.
This code illustrates this situation :
public static void main(String[] args) throws Exception {
Document document = new Document();
OutputStream result = new FileOutputStream("output.pdf");
PdfWriter.getInstance(document, result);
document.open();
Paragraph paragraph1 = new Paragraph("First paragraph");
Paragraph paragraph2 = new Paragraph("Second paragraph");
//380 causes the new page...
paragraph2.setSpacingBefore(380f);
//...whereas 370 does not
// paragraph2.setSpacingBefore(370f);
document.add(paragraph1);
document.add(paragraph2);
document.close();
}
Does someone hava an explication of this strange behaviour?
Thanks in advance
I have copied your code into a standalone example. You can find this example here: ParagraphSpacingBefore
public void createPdf(String filename) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
Paragraph paragraph1 = new Paragraph("First paragraph");
Paragraph paragraph2 = new Paragraph("Second paragraph");
paragraph2.setSpacingBefore(380f);
document.add(paragraph1);
document.add(paragraph2);
document.close();
}
I don't think this is different from what you're doing, but in my case, the two paragraphs are on a single page. Please check paragraph_spacebefore.pdf to find out for yourself.
Maybe you are also applying a spacing before to paragraph1
or maybe you are using an old version of iText (e.g. 2.1.7, a version that is obsolete and should no longer be used) or maybe you are using an unofficial version of iText (e.g. iText 4, a version that is created by a third party and of which no one knows if it's even legal to use).
In short: the problem can't be explained because the problem can't be reproduced.
As stated by Bruno, I was using an "old" buggy version of itext : 5.1.2 released in 2012. This bug was fixed by version 5.5.1 as mentionned in the changelog http://itextpdf.com/changelog/551 :
Bugfix regarding spacing before and after when a new page is created.
When using a newer version, everthing works just fine :)