New page within chapter in iText

南笙酒味 提交于 2019-12-12 03:44:14

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/41998669/new-page-within-chapter-in-itext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!