简体   繁体   English

无法使用apache poi更改ms字文件(XWPF)的方向

[英]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. 我试图在Apache POI中使用XWPF格式创建Word文档。 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. 我使用Java中的Apache POI XWPF在同一个word文档中使用Landscape和portrait页面的现有代码, 在创建文档后对其进行了函数调用,但是抛出了空指针。 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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM