Why does using ColumnText result in "The document has no pages" exception?
I want to use ColumnText to wrap text in a rectangle, but it tells me the document has no pages.
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(); pdfDoc.close();
}
When I run this code, I get the following error: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
You are trying to add the text into a rectangle which is too small. 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!
There is no ColumnText
class in iText 7, but be careful when specifying the area for adding content through Canvas
:
public void manipulatePdf(String dest) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
pdfDoc.addNewPage();
Paragraph p = new Paragraph("text is very long...");
Rectangle rootArea = new Rectangle(120, 700, 10, 10);
PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
new Canvas(canvas, pdfDoc, rootArea).add(p);
canvas.rectangle(rootArea);
canvas.stroke();
pdfDoc.close();
}
The rootArea
is a too small Rectangle
, so the Paragraph
won’t be added. Anyway you won’t get No Pages exception, because it’s necessary to create at least one page in the PdfDocument
before using PdfCanvas
instance.
Another approach is to use ColumnDocumentRenderer
: public void manipulatePdf(String dest) throws IOException { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); Document doc = new Document(pdfDoc); Rectangle[] columns = {new Rectangle(120, 700, 10, 10)}; doc.setRenderer(new ColumnDocumentRenderer(doc, columns)); doc.add(new Paragraph("the text is very long...")); doc.close(); }
You define an array of columns where you want the content to appear and then use add()
method as usual. In the code above the Paragraph
does not fit the Rectangle
, so nothing will be added to the document.