其實在原本下載包裡的範例就已經寫得很棒了!
(基本上也只是整個copy過來,加一點變數處理)
PS: 這是使用 3.14 版的,我是知道在 3.10 是跑不出來的
為了自己方便,我加了個 scale,去縮放/限制圖檔的大小
protected void addImageIntoDocx(XWPFRun r, String imgFile, String scale) throws Exception { File img = new File(imgFile); if(!img.exists() || img.isDirectory()) { throw new Exception("Image not found:"+imgFile); } int format; if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF; else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF; else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT; else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG; else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG; else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB; else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF; else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF; else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS; else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP; else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG; else { String err = "Unsupported picture: " + imgFile + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg"; throw new Exception(err); } BufferedImage bimg = ImageIO.read(img); int w = bimg.getWidth(); int h = bimg.getHeight(); double ratio = h*1d/w; try { int wmax = Integer.parseInt(scale); if(w < wmax) { ; } else { w = wmax; h = (int)Math.round(w*ratio); } } catch(Exception e) { w = 200; h = (int)Math.round(w*ratio); } //r.addBreak(); r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(w), Units.toEMU(h)); //r.addBreak(BreakType.PAGE); }
沒有留言:
張貼留言