aspose java 读取word文档中的图片保存至文件服务器并通过 图片路径替换该图片

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();
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章