Java 给Word指定字符串添加批注

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。Java 给Word指定字符串添加批注,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

本文将介绍在Java程序中如何给Word文档中的指定字符串添加批注。前文中,主要介绍的是针对某个段落来添加批注,以及回复、编辑、删除批注的方法,如果需要针对特定关键词或指定字符串来设置批注,可以参考本文的方法。

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

获取方法1通过官网下载,并导入Spire.Doc.jar文件至java程序。

获取方法2通过maven仓库安装导入。可参考方法教程

 

Java代码示例

import com.spire.doc.*;
import com.spire.doc.documents.CommentMark;
import com.spire.doc.documents.CommentMarkType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.Comment;

public class AddCommentToCharacters {
    public static void main(String[] args) {
        //加载测试文档
        Document doc = new Document();
        doc.loadFromFile("test.docx");

        //查找指定字符串
        TextSelection[] selections = doc.findAllString("皱状厚膜", true, false);

        //获取关键字符串所在段落
        Paragraph para = selections[0].getAsOneRange().getOwnerParagraph();
        int index = para.getChildObjects().indexOf(selections[0].getAsOneRange());

        //添加批注ID
        CommentMark start = new CommentMark(doc);
        start.setCommentId(1);
        start.setType(CommentMarkType.Comment_Start);
        CommentMark end = new CommentMark(doc);
        end.setType(CommentMarkType.Comment_End);
        end.setCommentId(1);

        //添加批注内容
        String str = "给指定字符串添加批注";
        Comment comment = new Comment(doc);
        comment.getFormat().setCommentId(1);
        comment.getBody().addParagraph().appendText(str);
        comment.getFormat().setAuthor("作者:");
        comment.getFormat().setInitial("CM");
        para.getChildObjects().insert(index, start);
        para.getChildObjects().insert(index + 1, selections[0].getAsOneRange());
        para.getChildObjects().insert(index + 2,end);
        para.getChildObjects().insert(index + 3, comment);

        //保存文档
        doc.saveToFile("字符串批注.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}

批注添加效果:

Java 给Word指定字符串添加批注

 

(本文完)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/209390.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!