/**
* 计算图片宽高
* @param picPath
* @return
*/
public static int[] getPictureWidthAndHeght(String picPath) {
int[] sizeArray = new int[2];
BufferedImage bf = null;
try {
bf = ImageIO.read(new File(picPath));
int width = bf.getWidth();
int height = bf.getHeight();
int widthEMU = Units.toEMU(width);
int heightEMU = Units.toEMU(height);
if (widthEMU / 360000 > 16) {
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumFractionDigits(0);
f.setRoundingMode(RoundingMode.UP);
//获取图片的EMU和图片在文档中最大EMU的比例值
double d = widthEMU / (360000 * 14d);
//根据比例值计算得出适合文档的最大EMU数值
widthEMU = Integer.parseInt(f.format(widthEMU / d).replace(",", ""));
heightEMU = Integer.parseInt(f.format(heightEMU / d).replace(",", ""));
sizeArray[0] = widthEMU;
sizeArray[1] = heightEMU;
}
} catch (IOException e) {
e.printStackTrace();
}
return sizeArray;
}
word中插入图片
public static void main(String[] args) throws IOException {
String docName = "段落中间插入图片.docx";
String wordFilePath = "E:\\word\\";
String wordOutPutPath = "E:\\word\\output\\";
// 图片地址
String picturePath = "E:\\word\\abc.png";
InputStream is = null;
FileOutputStream fos = null;
InputStream pis = null;
int parentParagraphNum = 3; // 指定图片插入的段落
try {
is = new FileInputStream(wordFilePath + docName);
pis = new FileInputStream(picturePath);
XWPFDocument doc = new XWPFDocument(is);
List<XWPFParagraph> paragraphs = doc.getParagraphs();
for (int i = 0; i < paragraphs.size(); i++) {
if (i == parentParagraphNum) {
XWPFParagraph lastParagraph = paragraphs.get(i);
XmlCursor cursor = lastParagraph.getCTP().newCursor();
XWPFParagraph newPara = doc.insertNewParagraph(cursor);
XWPFRun newParaRun = newPara.createRun();
newParaRun.addBreak();
newParaRun.addBreak();
newParaRun.addBreak();
newParaRun.addBreak();
newParaRun.addBreak();
newParaRun.addBreak();
newParaRun.addBreak();
newParaRun.addBreak();
int[] sizeArray = WordUtil.getPictureWidthAndHeght(picturePath);
newParaRun.addPicture(pis, XWPFDocument.PICTURE_TYPE_PNG, picturePath, sizeArray[0], sizeArray[1]);
}
}
fos = new FileOutputStream(wordOutPutPath + docName);
doc.write(fos);
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
}
}