实际工作中我们常常会遇到这样的业务需求,比如说:根据模板生成文件,将生成的文档发送邮件到指定的邮箱。实现这一需求我们可以采用根据模板生成word文档(参照前一篇文章),然后再将word文档转为PDF文档。
到这里就用到我今天要说的知识了,其实已经有很多优秀的博客写过了,所以这篇文章的主要目的还是借鉴、学习,掌握这个方法,用到自己的实际业务中去。
前置条件:准备aspose-words-15.8.0-jdk16.jar 、 license.xml 文件(破解版)
1、需要在项目中引入该jar包,如果要是本地使用的话可以直接将jar放在/WEB-INF/lib/ 目录下。
2、另一种方式是在pom文件中配置本地依赖;在项目中新建pom文件平级的文件夹lib,将aspose-words-15.8.0-jdk16.jar放入lib中,然后在pom文件中加入如下依赖
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>15.8.0-jdk16</version> <scope>system</scope> <systemPath>${project.basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath> </dependency>
PS:POM文件里面可以引用一些内置属性(Maven预定义可以直接使用)
${basedir} 项目根目录
${version}表示项目版本;
${project.basedir}同${basedir};
${project.version}表示项目版本,与${version}相同;
${project.build.directory} 构建目录,缺省为target
${project.build.sourceEncoding}表示主源码的编码格式;
${project.build.sourceDirectory}表示主源码路径;
${project.build.finalName}表示输出文件名称;
${project.build.outputDirectory} 构建过程输出目录,缺省为target/classes
代码结构:
/*** * 去除生成PDF的水印 * @return */ public static boolean getLicense() { boolean result = false; try { // license.xml应放在..WebRootWEB-INFclasses路径下 InputStream is = FreeMarkerWordUtil.class.getClassLoader().getResourceAsStream("license.xml"); log.info("InputStreamInputStreamInputStream=======" + is); License aposeLic = new License(); aposeLic.setLicense(is); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /*** * word转pdf * @param wordPath * @param pdfPath */ public static boolean word2Pdf(String wordPath, String pdfPath) { boolean flag = false; // 验证License 若不验证则转化出的pdf文档会有水印产生 if (!getLicense()) { return false; } try { //新建一个pdf文档 File file = new File(pdfPath); FileOutputStream os = new FileOutputStream(file); //Address是将要被转化的word文档 Document doc = new Document(wordPath, null); //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换 doc.save(os, SaveFormat.PDF); os.close(); flag = true; } catch (Exception e) { e.printStackTrace(); flag = false; } return flag; }
下载文件功能 /** * 下载文件 * * @param request * @param response * @param fileName 文件名称 * @param filePath 导出的文件 */ public static void downLoad(HttpServletRequest request, HttpServletResponse response, String fileName, String filePath) { // 获取响应输出流 OutputStream os = null; FileInputStream in = null; try { in = new FileInputStream(new File(filePath)); os = response.getOutputStream(); response.reset(); // 编码文件名 String fileNameDisplay = URLEncoder.encode(fileName, "UTF-8"); // 判断浏览器信息:对文件名进行编码 if (null != getBrowser(request) && "FF".equals(getBrowser(request))) { fileNameDisplay = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); } // 设置响应头 response.addHeader("Content-Disposition", "attachment; filename=" + fileNameDisplay); response.addHeader("Content-Type", "application/pdf"); byte[] by = new byte[1024]; while ((in.read(by)) != -1) { os.write(by); } os.flush(); } catch (IOException e) { // TODO throw new RuntimeException(e); } finally { if (null != os) { try { os.close(); } catch (IOException e) { System.err.println("response OutputStream close failure."); } } if (null != in) { try { in.close(); } catch (IOException e) { System.err.println("response OutputStream close failure."); } } } } /** * 获取浏览器相关信息 * * @param request * @return * @author */ public static String getBrowser(HttpServletRequest request) { if (null == request || null == request.getHeader("USER-AGENT")) { return null; } String userAgent = request.getHeader("USER-AGENT").toLowerCase(); if (userAgent != null && userAgent.trim().length() > 0) { if (userAgent.indexOf("msie") >= 0) return "IE"; if (userAgent.indexOf("firefox") >= 0) return "FF"; if (userAgent.indexOf("safari") >= 0) return "SF"; } return null; }
补充:
项目部署到linux服务器上后,生成的PDF会出现乱码的情况如图1-1所示。
1-1
乱码的原因是linux服务器未安装中文字体库。按照以下步骤可进行安装
1、进入linux字体库
cd /usr/share/Fonts
2、新建windows文件夹
mkdir windows
3、将准备好的字体库导入到新建的windows文件夹
sudo cp *.ttc /usr/share/fonts/windows/
sudo cp *.ttf /usr/share/fonts/windows/
4、更改字体库的权限(将当前windows字体库内文件权限也要进行修改,至少要有执行权限否则字体库不生效)
sudo chmod 755 /usr/share/fonts/windows/*
5、然后进入linux字体库
cd /usr/share/fonts/windows/
6、接着根据当前目录下的字体建立scale文件
sudo mkfontscale
7、接着建立dir文件
sudo mkfontdir
8、然后运行
sudo fc-cache -fv
9、查看字体库是否安装成功
实际遇到的问题:
1)license.xml 要用破解版,否则会在 aposeLic.setLicense(is);这块代码出现异常。