本文将介绍如何通过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.DefaultTableStyle;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.TableRowHeightType;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.TextRange;
public class AddTableToHeader {
public static void main(String[]args){
//加载需要添加页眉页脚的文档
Document doc= new Document("test.docx");
Section sec = doc.getSections().get(0);
//调用方法添加页眉页脚
AddHeaderFooter(sec);
//保存文档
doc.saveToFile("AddTableToHeader.docx");
}
private static void AddHeaderFooter(Section sec){
//添加表格到页眉
HeaderFooter header = sec.getHeadersFooters().getHeader();
Table table = header.addTable();
table.resetCells(2,2);//指定表格行数、列数
table.applyStyle(DefaultTableStyle.Light_Grid);//设置表格样式
//声明数组内容
String[][] data ={
new String[]{"出版号","日期"},
new String[]{"SC12546","2019年7月24日"},
};
//填充数组内容到表格
for (int i = 0; i < data.length; i++) {
TableRow dataRow = table.getRows().get(i);
dataRow.setHeight(20f);
dataRow.setHeightType(TableRowHeightType.Exactly);
for (int j = 0; j < data[i].length; j++) {
dataRow.getCells().get(j).setCellWidth(120f,CellWidthType.Point);
dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
range.getCharacterFormat().setFontName("楷体");
range.getCharacterFormat().setFontSize(12f);
range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
}
}
}
}
表格添加效果: