import java.io.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.*;
public class InsertPic {
/**java实现往已有内容word文档中追加图片功能简单实现
* @param args
* @throws IOException
* @throws InvalidFormatException
*/
public static void main(String[] args) throws IOException, InvalidFormatException {
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\49611\\Desktop\\t.docx");//读取目标文件路径
XWPFDocument docx = new XWPFDocument(fileInputStream);
XWPFParagraph par = docx.createParagraph();
XWPFRun run = par.createRun();
InputStream pic = new FileInputStream("C:\\Users\\49611\\Desktop\\HT.jpg");//插入图片路径1
byte [] picbytes = IOUtils.toByteArray(pic);
run.addPicture(new ByteArrayInputStream(picbytes), Document.PICTURE_TYPE_GIF, "", 6061200,3858000 );// 宽 高
FileOutputStream out = new FileOutputStream("C:\\Users\\49611\\Desktop\\t.docx");
run.setText(" 图1");//插入图片底部文字
run.setFontSize(13);
run.setCapitalized(true);
pic = new FileInputStream("C:\\Users\\49611\\Desktop\\MT.jpg");//插入图片路径2
picbytes = IOUtils.toByteArray(pic);
run.addPicture(new ByteArrayInputStream(picbytes), Document.PICTURE_TYPE_GIF, "", 6061200,3858000 );// 宽 高
out = new FileOutputStream("C:\\Users\\49611\\Desktop\\t.docx");
run.setText(" 图2");
run.setFontSize(13);
run.setCapitalized(true);
docx.write(out);
out.close();
pic.close();
System.out.println("sucess!!");
}
}