2017-09-14 22 views
0

我想通過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 –

回答

2

如果文檔被分割成幾個部分,則第一部分的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(); 
} 

} 
相關問題