aspose官網:https://apireference.aspose.com/words/java/com.aspose.words/Shape
參考文章:https://blog.csdn.net/pingnanlee/article/details/103596823
public void replaceWordImageWithSrc(){ try { Document srcDoc = new Document("C:\\Users\\Downloads\\1617000207075.docx"); DocumentBuilder builder=new DocumentBuilder(srcDoc); List<Shape> shapeList = Arrays.stream(builder.getDocument().getChildNodes(NodeType.SHAPE, true).toArray()) .filter(Shape.class::isInstance) .map(Shape.class::cast) .collect(Collectors.toList()); for (Shape shape : shapeList) { if (shape.getShapeType() == ShapeType.IMAGE){ builder.moveTo(shape); // 獲取這張圖片的 byte[] 數據 byte[] imageBytes = shape.getImageData().getImageBytes(); // 將byte[] 數據存到文件服務器並返回對應的圖片文件url String imgaeBase64Str = Base64.getMimeEncoder().encodeToString(imageBytes); // 獲取圖片的尺寸 double width = shape.getWidth(); double height = shape.getHeight(); // 獲取圖片的後綴名, 存儲時可能會用到 String imageSuffix = FileFormatUtil.imageTypeToExtension(shape.getImageData().getImageType()); // 此處省略存儲圖片文件的操作,我的操作是將 byte[] imageBytes 轉爲base64,然後再進行存儲,最後得到一個img標籤 String imageUrl ="<img src='http://localhost:8080/image/123.png' heigth='123' width='321'>"; // img標籤寫到這個位置,注意,這裏我用的不是 builder.insertHtml,因爲我將圖片替換成對應的url後,後續還要操作word,如果是直接保存成word文檔的話,可以使用builder.insertHtml // builder.write 好像有個坑,如果參數裏含有中文符號的話,會有word的格式的,類似如下 // "<img src='http://localhost:8080/image/‘<p>壁紙</p>.png' heigth='123' width='321'>" builder.write(imageUrl); // 移走圖片 shape.remove(); /** * 原本想通過先處理word文檔上所有的圖片,將圖片存到文件服務器上,並用對應的圖片路徑url替換原文檔中圖片數據 * (具體而言就是通過 builder.insertHtml(url) url="<img src = 'http://localhost/pic123456.jpg'>) * 經過上面的操作後,如果將被操作的文檔doc.save()保存的話,效果應該可以展現出來的 * 但是現在還需要讀取被操作文檔的html,這樣導致 本意是想將圖片的url替換圖片數據的,但是獲取word文檔的html內容時 * 會將url代表的圖片給轉爲base64,這樣仍不符合要求; * * 但是通過 builder.write(url)將圖片url寫回原圖的位置時,會出現這樣的效果,如果url中包含了中文的話,會被一些html * 標籤給隔開,導致url被分割成多個部分,而不是一個整體。 * */ } } } catch (Exception e) { e.printStackTrace(); } }