開發的時候遇到的問題,特此記錄一下
使用Apache POI(Java庫)刪除Word文檔中的空白頁時,需針對不同場景處理。以下是具體實現方法和代碼示例:
- 基礎刪除(段落/分頁符)?
通過刪除多余段落標記或分頁符實現:
XWPFDocument doc = new XWPFDocument(new FileInputStream(“input.docx”));
List paragraphs = doc.getParagraphs();
for (XWPFParagraph para : paragraphs) {
if (para.getText().trim().isEmpty()) {
doc.removeBodyElement(doc.getPosOfParagraph(para));
}
}
FileOutputStream out = new FileOutputStream(“output.docx”);
doc.write(out);
適用于簡單空白頁(由空段落引起)?
- 處理分節符/分頁符?
顯式刪除分節符或分頁符:
for (XWPFSection sect : doc.getSections()) {
if (sect.getParagraphs().isEmpty()) {
doc.removeBodyElement(doc.getPosOfSection(sect));
}
}
需結合CTP和CTSectPr處理XML底層標簽?
- 表格后的空白頁?
調整段落行距以隱藏不可刪的標記:
XWPFParagraph lastPara = doc.getLastParagraph();
if (lastPara != null) {
lastPara.setSpacingBetween(1, LineSpacingRule.EXACT);
}
解決表格末尾自動生成的段落標記導致的空白頁?
- 批量替換(高級)?
使用正則替換刪除隱藏符號:
Pattern pattern = Pattern.compile(“(\f|\b\s{2,}\b)”);
for (XWPFParagraph para : paragraphs) {
String text = para.getText();
text = pattern.matcher(text).replaceAll(“”);
para.replaceText(text);
}
處理分頁符(\f)和連續空格?
注意事項?
有些方法會把插入的圖片也會當空白頁一起清掉,注意多測試!