原始需求
java-web and 小程序 项目某页面,用户在支付前生成在线合同,并且签订电子签名,并且可以提供PDF在线预览和下载功能。
分析问题
- 既然是在线合同,肯定就需要靠模板来生成,这里我使用了freemarker模板引擎,这里就不详细介绍了,直接借用别人的帖子使用freemarker生成word,步骤详解并奉上源代码,如果需要循环插入列表,图片等情况,不懂就问,评论区见
- 由于freemarker生成的word本身就不是一个标准格式的word,他其实是一个xml格式的文件,所以用一般的的word转pdf工具是会出现这种问题
Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: The supplied data appears to be a raw XML file. Formats such as Office 2003 XML are not supported
- 这里介绍几种java里实现Word转PDF的方案:
一、libreOffice
优点:样式稳定,缺点:性能较差
二、docx4j
优点:性能比 libreoffice 稍好,缺点:性能差、容易出现 PDF 和 Word 样式不一致问题
三、documents4j
优点:样式稳定、性能高,缺点:要依赖本地的 office 软件做转换,在 linux 下要调远程服务来转换,GitHub:documents4j
四、jacob
优点:样式稳定、性能高,缺点:只支持 window 系统且服务器要安装 office 软件,并发量大时会有瓶颈
五、pageOffice
优点:兼容性好,性能高,缺点:收费,客户端需要安装 office 软件和卓正控件,偶尔会出现兼容性问题
实际应用中,前面四种方案都用过,踩了不少坑,比如 libreoffice,要考虑生产环境低内核版本问题,docx4j 的转换后样式错乱问题,documents4j 不稳定,会出现进程阻塞,jacob 只支持 window 服务器,最后还说卓正的 pageOffice最好用。
为了考虑性能,样式稳定,成本,开发效率,最终我选择了Aspose
!!!
Aspose
apose是一个很强大的office文档处理软件,可以完美的实现word文档转换为pdf文件,缺点就是软件是需要付费的。但是网上可以找到很多的破解版jar包,测试效果还是很不错的,而且使用简单,项目中使用的就是这种方式。
apose的Jar包和maven-pom.xml
链接:https://pan.baidu.com/s/1Fc-9aefeo8jt_hlqnY0UGw
提取码:z81j
<!--添加本地的aspose-words-15.8.0-jdk16.jar包-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>
license.xml(去除水印)
<?xml version="1.0" encoding="UTF-8" ?>
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
转换工具类
package com.example.declaration.util;
import com.aspose.words.*;
import com.aspose.words.Document;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
public class WordToPDF {
//public static void main(String[] args) {
// String docPath = BasePath.BASE_PATH + "test.docx";
// String pdfPath = BasePath.BASE_PATH + "test.pdf";
// WordToPDF.wordToPdf(docPath, pdfPath);
//
//}
public static boolean wordToPdf(String inPath, String outPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return false;
}
FileOutputStream os = null;
try {
long old = System.currentTimeMillis();
File file = new File(outPath); // 新建一个空白pdf文档
os = new FileOutputStream(file);
Document doc = new Document(inPath); // Address是将要被转化的word文档
doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
// EPUB, XPS, SWF 相互转换
long now = System.currentTimeMillis();
System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static boolean getLicense() {
boolean result = false;
InputStream is = null;
try {
Resource resource = new ClassPathResource("license.xml");
is = resource.getInputStream();
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 导出最后的pdf格式
*
* @param response
* @param pdfPath
* @param pdfPath
*/
public static void exportPdf(HttpServletResponse response, String pdfPath, String fileName) {
InputStream inputStream = null;
ServletOutputStream outputStream = null;
File pdfFile = new File(pdfPath);
try {
byte[] bs = new byte[1024];
inputStream = new FileInputStream(pdfFile);
outputStream = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "filename=" + URLEncoder.encode(fileName, "UTF-8"));
while (inputStream.read(bs) > 0) {
outputStream.write(bs);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
到这里就结束了
乱码问题请看:aspose将word转pdf时乱码,或者出现小方框问题