如何通过 apache poi 为整个文档和所有部分设置边距

How to set margin for whole document and all sections by apache poi

我想用 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"));

但只更改了最新的部分,不是所有部分,也不是整个文档。 我应该怎么做才能更改所有部分的边距和整个文档的边距?

如果文档被分成多个部分,那么第一个部分的 SectPr 位于段落内的 PPr 元素中,这些元素是部分分隔符。只有最后一节的 SectPr 直接在 Body 中。所以我们需要遍历所有段落以获得所有 SectPrs.

示例:

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();
 }

}