通过docx4j完美合并docx

一开始有这个需求,是想转成html合成pdf这样做,没想到转了之后格式错误,不得不停止,几经搜索,知道有docx4j

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.Iterator;  
import java.util.List;  

import org.apache.commons.io.IOUtils;  
import org.docx4j.jaxb.Context;  
import org.docx4j.openpackaging.exceptions.Docx4JException;  
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;  
import org.docx4j.openpackaging.parts.PartName;  
import org.docx4j.openpackaging.parts.WordprocessingML.AlternativeFormatInputPart;  
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;  
import org.docx4j.relationships.Relationship;  
import org.docx4j.wml.CTAltChunk;  


public class DocxUtil {  



/** 
 * 合并docx 
 * @param streams 
 * @return 
 * @throws Docx4JException 
 * @throws IOException 
 */  
public static InputStream mergeDocx(final List<InputStream> streams) throws Docx4JException, IOException {  

    WordprocessingMLPackage target = null;  
    final File generated = File.createTempFile("generated", ".docx");  

    int chunkId = 0;  
    Iterator<InputStream> it = streams.iterator();  
    while (it.hasNext()) {  
        InputStream is = it.next();  
        if (is != null) {  
            if (target == null) {  
                // Copy first (master) document  
                OutputStream os = new FileOutputStream(generated);  
                os.write(IOUtils.toByteArray(is));  
                os.close();  

                target = WordprocessingMLPackage.load(generated);  
            } else {  
                // Attach the others (Alternative input parts)  
                insertDocx(target.getMainDocumentPart(), IOUtils.toByteArray(is), chunkId++);  
            }  
        }  
    }  

    if (target != null) {  
        target.save(generated);  
        return new FileInputStream(generated);  
    } else {  
        return null;  
    }  
}  

// 插入文档  
private static void insertDocx(MainDocumentPart main, byte[] bytes, int chunkId) {  
    try {  
        AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(  
                new PartName("/part" + chunkId + ".docx"));  
        // afiPart.setContentType(new ContentType(CONTENT_TYPE));  
        afiPart.setBinaryData(bytes);  
        Relationship altChunkRel = main.addTargetPart(afiPart);  

        CTAltChunk chunk = Context.getWmlObjectFactory().createCTAltChunk();  
        chunk.setId(altChunkRel.getId());  

        main.addObject(chunk);  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

public static void main(String[] args) {
List li=new ArrayList();
for (int i = 0; i < urls.size(); i++) {
URL url = new URL(urls.get(i));
URLConnection conn = url.openConnection();// 打开链接
InputStream is = conn.getInputStream();// 获取数据流
li.add(is);
}
InputStream input=DocxUtil.mergeDocx(li);
byte[] buffer = new byte[256];
int b= 0;
while((b=input.read(buffer)) != -1){
//4.写到输出流(out)中
out.write(buffer,0,b);
}
}


//附上原来用zip做的,1个zip包里多个doc,用起来很难受  
OutputStream out = response.getOutputStream();  
                    response.setCharacterEncoding("utf-8");  
                    response.setContentType("application/zip");  
                    response.setHeader("Content-disposition",  
                            "attachment;filename=" + new String((groupNum+"wordword").toString().getBytes("utf-8"), "ISO-8859-1")  
                                + ".zip");  
                    StringBuilder entryname = null;   
                    ZipEntry tempEntry = null;  
                    ZipOutputStream tempZStream = new ZipOutputStream(new BufferedOutputStream(out));  
                    try {  
                        int i = 0;  
                        int b = 0;    
                        byte[] buffer = new byte[512];  
                        for (InputStream input : li) {  

                            entryname = new StringBuilder("");  
                            entryname.append(  mapList.get(i).get("XM")+"-"+"wordwordzip").append(".docx");  
                            tempEntry = new ZipEntry(entryname.toString());  
                            tempEntry.setMethod(ZipEntry.DEFLATED);  
//                          tempEntry.setSize((long) letterInfo.length);  
                            tempZStream.putNextEntry(tempEntry);  
                            while ((b=input.read(buffer)) != -1){    
                                //4.写到输出流(out)中    
                                tempZStream.write(buffer,0,b);    
                            }  
                            i++;  
                        }
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值