How to identify if a paragraph lands on a page break in Apache POI

3.2k views Asked by At

I currently using Apache POI to create a simple .docx file. The problem is that if a paragraph lands on a page break, I need move that whole paragraph to the next page. The only thing is that I'm not sure how to determine if a paragraph lands on a page break.

Therefore my question is:

Is there a way to determine if a paragraph lands on a page break in Apache POI?

For example:

This paragraph:

enter image description here

Will be recognized as on a page break and will be automatically changed to this:

enter image description here

1

There are 1 answers

6
mustangDC On

This is a sample code, may be not a 100%. Try once and let me know, if I can improve it according to your scenario then definitely will do.

Assuming that you are using an XWPFDocument document class

ExtendedProperties ep = document.getProperties().getExtendedProperties();
int numberOfLines = ep.getUnderlyingProperties().getLines());

The code mentioned above will give you a count of lines in the document, match it with the number of lines you are putting into the document.

For Example:-

  1. Suppose numberOfLines returns 50.

  2. Check the number of lines you are printing in the document using a counter, if you feel the paragraph has arrived and the line count is almost 40, put a break there.

    ExtendedProperties ep = document.getProperties().getExtendedProperties(); int numberOfLines = ep.getUnderlyingProperties().getLines()); XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); //create new run Page n run.setText("TITLE");
    //……………………………Your Logic here……………………………// run.addCarriageReturn(); //separate previous text from break run.addBreak(BreakType.PAGE); //Break the page run.addBreak(BreakType.WORD_WRAPPING); //cancels effect of page break WXPFRun run2 = paragraph.createRun(); //create a new run for pane n+1

Hope it helps to get close to what you need.

Thanks