AsposeTool工具类
/*
* Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Words. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import com.aspose.words.Font;
import com.aspose.words.*;
import org.jeecg.common.util.StringUtil;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AsposeTool {
static boolean licenseFlag = false;
static {
try {
InputStream is = AsposeTool.class.getClassLoader().getResourceAsStream("config/license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
License aposeLic = new License();
aposeLic.setLicense(is);
licenseFlag = true;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 替换word中的占位符
* @param sourcePath
* @param outPath
* @param params
* @throws Exception
*/
public static void replace(String sourcePath, String outPath, Map<String, Object> params, String type) throws Exception {
Document doc = new Document(sourcePath);
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue()).replaceAll("\n", ControlChar.LINE_BREAK).replaceAll("null", "");
FindReplaceOptions findReplaceOptions = new FindReplaceOptions();
if (key.startsWith(":")) {
String subKey = "#{" + key.substring(1) + "}";
if(key.contains(".table")) {
HashMap<String, Object> tableMap = (HashMap<String, Object>) params.get(key);
doc.getRange().replace(subKey, "", new FindReplaceOptions(new ReplaceAndInsertTable(subKey, tableMap)));
} else if (value.contains("#break#")) {
//多行文本换行处理
String repText = value.replaceAll("#break#", (char) 11 + "");
doc.getRange().replace(subKey, repText, findReplaceOptions);
} else if (value.toLowerCase().endsWith("png") || value.toLowerCase().endsWith("jpg")) {
//图片处理
System.out.println("key:" + key);
if (FileUtil.exist(value)) {
NodeCollection shapeCollection = doc.getChildNodes(NodeType.SHAPE, true);
Iterator<Shape> shapeIterate = shapeCollection.iterator();
List<Shape> shaplist = new ArrayList<Shape>();
while (shapeIterate.hasNext()) {
Shape shape = shapeIterate.next();
if (key.equals(shape.getName())) {
shaplist.add(shape);
}
}
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < shaplist.size(); i++) {
Shape shape = shaplist.get(i);
//将光标移动到指定节点
builder.moveTo(shape);
Shape img = builder.insertImage(value, width, height);
img.setName(subKey);
shape.remove();
}
//替换文字为图片
doc.