我在Java项目中使用Apache POI。我使用以下代码在风景页面上工作:
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在文档的开头在横向页面之前显示空白的纵向页面。 因此,如何避免创建空白页?
答案 0 :(得分:2)
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();
}
}