本文将介绍如何通过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();
}
}
表格添加效果: