Java 讀取Word批註中的文本和圖片

本文將介紹讀取Word批註的方法,包括讀取Word批註中的文本及圖片。關於操做Word批註的方法還能夠參考這兩篇文章:Java 添加、回覆、修改、刪除Word批註Java 給Word指定字符串添加批註。下面將經過Java代碼來演示如何讀取批註。html

工具使用:Word類庫(Free Spire.Doc for Java 免費版java

Jar文件獲取:可經過官網下載,下載後解壓文件,並將lib文件夾下的Spire.Doc.jar文件導入java程序;也能夠經過Maven倉庫安裝導入,具體路徑配置及導入方法能夠參考教程數組

測試文檔以下:批註中包含文本和圖片maven

 

 


 

【示例1讀取批註中的文本

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.Comment;
import com.spire.doc.fields.TextRange;

public class ReadComment {
    public static void main(String[] args) {
        //加載測試文檔
        Document doc = new Document();
        doc.loadFromFile("sample.docx");

        //實例化String類型變量
        String text = "";

        //遍歷全部批註
        for(int i = 0;i< doc.getComments().getCount();i++){
            Comment comment = doc.getComments().get(i);
            //遍歷全部批註中的段落
            for(int j= 0;j < comment.getBody().getParagraphs().getCount();j++) {
                Paragraph paragraph = comment.getBody().getParagraphs().get(j);
                //遍歷段落中的對象
                for (Object object : paragraph.getChildObjects()) {
                    //讀取文本
                    if (object instanceof TextRange) {
                        TextRange textRange = (TextRange) object;
                        text = text + textRange.getText();
                    }
                }
            }
        }
        //輸入文本內容
        System.out.println(text);
    }
}

批註文本讀取結果:工具

 

【示例2讀取批註中的圖片

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.Comment;
import com.spire.doc.fields.DocPicture;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;


public class ExtractImgsInComment {
    public static void main(String[] args) throws IOException{
        //加載測試文檔
        Document doc = new Document();
        doc.loadFromFile("sample.docx");

        //建立ArrayList數組對象
        ArrayList images = new ArrayList();

        //遍歷全部批註
        for(int i = 0;i< doc.getComments().getCount();i++){
            Comment comment = doc.getComments().get(i);
            //遍歷全部批註中的段落
            for(int j= 0;j < comment.getBody().getParagraphs().getCount();j++) {
                Paragraph paragraph = comment.getBody().getParagraphs().get(j);
                //遍歷段落中的對象
                for (Object object : paragraph.getChildObjects()) {
                    //獲取圖片對象
                    if(object instanceof DocPicture){
                        DocPicture picture = (DocPicture) object;
                        images.add(picture.getImage());
                    }
                }
            }
        }
        //提取圖片,並指定圖片格式
        for (int z = 0; z< images.size(); z++) {
            File file = new File(String.format("圖片-%d.png", z));
            ImageIO.write((RenderedImage) images.get(z), "PNG", file);
        }
    }
}

批註圖片讀取結果:測試

 

(本文完)spa

相關文章
相關標籤/搜索