Search code examples
javaapache-poixwpf

Creating word document with Apache Poi 3.17, while creating table if table row ends just before the footer, it is creating another blank page?


I am using Apache POI version 3.17 and want to stick with that version only, due to some other dependency of the application. Table data is dynamic and I can't fix the row height, sometimes when table's last row ends near the footer, it is creating a separate blank page. Could anyone please help me out how to tackle this scenario?

enter image description here

I prefer to prevent the creation of empty pages.


Solution

  • I've found a solution to the problem. The issue arises because Microsoft Word automatically adds a paragraph at the end of a table. This behavior causes a blank page to appear when a table row reaches the end of a page and overflows due to the automatically added paragraph.

    https://www.technewstoday.com/page-wont-delete-in-word/#:~:text=Since%20Word%20automatically%20adds%20a,paragraph%20marker%20that%20Word%20inserted.

    To resolve this issue manually in a Word document, I followed these steps:

    Click on the "Home" tab. Right-click in front of the paragraph marker at the end of the table. Choose the "Paragraph" option from the context menu. In the "Indents and Spacing" tab, set "Before" and "After" fields to 0pt under the "Spacing" section. Set the line spacing to "Exactly" and the "At" value to 0.7pt (minimum).

    Afterward, I applied a similar solution programmatically using the XWPF document instance and the Apache POI library. Here's how I did it:

    XWPFParagraph preventBlankPage = document.createParagraph();
    preventBlankPage.setSpacingAfter(0);
    preventBlankPage.setSpacingBefore(0);
    preventBlankPage.setSpacingBetween(0.1, LineSpacingRule.EXACT);
    

    By adding an empty paragraph after creating the table and then setting the spacing before and after the paragraph to 0pt, as well as spacing between to 0.1pt with line spacing set to "Exactly," I was able to prevent the document application from adding an extra blank page.

    This approach ensures that the table's layout remains consistent and avoids the appearance of unnecessary blank pages in the document.