I have a large chapter containing several sections. I need to split one section content to make it more pretty and readable. I tried to use setPageEmpty(false) and newPage() before expected page break but the page doesn't breaks:
Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
writer.setPageEvent(new PageEventHandler(doc));
doc.open();
Chapter chapter = new ChapterAutoNumber("Main info");
chapter.add(new Paragraph("Lorem ipsum dolor sit amet", font));
writer.setPageEmpty(false);
itextDocument.newPage();
After this code I'm going on to fill the chapter content and finally I'm going to write:
doc.add(chapter);
But after first paragraph I need a page break. How to split section content? I use iText 5.5
It doesn't make sense to use the newPage()
method if you want to add a new page inside a Chapter
. Take a look at the following snippet:
Chapter chapter = new ChapterAutoNumber("Main info");
chapter.add(p1);
document.newPage();
chapter.add(p2);
document.add(chapter);
What do you see?
You see a chapter being populated with objects p1
and p2
. Both objects, p1
and p2
, aren't rendered to the document
until the very last line: document.add(chapter);
Only when this line is triggered, p1
is actually added to the document
because the document isn't aware of what happens with the chapter
before you add it.
This means that document.newPage()
is triggered before p1
is rendered, instead of between p1
and p2
.
To solve this, you need to use the Chunk.NEXTPAGE
object:
Chapter chapter = new ChapterAutoNumber("Main info");
chapter.add(p1);
chapter.add(Chunk.NEXTPAGE);
chapter.add(p2);
document.add(chapter);
That special Chunk
object is now part of the chapter
object, and a new page will be triggered between p1
and p2
.