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

时间:2017-09-14 08:38:27

标签: java apache-poi docx

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

但是只更改了最新的部分,而不是所有部分而不是整个文档。 如何更改所有部分'保证金和整个文件的保证金?

1 个答案:

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

}