在 Java 中使用 Apache POI XWPF 在同一个 word 文档中横向和纵向页面 [英] Landscape and portrait pages in the same word document using Apache POI XWPF in Java

查看:75
本文介绍了在 Java 中使用 Apache POI XWPF 在同一个 word 文档中横向和纵向页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java 和 Apache POI 库来创建包含一些横向页面和一些纵向页面的 Word 文档.我可以改变所有页面的方向,但有没有办法只改变其中一些页面的方向?我尝试使用不同的部分和正文,但无济于事.

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, but is there a way to change just the orientation of some of them? I have tried using different sections and bodies, but to no avail.

目前我已经编写了一个函数,它将 XWPFDocument 作为输入并更改新主体的方向.我本来希望改变新正文的方向不会影响以前的页面,但会影响整个文档.

At the moment I have written a function that takes a XWPFDocument as input and changes the orientation of a new body. I had hoped changing the orientation for new body would not affect the previous pages, but it affects the entire document.

private void changeOrientation(XWPFDocument document, String orientation){
    CTDocument1 doc = document.getDocument();
    CTBody body = doc.addNewBody();
    body.addNewSectPr();
    CTSectPr section = body.getSectPr();
    if(!section.isSetPgSz()) {
        section.addNewPgSz();
    }
    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));
    }
}

谢谢!

推荐答案

原来需要一个 CTPPr(分节符),可以用以下代码完成:

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.

这篇关于在 Java 中使用 Apache POI XWPF 在同一个 word 文档中横向和纵向页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆