aspose.word讀取word中的圖片並替換爲文字

aspose.word讀取word中的圖片並替換爲文字

try {
            // 新建文檔對象
            Document doc = new Document(filePath);
            // 查詢文檔中所有圖片
            NodeCollection shapeCollection = doc.getChildNodes(NodeType.SHAPE, true);
            // 序列化
            Node[] shapes = shapeCollection.toArray();
            int index = 1;
            // 如果文檔存在圖片
            if (shapes.length > 0) {
                for (Node node : shapes) {
                    Shape shape = (Shape) node;
                    if (shape.getShapeType() == ShapeType.OLE_OBJECT) {// 如果shape類型是ole類型
                        System.out.println(node.getNodeType());
                        ImageData i = shape.getImageData();// 獲得圖片數據
                        String imageName = index++ + ".wmf";
                        i.save(imgDir + imageName);// 導出圖片
                        File f = new File(imgDir + imageName);
                        DocumentBuilder builder = new DocumentBuilder(doc);// 新建文檔節點
                        builder.moveTo(shape);// 移動到圖片位置
                        builder.write("[" + imageName + "]");// 插入替換文本
                        shape.remove();// 移除圖形
                    } else if (shape.getShapeType() == ShapeType.IMAGE) {// 如果shape類型是ole類型
                        System.out.println(node.getNodeType());
                        ImageData i = shape.getImageData();// 獲得圖片數據
                        String imageName = index++ + ".png";
                        i.save(imgDir + imageName);// 導出圖片
                        File f = new File(imgDir + imageName);
                        DocumentBuilder builder = new DocumentBuilder(doc);// 新建文檔節點
                        builder.moveTo(shape);// 移動到圖片位置
                        builder.write("[" + imageName + "]");// 插入替換文本
                        shape.remove();// 移除圖形
                    }
                }
                doc.save("");// 保存修改後的文檔
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章