核心代碼
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
public void setLandscape(XWPFDocument doc) {
// 1. 獲取文檔 body
CTDocument1 document = doc.getDocument();
CTBody body = document.getBody();
// 2. 確保節屬性存在
if (!body.isSetSectPr()) {
body.addNewSectPr();
}
CTSectPr section = body.getSectPr();
// 3. 確保頁面尺寸存在
if (!section.isSetPgSz()) {
section.addNewPgSz();
}
CTPageSz pageSize = section.getPgSz();
// 4. 關鍵:必須同時設置寬高和方向
// A4 橫向:寬 29.7cm, 高 21cm (單位:1/20 磅)
pageSize.setW(BigInteger.valueOf(15840)); // 11.9 英寸 * 1440
pageSize.setH(BigInteger.valueOf(12240)); // 8.5 英寸 * 1440
pageSize.setOrient(STPageOrientation.LANDSCAPE);
}
關鍵點解析
| 參數 | 值 | 說明 |
| setW | 15840 | 頁面寬度 (29.7cm = 11.9英寸 × 1440) |
| setH | 12240 | 頁面高度 (21cm = 8.5英寸 × 1440) |
| setOrient | LANDSCAPE | 橫向枚舉值 |
完整示例
public class WordLandscapeDemo {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
// 設置橫向
setLandscape(doc);
// 添加內容
XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun();
run.setText("這是橫向頁面內容");
run.setFontSize(16);
// 保存
try (FileOutputStream out = new FileOutputStream("landscape.docx")) {
doc.write(out);
}
doc.close();
}
}
常見坑點
- ❌ 只設置
setOrient 不設置尺寸 → 無效
- ❌ 尺寸單位錯誤(以為是像素/厘米) → 頁面異常
- ❌ 多節文檔未對每個節設置 → 只有第一頁橫向
多節文檔處理
// 為每個節單獨設置
for (int i = 0; i < doc.getDocument().getBody().sizeOfSectPrArray(); i++) {
CTSectPr sectPr = doc.getDocument().getBody().getSectPrArray(i);
// 對每個 sectPr 重複上述設置...
}