使用 POI 向word文档段落中间插入图片

    /*** 计算图片宽高* @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 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();}}}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部