这篇文章将为大家详细讲解有关Java获取Word批注的文字和图片的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

工具使用:Word类库(Free Spire.Doc for Java 免费版)

Jar文件获取:可通过官网下载,下载后解压文件,并将lib文件夹下的Spire.Doc.jar文件导入java程序。

测试文档如下:批注中包含文本和图片

【示例1】读取批注中的文本

importcom.spire.doc.*;importcom.spire.doc.documents.Paragraph;importcom.spire.doc.fields.Comment;importcom.spire.doc.fields.TextRange;publicclassReadComment{publicstaticvoidmain(String[]args){//加载测试文档Documentdoc=newDocument();doc.loadFromFile("sample.docx");//实例化String类型变量Stringtext="";//遍历所有批注for(inti=0;i<doc.getComments().getCount();i++){Commentcomment=doc.getComments().get(i);//遍历所有批注中的段落for(intj=0;j<comment.getBody().getParagraphs().getCount();j++){Paragraphparagraph=comment.getBody().getParagraphs().get(j);//遍历段落中的对象for(Objectobject:paragraph.getChildObjects()){//读取文本if(objectinstanceofTextRange){TextRangetextRange=(TextRange)object;text=text+textRange.getText();}}}}//输入文本内容System.out.println(text);}}

批注文本读取结果:

【示例2】读取批注中的图片

importcom.spire.doc.*;importcom.spire.doc.documents.Paragraph;importcom.spire.doc.fields.Comment;importcom.spire.doc.fields.DocPicture;importjavax.imageio.ImageIO;importjava.awt.image.RenderedImage;importjava.io.File;importjava.io.IOException;importjava.util.ArrayList;publicclassExtractImgsInComment{publicstaticvoidmain(String[]args)throwsIOException{//加载测试文档Documentdoc=newDocument();doc.loadFromFile("sample.docx");//创建ArrayList数组对象ArrayListimages=newArrayList();//遍历所有批注for(inti=0;i<doc.getComments().getCount();i++){Commentcomment=doc.getComments().get(i);//遍历所有批注中的段落for(intj=0;j<comment.getBody().getParagraphs().getCount();j++){Paragraphparagraph=comment.getBody().getParagraphs().get(j);//遍历段落中的对象for(Objectobject:paragraph.getChildObjects()){//获取图片对象if(objectinstanceofDocPicture){DocPicturepicture=(DocPicture)object;images.add(picture.getImage());}}}}//提取图片,并指定图片格式for(intz=0;z<images.size();z++){Filefile=newFile(String.format("图片-%d.png",z));ImageIO.write((RenderedImage)images.get(z),"PNG",file);}}}

批注图片读取结果:

关于Java获取Word批注的文字和图片的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。