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 aChapter
. Take a look at the following snippet:What do you see?
You see a chapter being populated with objects
p1
andp2
. Both objects,p1
andp2
, aren't rendered to thedocument
until the very last line:document.add(chapter);
Only when this line is triggered,p1
is actually added to thedocument
because the document isn't aware of what happens with thechapter
before you add it.This means that
document.newPage()
is triggered beforep1
is rendered, instead of betweenp1
andp2
.To solve this, you need to use the
Chunk.NEXTPAGE
object:That special
Chunk
object is now part of thechapter
object, and a new page will be triggered betweenp1
andp2
.