java中使用poi實現合並word文檔,兼容圖片的合並並分頁


最近需要做一個java合並wrod的實現方法,網上查了看看發現有的方法word里的圖片沒辦法正確的合並到目標文件。后來又查了下,綜合了一下自己寫了個測試方法,順手記了一下。

package com.fosung.pb.develop.report.service;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class test {
    public static void main (String[] args) throws Exception {

        File newFile = new File("f:\\張三_發展黨員紀實材料.docx");
        List<File> srcfile = new ArrayList<>();
        File file1 = new File("F:\\report\\step3\\substep7.docx");
        File file2 = new File("F:\\report\\step3\\substep9.docx");
        File file3 = new File("F:\\report\\step3\\substep9-4.docx");
        File file4 = new File("F:\\report\\step2\\substep3.docx");
        srcfile.add(file2);
        srcfile.add(file1);
        srcfile.add(file3);
        srcfile.add(file4);
        try {
            OutputStream dest = new FileOutputStream(newFile);
            ArrayList<XWPFDocument> documentList = new ArrayList<>();
            XWPFDocument doc = null;
            for (int i = 0; i < srcfile.size(); i++) {
                FileInputStream in = new FileInputStream(srcfile.get(i).getPath());
                OPCPackage open = OPCPackage.open(in);
                XWPFDocument document = new XWPFDocument(open);
                documentList.add(document);
            }
            for (int i = 0; i < documentList.size(); i++) {
                doc = documentList.get(0);
                if(i != 0){
                    documentList.get(i).createParagraph().setPageBreak(true);
                    appendBody(doc,documentList.get(i));
                }
            }
            doc.createParagraph().setPageBreak(true);
            doc.write(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
        CTBody src1Body = src.getDocument().getBody();
        CTBody src2Body = append.getDocument().getBody();

        List<XWPFPictureData> allPictures = append.getAllPictures();
        // 記錄圖片合並前及合並后的ID
        Map<String,String> map = new HashMap();
        for (XWPFPictureData picture : allPictures) {
            String before = append.getRelationId(picture);
            //將原文檔中的圖片加入到目標文檔中
            String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
            map.put(before, after);
        }

        appendBody(src1Body, src2Body,map);

    }

    private static void appendBody(CTBody src, CTBody append,Map<String,String> map) 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("<"));

        if (map != null && !map.isEmpty()) {
            //對xml字符串中圖片ID進行替換
            for (Map.Entry<String, String> set : map.entrySet()) {
                addPart = addPart.replace(set.getKey(), set.getValue());
            }
        }
        //將兩個文檔的xml內容進行拼接
        CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);

        src.set(makeBody);
    }
}

 

剛開始合並后遇到了一個問題,就是合並完word后,所有表格都緊緊挨在了一起,沒有分頁。后來加上了分頁符

documentList.get(i).createParagraph().setPageBreak(true);實現了分頁效果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM