我想通过apache-poi编辑整个文档页边距,我想要更改所有部分。这是我的代码:
XWPFDocument docx = new XWPFDocument(OPCPackage.open("template.docx"));
CTSectPr sectPr = docx.getDocument().getBody().getSectPr();
CTPageMar pageMar = sectPr.getPgMar();
pageMar.setLeft(BigInteger.valueOf(1200L));
pageMar.setTop(BigInteger.valueOf(500L));
pageMar.setRight(BigInteger.valueOf(800L));
pageMar.setBottom(BigInteger.valueOf(1440L));
docx.write(new FileOutputStream("test2.docx"));
但是只更改了最新的部分,而不是所有部分而不是整个文档。 如何更改所有部分'保证金和整个文件的保证金?
答案 0 :(得分:2)
如果文档被分成多个部分,则第一部分的SectPr
位于段落中的PPr
个元素中,这些元素是节分隔符。只有最后一部分的SectPr
直接位于Body
内。因此,我们需要循环遍历所有段落以获取所有SectPr
s。
示例:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import java.util.List;
import java.util.ArrayList;
import java.math.BigInteger;
public class WordGetAllSectPr {
public static List<CTSectPr> getAllSectPr(XWPFDocument document) {
List<CTSectPr> allSectPr = new ArrayList<>();
for (XWPFParagraph paragraph : document.getParagraphs()) {
if (paragraph.getCTP().getPPr() != null && paragraph.getCTP().getPPr().getSectPr() != null) {
allSectPr.add(paragraph.getCTP().getPPr().getSectPr());
}
}
allSectPr.add(document.getDocument().getBody().getSectPr());
return allSectPr;
}
public static void main(String[] args) throws Exception {
XWPFDocument docx = new XWPFDocument(new FileInputStream("template.docx"));
List<CTSectPr> allSectPr = getAllSectPr(docx);
System.out.println(allSectPr.size());
for (CTSectPr sectPr : allSectPr) {
CTPageMar pageMar = sectPr.getPgMar();
pageMar.setLeft(BigInteger.valueOf(1200L));
pageMar.setTop(BigInteger.valueOf(500L));
pageMar.setRight(BigInteger.valueOf(800L));
pageMar.setBottom(BigInteger.valueOf(1440L));
}
docx.write(new FileOutputStream("test2.docx"));
docx.close();
}
}