使用java开发时,碰到一个需求,需要在一个word文件指定位置嵌套另一个word文件中的内容,通过以下代码实现:
package com.macrochina.mis.tools;
import com.aspose.words.*;
import org.springframework.boot.system.ApplicationHome;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class AsposeWordHandler {
public void main(String[] args) throws IOException {
//在文档指定位置处插入其他文件。docPosition为自定义符号。
DocInsert("{{insertFilePosition}}", "D:/temp/main.docx", "D:/temp/1.docx", "D:/temp/2.docx", true);
}
/**
* 在 mainWord 文档指定位置处插入其他文件。docPosition 为自定义符号。
*
* @param docPosition 主文件 mainWord 中的特定文件的位置,本实例以 {{insertFilePosition}} 标识
* @param mainWord 主文件
* @param AddWord 往主文件中添加的附加文件
* @param outWord 输出文件
* @param isPortrait 横向还是纵向
*/
public void DocInsert(String docPosition, String mainWord, String AddWord, String outWord, boolean isPortrait) {
if (!getLicense()) {
System.out.println("Aspose_word_License Error!");
}
try {
// 使用Aspose.words 加载要处理的文档 mainWord
Document doc = new Document(mainWord);
// 获取需要进行追加的文档 addWord
Document addDocument = new Document(AddWord);
// 创建一个文本生成构造器 builder
DocumentBuilder Builder = new DocumentBuilder(doc);
NodeCollection runs = doc.getChildNodes(NodeType.PARAGRAPH, true); //获取所有节点
for (int i = 0; i < runs.getCount(); i++) {
Paragraph r = (Paragraph) runs.get(i);
String text = r.getRange().getText();//获取段落文本
//获取到标志点位
if (text.length() >= docPosition.length() && text.indexOf(docPosition) >= 0) {
//指定段落插入表格
Builder.moveTo(r);
Builder.getPageSetup().setPaperSize(PaperSize.A4);
if (isPortrait) {
Builder.getPageSetup().setOrientation(Orientation.PORTRAIT);
} else {
Builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
}
Node insertAfterNode = Builder.getCurrentParagraph().getPreviousSibling();
insertDocumentAfterNode(insertAfterNode, doc, addDocument);
r.remove();//删除标志点位所在行
break;
}
}
//doc.updateFields(); // 因为文档结构变动可能需要更新目录
doc.save(outWord); // 保存合并后的新文件
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 在指定位置插入新文件信息
*
* @param insertAfterNode 插入的位置
* @param mainDoc 主文档
* @param srcDoc 要拼接进去的文档
* @throws Exception 异常捕获
*/
private void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc, Document srcDoc) throws Exception {
if (insertAfterNode.getNodeType() != 8 && insertAfterNode.getNodeType() != 5) {
throw new Exception("The destination node should be either a paragraph or table.");
} else {
CompositeNode dstStory = insertAfterNode.getParentNode();
Body body = srcDoc.getLastSection().getBody();
while (null != body.getLastParagraph() && !body.getLastParagraph().hasChildNodes()) {
srcDoc.getLastSection().getBody().getLastParagraph().remove();
}
NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
int sectCount = srcDoc.getSections().getCount();
for (int sectIndex = 0; sectIndex < sectCount; ++sectIndex) {
Section srcSection = srcDoc.getSections().get(sectIndex);
int nodeCount = srcSection.getBody().getChildNodes().getCount();
for (int nodeIndex = 0; nodeIndex < nodeCount; ++nodeIndex) {
Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
Node newNode = importer.importNode(srcNode, true);
dstStory.insertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
}
/**
* 获取aspose.words的license文件
* @return license文件是否正常
*/
public boolean getLicense() {
boolean result = false;
try {
ApplicationHome home = new ApplicationHome(getClass());
File jarFile = home.getSource();
//System.out.println("=================" + jarFile.getParentFile().getParentFile().toString());
File file = new File(jarFile.getParentFile().getParentFile().toString() + "/license.xml");
if (file.exists()) {
InputStream is = new FileInputStream(file);
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
}
} catch (Exception e) { //异常处理
e.printStackTrace();
}
return result;
}
}