2016-09-24 5 views
1

Мне нужна помощь, заменив изображение другим изображением в Word с помощью Apache POI или любой другой библиотеки, которая могла бы выполнять эту работу. Я знаю, как заменить слово с помощью Apache POI, но я не могу понять, как заменить изображение.Замените образ Apache POI

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

    String c22 = "OTHER WORD"; 

    try { 
     XWPFDocument doc = new XWPFDocument(OPCPackage.open("imagine.docx")); 
     for (XWPFParagraph p : doc.getParagraphs()) { 
      List<XWPFRun> runs = p.getRuns(); 
      if (runs != null) { 
       for (XWPFRun r : runs) { 
        String text = r.getText(0); 
        if (text != null) { 
         String imgFile = "imaginedeschis.jpg"; 
         try (FileInputStream is = new FileInputStream(imgFile)) { 
          r.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, 
              Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels 
          text = text.replace("1ST WORD", c22); 
         } // 200x200 pixels 
         r.setText(text, 0); 
        } 
       } 
      } 
     }  
     doc.write(new FileOutputStream("output.docx")); 
    } catch (InvalidFormatException | IOException m){ } 
} 

ответ

1

Я использую ниже код Java для замены одного изображения в документе Word (* .docx). Пожалуйста, поделитесь, если у кого-то есть лучший подход.

public XWPFDocument replaceImage(XWPFDocument document, String imageOldName, String imagePathNew, int newImageWidth, int newImageHeight) throws Exception { 
    try { 
     LOG.info("replaceImage: old=" + imageOldName + ", new=" + imagePathNew); 

     int imageParagraphPos = -1; 
     XWPFParagraph imageParagraph = null; 

     List<IBodyElement> documentElements = document.getBodyElements(); 
     for(IBodyElement documentElement : documentElements){ 
      imageParagraphPos ++; 
      if(documentElement instanceof XWPFParagraph){ 
       imageParagraph = (XWPFParagraph) documentElement; 
       if(imageParagraph != null && imageParagraph.getCTP() != null && imageParagraph.getCTP().toString().trim().indexOf(imageOldName) != -1) { 
        break; 
       } 
      } 
     } 

     if (imageParagraph == null) { 
      throw new Exception("Unable to replace image data due to the exception:\n" 
        + "'" + imageOldName + "' not found in in document."); 
     } 
     ParagraphAlignment oldImageAlignment = imageParagraph.getAlignment(); 

     // remove old image 
     document.removeBodyElement(imageParagraphPos); 

     // now add new image 

     // BELOW LINE WILL CREATE AN IMAGE 
     // PARAGRAPH AT THE END OF THE DOCUMENT. 
     // REMOVE THIS IMAGE PARAGRAPH AFTER 
     // SETTING THE NEW IMAGE AT THE OLD IMAGE POSITION 
     XWPFParagraph newImageParagraph = document.createParagraph();  
     XWPFRun newImageRun = newImageParagraph.createRun(); 
     //newImageRun.setText(newImageText); 
     newImageParagraph.setAlignment(oldImageAlignment); 
     try (FileInputStream is = new FileInputStream(imagePathNew)) { 
      newImageRun.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imagePathNew, 
         Units.toEMU(newImageWidth), Units.toEMU(newImageHeight)); 
     } 

     // set new image at the old image position 
     document.setParagraph(newImageParagraph, imageParagraphPos); 

     // NOW REMOVE REDUNDANT IMAGE FORM THE END OF DOCUMENT 
     document.removeBodyElement(document.getBodyElements().size() - 1); 

     return document; 
    } catch (Exception e) { 
     throw new Exception("Unable to replace image '" + imageOldName + "' due to the exception:\n" + e); 
    } finally { 
     // cleanup code 
    } 
} 

https://bitbucket.org/wishcoder/java-poi-word-document/wiki/Home Пожалуйста, посетите другие примеры, как:

  • Открыть существующий документ Microsoft Word (* .docx)
  • Clone таблицы в документ Word и добавить новые данные в таблицу клонированного
  • Update существующие таблицы-> Данные ячейки в документе
  • Обновление существующей гиперссылки в документе
  • R замените существующее изображение в документе
  • Сохранить документ Microsoft Word (* .docx)