2

i am trying to create a word document using XWPF format in apache poi. the document requires tables to be created, so i need to set the page orientation to landscape. i used the existing code of Landscape and portrait pages in the same word document using Apache POI XWPF in Java and included a function call for it after creating a document , but its throwing a null pointer exeption. can any one assist me with that. thank you in advance. i used the following code:

private void changeOrientation(XWPFDocument document, String orientation){
    CTDocument1 doc = document.getDocument();
    CTBody body = doc.getBody();
    CTSectPr section = body.addNewSectPr();
    XWPFParagraph para = document.createParagraph();
    CTP ctp = para.getCTP();
    CTPPr br = ctp.addNewPPr();
    br.setSectPr(section);
    CTPageSz pageSize = section.getPgSz();
    if(orientation.equals("landscape")){
        pageSize.setOrient(STPageOrientation.LANDSCAPE);
        pageSize.setW(BigInteger.valueOf(842 * 20));
        pageSize.setH(BigInteger.valueOf(595 * 20));
    }
    else{
        pageSize.setOrient(STPageOrientation.PORTRAIT);
        pageSize.setH(BigInteger.valueOf(842 * 20));
        pageSize.setW(BigInteger.valueOf(595 * 20));
    }
}

Its throwing an error at the line :

pageSize.setOrient(STPageOrientation.LANDSCAPE);
Community
  • 1
  • 1
Mohammed Siddiq
  • 477
  • 4
  • 16

1 Answers1

2

Not all sections will have a Page Size object set on them. You need to check if one is there, and add it if not, before you set the orientation for it

So, you should change the line

    CTPageSz pageSize = section.getPgSz();

To instead be

    CTPageSz pageSize;
    if (section.isSetPgSz()) {
       pageSize = section.getPgSz();
    } else {
       pageSize = section.addNewPgSz();
    }

And on then go on with your calls like

    pageSize.setOrient(STPageOrientation.LANDSCAPE);
Gagravarr
  • 47,320
  • 10
  • 111
  • 156
  • Great, glad that helped! To let others know, please click the tick mark by the question, to "accept" it to mark it as being right – Gagravarr Nov 29 '15 at 19:26