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

前端 未结 2 1552
说谎
说谎 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:18

    According to OOXML Specification ECMA-376, Fourth Edition, Part 1 - Fundamentals And Markup Language Reference - 17.6.18 sectPr (Section Properties), in a document with multiple sections, section properties (the sectPr element) are stored as the child element of :

    • the last paragraph in the section, for all sections except the final section,
    • the body element, for the final section.

    So, to change page orientation of a section one should create or locate corresponding sectPr and use following code:

    private void changeOrientation(CTSectPr section, String orientation) {
        CTPageSz pageSize = section.isSetPgSz? section.getPgSz() : section.addNewPgSz();
        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));
        }
    }
    

提交回复
热议问题