如何为apache poi设置整个文档和所有部分的保证金

问题描述:

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

但是只有最新的部分被改变了,并不是所有的部分都不是整个文件。 我应该怎么做才能更改所有章节的保证金和整个文档的保证金?

+0

@Punit你的编辑介绍无用的降价和新的错误;今后请在编辑时尝试修复所有*问题,并仔细检查所有更改是否正确。 OP:请只接受实际让您的帖子更好的修改。 –

+0

你说得对。我错误地接受了编辑,之后我感到后悔。谢谢。 @Baum mit Augen –

如果文档被分割成几个部分,则第一部分的SectPr s位于段落分隔符段落内的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(); 
} 

}