Why does using ColumnText result in "The document has no pages" exception?
I want to use ColumnText
to wrap text in a rectangle:
Document document = new Document(PageSize.A4.rotate()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); ColumnText column = new ColumnText(writer.getDirectContent()); column.setSimpleColumn(new Phrase("text is very long ..."), 10, 10, 20, 20, 18, Element.ALIGN_CENTER); column.go(); document.close();
ExceptionConverter: java.io.IOException: The document has no pages.
Do you have any suggestions how to fix this problem?
Posted on StackOverflow on Sep 23, 2014 by Han Kun
I see that you have the following line:
column.go();
You did not use something like this:
int status = column.go();
If you did, and if you examined status
, you would have noticed that the column
object still contained some text.
What text? All the text.
There is a serious error in this line:
column.setSimpleColumn(new Phrase("text is very long ..."), 10, 10, 20, 20, 18, Element.ALIGN_CENTER);
You are trying to add the text "text is very long ..."
into a rectangle with the following coordinates:
float llx = 10;
float lly = 10;
float urx = 20;
float ury = 20;
You didn't define a font, so the font is Helvetica with font size 12pt and you defined a leading of 18pt.
This means that you are trying to fit text that is 12pt heigh with an extra 6pt for the leading into a square that measures 10 by 10 pt. Surely you understand that this can't work!
As a result, nothing is added to the PDF and rather than showing an empty page, iText throws an exception saying: there are no pages! You didn't add any content to the document!
You can fix this, for instance by changing the incorrect line into something like this:
column.setSimpleColumn(new Phrase("text is very long ..."), 36, 36, 559, 806, 18, Element.ALIGN_CENTER);
An alternative would be:
column.setSimpleColumn(rect);
column.addElement(paragraph);
In these two lines rect
is a Rectangle
object. The leading and the alignment are to be defined at the level of the Paragraph
object (in this case, you don't use a Phrase
).