我试图在here的帮助下在单页上设置页面方向,但没有运气。此代码片断会生成一个文档,但它只会将最后一页设置为横向。我无法弄清楚什么是错误的...任何帮助或指导,将不胜感激!
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("FIRST PAGE");
changeOrientation(document, "landscape");
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("SECOND PAGE");
changeOrientation(document, "portrait");
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("THIRD PAGE");
changeOrientation(document, "landscape");
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("FOURTH PAGE");
FileOutputStream fos = new FileOutputStream(new File("C:/test.docx"));
document.write(fos);
fos.close();
}
private static 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.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));
}
}编辑:
这给我document.xml(看起来不正确):
FIRST PAGE
SECOND PAGE
THIRD PAGE
FOURTH PAGE
编辑2:这是用Word创建时document.xml的样子(删除了一些不相关的东西...)。我担心在POI中我足够好,想知道如何让它像这样生成xml:
FIRST PAGE
SECOND PAGE
THIRD PAGE
FOURTH PAGE编辑3:
感谢您的良好指导,但我仍然无法100%发挥作用。我现在已将代码更改为以下内容。但是这会导致设置上一页的方向而不是所需的方向。其余的不正确。
Image that shows the resulting pages
private static void changeOrientation(XWPFDocument document, String orientation, boolean pFinalSection){
CTSectPr section;
if (pFinalSection) {
CTDocument1 doc = document.getDocument();
CTBody body = doc.getBody();
section = body.getSectPr() != null ? body.getSectPr() : body.addNewSectPr();
XWPFParagraph para = document.createParagraph();
CTP ctp = para.getCTP();
CTPPr br = ctp.addNewPPr();
br.setSectPr(section);
} else {
XWPFParagraph para = document.createParagraph();
CTP ctp = para.getCTP();
CTPPr br = ctp.addNewPPr();
section = br.addNewSectPr();
br.setSectPr(section);
}
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));
}
}