将图片复制到word文档

时间:2016-08-04 15:10:03

标签: java apache-poi

有人可以告诉我如何使用java将图片复制到word文档。香港专业教育学院尝试过代码,但我一直收到一个错误,说文档内容有误。请帮忙。提前谢谢!

1 个答案:

答案 0 :(得分:1)

原则上这很简单,因为您只需使用XWPFRun.addPicture将图片添加到XWPFRun。

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.util.Units;

import org.apache.poi.xwpf.usermodel.*;

public class CreateWordWithImage {

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

  XWPFDocument doc= new XWPFDocument();

  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run=paragraph.createRun();  
  run.setText("The Body:");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();  
  run.setText("Lorem ipsum....");

  run = paragraph.createRun();  
  String imgFile="Koala.png";
  XWPFPicture picture = run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(100), Units.toEMU(100));

  run = paragraph.createRun();  
  run.setText("...Lorem ipsum....");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();  
  run.setText("Lorem ipsum....");

  doc.write(new FileOutputStream("test.docx"));

 }
}