Landscape and portrait pages in the same word document using Apache POI XWPF in Java

前端 未结 2 1582
说谎
说谎 2021-01-26 07:01

I am trying to use Java and the Apache POI library to create a word document that contained some landscape and some portrait pages. I can change the orientation of all the pages

2条回答
  •  情话喂你
    2021-01-26 07:26

    Turns out a CTPPr (a section break) is needed, which can be done with 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));
        }
    }
    

    However, this only works once, so pages can't alternate orientations. It has to be all the landscape pages first and portrait last or vice versa.

提交回复
热议问题