Gopika Ravikumar
Gopika Ravikumar

Reputation: 21

Extra page added while creating sections in word using docx4j

I am trying to create a word document and split into different sections so that I can apply different headers and orientation to different sections. I was able to create sections but an extra section with no content is getting created at the end of the document. How can I remove this? These are my different sections.

Section #1: section 1

Section #2: section 2

Last section: last section

In the last section, there is an extra page after the section break which I am trying to remove.

This is the code I used for creating sections

  ObjectFactory factory = Context.getWmlObjectFactory();
  P sectionParagraph = factory.createP();
        wordprocessingMLPackage.getMainDocumentPart().getJaxbElement().getBody().getContent().add(sectionParagraph);

  // Create the section properties (SectPr) for the new section
  SectPr sectPr = factory.createSectPr();
  SectPr.Type sectPrType = factory.createSectPrType();
  sectPrType.setVal("nextPage");

  sectPr.setType(sectPrType);

  SectPr.PgSz pageSz = factory.createSectPrPgSz();
  pageSz.setOrient(STPageOrientation.PORTRAIT);
  sectPr.setPgSz(pageSz);

  // Attach the section properties to the paragraph
  sectionParagraph.setPPr(factory.createPPr());
  sectionParagraph.getPPr().setSectPr(sectPr);

I added this code to places where the different sections are supposed to end.

Upvotes: 2

Views: 60

Answers (1)

Gopika Ravikumar
Gopika Ravikumar

Reputation: 21

I was able to solve this by attaching the sectPr of the last section to the document instead of a paragraph.

    SectPr sectPr = factory.createSectPr();
    SectPr.Type sectPrType = factory.createSectPrType();
    sectPrType.setVal("nextPage");

    sectPr.setType(sectPrType);

    wordprocessingMLPackage.getMainDocumentPart().getJaxbElement().getBody().setSectPr(sectPr);

Upvotes: 0

Related Questions