我在一个Java项目中使用ApachePOI。我在一个横向页面上工作过,代码如下:
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;
if (section.isSetPgSz ()) {
pageSize = section.getPgSz ();
} else {
pageSize = section.addNewPgSz ();
}
pageSize.setOrient (STPageOrientation.LANDSCAPE);
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));
}
}
我在创建文档后调用该方法
private void dipl()
{
XWPFDocument document = new XWPFDocument ();
String landscape = "landscape";
changeOrientation (document, landscape);
} // ......
问题是Word在横向页面之前的文档开头显示空白的纵向页面。那么,如何避免创建空白页面呢?
Word
文档的默认节属性仅在正文中设置,而不是在段落中设置。如果节属性在段落中,则这是其他节的属性,例如,如果文档包含横向部分和纵向部分。
创建仅具有横向格式信纸大小的Word
文档的最小工作示例是:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
public class CreateWordLandscape {
public static void main(String[] args) throws Exception {
XWPFDocument document= new XWPFDocument();
CTDocument1 ctDocument = document.getDocument();
CTBody ctBody = ctDocument.getBody();
CTSectPr ctSectPr = (ctBody.isSetSectPr())?ctBody.getSectPr():ctBody.addNewSectPr();
CTPageSz ctPageSz = (ctSectPr.isSetPgSz())?ctSectPr.getPgSz():ctSectPr.addNewPgSz();
ctPageSz.setOrient(STPageOrientation.LANDSCAPE);
//paper size letter
ctPageSz.setW(java.math.BigInteger.valueOf(Math.round(11 * 1440))); //11 inches
ctPageSz.setH(java.math.BigInteger.valueOf(Math.round(8.5 * 1440))); //8.5 inches
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
FileOutputStream out = new FileOutputStream("CreateWordLandscape.docx");
document.write(out);
out.close();
document.close();
}
}