本文将介绍如何通过spire.doc for java来添加文本字符串、图片以及格式化的表格到word书签。
测试文档如下,文中第三段已插入书签 “书签1”:
添加文本、图片到word书签
import com.spire.doc.*;
import com.spire.doc.documents.bookmarksnavigator;
import com.spire.doc.documents.paragraph;
import com.spire.doc.documents.textwrappingstyle;
import com.spire.doc.fields.docpicture;
public class addimgtobookmarkcontent {
public static void main(string[]args){
//加载包含书签的文档
document doc = new document();
doc.loadfromfile("测试.docx");
//定位到指定书签位置起始标签位置,插入图片
bookmarksnavigator bookmarksnavigator1 = new bookmarksnavigator(doc);
bookmarksnavigator1.movetobookmark("书签1",true,false);
paragraph para = new paragraph(doc);
docpicture picture = para.appendpicture("docjava.png");
picture.setwidth(100f);
picture.setheight(100f);
picture.settextwrappingstyle(textwrappingstyle.through);
bookmarksnavigator1.insertparagraph(para);
//定位到指定书签位置末尾标签位置,插入文本
bookmarksnavigator bookmarksnavigator2 = new bookmarksnavigator(doc);
bookmarksnavigator2.movetobookmark("书签1",false,true);
bookmarksnavigator2.inserttext("新插入的文本!!!");
//保存文档
doc.savetofile("添加文本、图片到书签.docx",fileformat.docx_2013);
doc.dispose();
}
}
文本、图片添加效果:
添加表格到word书签
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.textrange;
public class addtabletobookmarkcontent{
public static void main(string[]args){
//加载包含书签的文档
document doc = new document();
doc.loadfromfile("测试.docx");
//声明数组内容
string[][] data =
{
new string[]{"产品", "版本", "发布日期"},
new string[]{"spire.doc for java", "v2.7.2", "2019-07-24"},
};
//创建表格
table table = new table(doc, true);
table.resetcells(2, 3);
for (int i = 0; i < data.length; i ) {
tablerow datarow = table.getrows().get(i);
for (int j = 0; j < data[i].length; j ) {
textrange range = datarow.getcells().get(j).addparagraph().appendtext(data[i][j]);
range.getownerparagraph().getformat().sethorizontalalignment(horizontalalignment.center);
range.getcharacterformat().setfontname("楷体");
datarow.getrowformat().sethorizontalalignment(rowalignment.center);
datarow.getcells().get(j).getcellformat().setverticalalignment(verticalalignment.middle);
}
}
//定位到指定书签位置,添加表格
bookmarksnavigator bookmarksnavigator = new bookmarksnavigator(doc);
bookmarksnavigator.movetobookmark("书签1");
bookmarksnavigator.inserttable(table);
//保存文档
doc.savetofile("添加表格到word书签.docx",fileformat.docx_2013);
doc.dispose();
}
}
表格添加效果: