Hello World程序
// Create a new empty document A
Document docA = new Document();
// Inisialize a DocumentBuilder
DocumentBuilder builder = new DocumentBuilder(docA);
// Insert text to the document A start
builder.moveToDocumentStart();
builder.write("First Hello World paragraph");
// Open an existing document B
Document docB = new Document("C:\\Temp\\documentB.docx");
// Add document B to the and of document A, preserving document B formatting
docA.appendDocument(docB, ImportFormatMode.KEEP_SOURCE_FORMATTING);
// Save the output as PDF
docA.save("C:\\Temp\\output_AB.pdf");
证书验证
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = AsposeWordsUtils.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
静态数据的处理
// 首先要读取模板文档
Document doc = new Document("模板文档输入流");
DocumentBuilder builder = new DocumentBuilder(doc);
// 有两种方法能够处理静态的数据
// 1、通过builder的moveToMergeField移动到指定的域
builder.moveToMergeField(key);
builder.write(); // 插入文字
builder.insertImage(); // 插入图片
// 2、全盘覆盖,一次性把指定的域都给换成指定的值(只能做文字的覆盖,无法处理图片)
doc.getMailMerge().execute(keys,values);
// 处理完后将修改好的文档保存到指定的路径
doc.save(new FileOutPutStream(new File("保存路径")),SaveFormat.DOCX);
动态数据的处理
// 关于动态行的处理,其他网站上有许多的案例,这里笔者只讲一下对于上图需要实现动态列情况的处理
// 以下内容仅为笔者在Aspose.Words使用中总结出的方法,并不为最优的解决方案
// 首先依然是读取模板文档
Document doc = new Document("模板文档输入流");
DocumentBuilder builder = new DocumentBuilder(doc);
// 读取指定的表格
Table table = (Table) doc.getChild(NodeType.TABLE, tableIndex, true);
// 参数说明:getChild(节点类型,表格索引,是否深克隆)
// 备份生成模板行
Row rowImage = (Row) table.getRows().get(rowIndex).deepClone(true);
Row rowTitle = (Row) table.getRows().get(rowIndex + 1).deepClone(true);
// 备份生成模板单元格
Node cellImage = rowImage.getCells().get(cellIndex).deepClone(true);
Node cellTitle = rowTitle.getCells().get(cellIndex).deepClone(true);
// 备份的原因主要是为了拼接在表格后面,属于一种比较笨的方式实现动态列,记住一定要开启深克隆
// 接下来是实现动态列的原理
// 插入新的单元格
table.getRows().get(rowIndex).getCells().add(cellImage.deepClone(true));
table.getRows().get(rowIndex + 1).getCells().add(cellTitle.deepClone(true));
// 插入新的行
table.getRows().add(rowImage.deepClone(true));
table.getRows().add(rowTitle.deepClone(true));
// 建议插入一列单元格后就进行数据的插入
builder.moveToMergeField(key);
builder.write(value);
// builder.moveToMergeField在遇到相同的域名时,会按照前后的顺序进行移动
// 以上就是通过搬砖的方式实现动态列,笔者认为不太优雅,如果读者有更好的方法,欢迎跟笔者交流