合并2 docx与不同的页眉和页脚

时间:2017-05-05 07:34:11

标签: java apache-poi docx

我有2个(以及更多)docx与différent页眉和页脚,我想合并它们保持不同的页眉和页脚。我使用POI并且我有合并2 docx的代码,问题是最终文件的第二部分(因此要合并的2 docx)没有任何页眉和页脚。

public static void merge(InputStream src1, InputStream src2, OutputStream dest) throws Exception {
    OPCPackage src1Package = OPCPackage.open(src1);
    OPCPackage src2Package = OPCPackage.open(src2);
    XWPFDocument src1Document = new XWPFDocument(src1Package);        
    CTBody src1Body = src1Document.getDocument().getBody();
    XWPFDocument src2Document = new XWPFDocument(src2Package);
    CTBody src2Body = src2Document.getDocument().getBody();        
    appendBody(src1Body, src2Body);
    src1Document.write(dest);
}

private static void appendBody(CTBody src, CTBody append) throws Exception {
    XmlOptions optionsOuter = new XmlOptions();
    optionsOuter.setSaveOuter();
    String appendString = append.xmlText(optionsOuter);
    String srcString = src.xmlText();
    String prefix = srcString.substring(0,srcString.indexOf(">")+1);
    String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
    String sufix = srcString.substring( srcString.lastIndexOf("<") );
    String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
    CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);
    src.set(makeBody);
}

0 个答案:

没有答案