Java 添加、修改、刪除Word批註

批註,是做者或審閱者給文檔添加的註釋或註解。經過查看批註,能夠更加詳細地瞭解某些文字的背景。除添加文本信息到批註外,還能夠經過添加圖片的方式來使其內容更具豐富性和直觀性。本文將經過使用Java程序來詳細介紹如何添加、修改和刪除Word文檔中的批註(含文本和圖片)。html

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

Jar文件獲取及導入:

方法1:經過官網下載獲取jar包。解壓後將lib文件夾下的Spire.Doc.jar文件導入Java程序。(以下圖)
安裝圖.pngjava

方法2:經過maven倉庫安裝導入。具體安裝詳解參見此網頁app

【示例1】添加Word批註

import com.spire.doc.*;  
import com.spire.doc.documents.Paragraph;  
import com.spire.doc.fields.Comment;  
public class InsertComment {  
public static void main(String[] args) {  

//加載測試文檔  
Document doc = new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");  

//獲取指定段落  
Section sec = doc.getSections().get(0);  
Paragraph para= sec.getParagraphs().get(1);  

//插入文本到批註  
Comment comment = para.appendComment("徐志摩,現代新月派表明詩人,原名章垿,字槱森,留學英國時更名志摩。");  

//插入圖片到批註  
comment.getBody().addParagraph().appendPicture("C:\\Users\\Test1\\Desktop\\Image.jpg");  

//保存文檔  
  doc.saveToFile("output/InsertComment.docx", FileFormat.Docx_2010);  
    }  
}

批註添加效果:maven

效果1.png

【示例2】修改Word批註

import com.spire.doc.*;  
public class ReplaceComment {  
public static void main(String[] args) {  

//加載含有批註的測試文檔  
Document doc = new Document("C:\\Users\\Test1\\Desktop\\InsertComment.docx"); 

//獲取第一個批註中的第一段,用新的文本替換原有批註中的文本  
doc.getComments().get(0).getBody().getParagraphs().get(0).replace("徐志摩,現代新月派表明詩人,原名章垿,字槱森,留學英國時更名志摩。",
"徐志摩是一位在中國文壇上曾經活躍一時並有必定影響的做家。",false,false);  

//獲取第一個批註中的第二段,刪除原有圖片,再調用方法添加新圖片(用圖片替換圖片)  
doc.getComments().get(0).getBody().getParagraphs().get(1).getChildObjects().removeAt(0);  
doc.getComments().get(0).getBody().getParagraphs().get(1).appendPicture("C:\\Users\\Test1\\Desktop\\Image2.jpg");  

//保存文檔  
doc.saveToFile("output/ReplaceComment.docx",FileFormat.Docx_2013);  
  
    }  
}

批註修改效果:工具

效果2.png

【示例3】刪除Word批註

import com.spire.doc.*;  
import com.spire.doc.FileFormat;  
public class DeleteComment {  
public static void main(String[] args) {  
String inputFile="C:\\Users\\Test1\\Desktop\\InsertComment.docx";  
String outputFile="output/DeleteComment.docx";  
  
//加載示例文檔  
Document doc= new Document(inputFile);  
//刪除批註  
doc.getComments().removeAt(0);  
//保存文檔  
doc.saveToFile(outputFile, FileFormat.Docx);  
    }  
}

批註刪除效果:測試

效果3.png

(本文完)spa

相關文章
相關標籤/搜索