1.在pom.xml文件中导入poi-tl:
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.9.1</version>
</dependency>
2.编写测试类:
package com.mischen.mapreduce.wordcount;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
/**
* @ClassName TestMergeWord
* @Description DOTO
* @Author mischen
* @Date 2021/5/13 0013 23:16
* @Version 1.0
**/
public class TestMergeWord {
public static void main(String[] args) throws Exception{
/* NiceXWPFDocument main = new NiceXWPFDocument(new FileInputStream("C:\\Users\\Administrator\\Desktop\\PMP\\pmp记忆知识点.docx"));
NiceXWPFDocument sub = new NiceXWPFDocument(new FileInputStream("C:\\Users\\Administrator\\Desktop\\PMP\\zookpeer.docx"));
// 合并两个文档
NiceXWPFDocument newDoc = main.merge(sub);
// 生成新文档
FileOutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\PMP\\new_doc.docx");
newDoc.write(out);
newDoc.close();
out.close();*/
XWPFDocument doc = new XWPFDocument(new FileInputStream("C:\\Users\\Administrator\\Desktop\\PMP\\new_doc.docx"));
// 段落
List<XWPFParagraph> paragraphs = doc.getParagraphs();
InputStream stream = new FileInputStream("C:\\Users\\Administrator\\Pictures\\Saved Pictures\\稳定就业证明模板.png");
int length=paragraphs.size();
XWPFRun run = paragraphs.get(length-1).createRun();
run.addPicture(stream, XWPFDocument.PICTURE_TYPE_PNG, "Generated", Units.toEMU(256), Units.toEMU(256));
FileOutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\PMP\\2.docx");
doc.write(out);
out.close();
System.out.println("合并word成功!");
}
}
需要注意的是,在上面的测试类中,路径下面的文档是必须真实存在的,图片也是要真实存在的,paragraphs.get(length-1).createRun()这个表示
读取最后一个段落,run.addPicture(stream, XWPFDocument.PICTURE_TYPE_PNG, "Generated", Units.toEMU(256), Units.toEMU(256)); 表示往最后一个段落
里面添加一张图片,最后将文档输出为2.docx