Search code examples
javams-wordapache-poixwpf

Unable to change orientation of ms-word file(XWPF) using apache poi


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);

Solution

  • 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);