工作中,经常做一些导出、读取Excel文档,但是从来没有尝试Word转PDF。我们通常使用的是POI和JXL。这两个插件对Excel已经有很好的支持了。操作PDF通常使用的是ITEXT插件,该插件可以操作复杂的PDF,当然我们也可以通过freemarker来生成PDF也是可以的。但是最近的项目在打印合同的时候,只提供了word模板,然后打印PDF,期间需要读取数据,填充到Word文档中,该文档还是修订格式,还需要接受所有修订以后,转成PDF下载。本以为很简单,通过freemarker就可以轻松实现,但是在尝试过后,还知道不是很顺利,网上也提供了不少的解决方案,个人感觉大多都不是好,有一些只支持Window系统,有一些则需要安装Office软件,在这里,给大家提供本人在这个过程中的一些新的体会,让大家遇到这类问题少走一些弯路。
首先比较一下网上各种版本的实现比较:具体实现方式自行百度,这里不再赘述。
第一种:JobConverter + OpenOffice
这种方式需要安装OpenOffice服务,windows . linux 都可以配置。
第二种:SaveAsPDFandXPS + jacob (Windows操作系统下,电脑里有office)
不兼容Linux系统,只支持WIN系统,不合适生产环境。
第三种:。。。。。。
其他的方案就不一一举例感兴趣的同学,可以执行百度搜索,个人觉得都不够简单而有效的解决我们的问题。
请点击:下载地址
下面直入主题,贴代吗
1.配置pom.xml
<dependency>
<groupId>org.aspose-words</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0-jdk16</version>
<scope>system</scope>
<systemPath>${project.basedir}/WebRoot/WEB-INF/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>
2.核心代码实现
/**
* @param dataMap 数据
* @param templateName 模板
* @param uuid
* @return
*/
public String genWordFile(Map<?, ?> dataMap, String templateName, String uuid) throws SystemException {
Writer writer = null;
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
configuration
.setDirectoryForTemplateLoading(new File(getPath().replace("WEB-INF/classes/", "") + "templates"));
String filePath = OpermngFormConfig.DOWNLOADFILEPATH + UUID.randomUUID().toString() + ".doc";
File outFile = new File(filePath);
Template template = configuration.getTemplate(templateName);
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
template.process(dataMap, writer);
writer.flush();
return filePath;
} catch (Exception e) {
logger.error("[{}]生成word文档异常", uuid, e);
throw new SystemException("生成word文档异常");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
logger.error("[{}]关闭流资源异常", uuid, e);
}
}
}
}
/**
* word转PDF
* @param dataMap
* @param templateName
* @param uuid
* @param response
*/
public void word2PDF(Map<?, ?> dataMap, String templateName, String uuid, HttpServletResponse response)
throws SystemException {
String filePath = genWordFile(dataMap, templateName, uuid);
String file_path = OpermngFormConfig.DOWNLOADFILEPATH + UUID.randomUUID().toString() + ".doc";
try {
getLicense(uuid);
Document document = new Document(filePath);
document.acceptAllRevisions();
document.save(file_path, SaveFormat.DOC);
deleteFile(new File(filePath));
} catch (Exception e) {
logger.error("[{}]接受word修订格式异常", uuid, e);
throw new SystemException("接受word修订格式异常");
}
genPDFFile(file_path, uuid, response);
}
/**
* 生成PDF文件
* @param filePath
* @param uuid
* @param response
* @throws SystemException
*/
public void genPDFFile(String filePath, String uuid, HttpServletResponse response) throws SystemException {
getLicense(uuid);
try {
logger.info("[{}]打印即将转换的word路径:{}", uuid, filePath);
Document doc = new Document(filePath);
doc.save(response.getOutputStream(), SaveFormat.PDF);
logger.info("[{}]转换pdf完成", uuid);
deleteFile(new File(filePath));
} catch (Exception e) {
logger.error("[{}]生成pdf文档异常", uuid, e);
throw new SystemException("生成pdf文档异常");
}
}
/**
* 验证License 若不验证则转化出的pdf文档会有水印产生
* @param uuid
* @return
*/
private boolean getLicense(String uuid) {
boolean result = false;
try {
String filePath = Thread.currentThread().getContextClassLoader().getResource("license.xml").getFile();
if (System.getProperty("os.name").startsWith("Windows")) {
filePath = filePath.substring(1);
}
InputStream is = new FileInputStream(filePath);
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
logger.error("[{}]验证License异常", uuid, e);
}
return result;
}