Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache poi page breaks

I need to create a simple word document for printing from a java program. It is necessary to have the output printed on separate pages. I'm using the following code:

XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("TITLE");
run.addCarriageReturn();
run.setText("some text and stuff here");
run.addBreak(BreakType.PAGE);
run.setText("more text");
run.addCarriageReturn();
run.setText("one more line");

Trouble is, anything I try to insert after this page break appears on its own on a page (the last two lines of text in the above example will appear on different pages). It's as if there is now an 'auto-page-break' after every statement. I've tried using new run, or new paragraph, but the result is always the same. Any ideas? Starting to get very frustrated here....

like image 957
BendyMan Avatar asked Feb 16 '15 10:02

BendyMan


3 Answers

XWPFDocument document = new XWPFDocument();
...
XWPFParagraph paragraph = document.createParagraph();
paragraph.setPageBreak(true);
like image 165
120196 Avatar answered Nov 15 '22 14:11

120196


Have found an answer - not sure it's the best way. It's necessary to add a carriage return after the last line of the page, or it too moves to the next page. Then add Break (WORD_WRAPPING), and start a new run for the next page. (The only problem with this solution is it leaves a blank line at the top of each new page!)

XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("TITLE");
run.addCarriageReturn();
run.setText("some text and stuff here");
run.addCarriageReturn();                 //separate previous text from break
run.addBreak(BreakType.PAGE);
run.addBreak(BreakType.WORD_WRAPPING);   //cancels effect of page break
WXPFRun run2 = paragraph.createRun();    //create new run
run2.setText("more text");
run2.addCarriageReturn();
run2.setText("one more line");
like image 30
BendyMan Avatar answered Nov 15 '22 15:11

BendyMan


XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Text");
run.addBreak(BreakType.PAGE);
XWPFRun run2 = paragraph.createRun();
run.setText("Another text");
like image 1
ilhan Avatar answered Nov 15 '22 15:11

ilhan