1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 使用Freemark和aspose.word实现动态word转pdf

使用Freemark和aspose.word实现动态word转pdf

时间:2019-12-06 23:47:39

相关推荐

使用Freemark和aspose.word实现动态word转pdf

前言

因为公司业务需要实现业务人员提供wodr模板,然后系统填充数据生成pdf文件,本文的想法是通过Freemark填充数据生成word再通过aspose.word把word文档转为pdf文档。

本文比较有局限性,如果有类似业务可以参考一下

因为要保证word样式不被打乱,在之前尝试过使用wkhtmltopdf,但是wkhtmltopdf如果要放在linux上很麻烦(ps:公司服务器是docker加内网),而且wkhtmltopdf相当于一个挂件,所以换了一种方式

所需maven,本项目是springboot

<dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>15.8.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>

一、word转成ftl模板?

首先准备一个wodr文档

然后另存为xml格式

然后把文件名后缀改成ftl

顺便改个英文名

这样一个固定样式的ftl模板就拿到了

二、使用freemarker填充数据,并生成pdf

代码如下:

import com.aspose.words.Document;import com.aspose.words.FontSettings;import com.aspose.words.SaveFormat;import freemarker.template.Configuration;import freemarker.template.Template;import mons.lang.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.io.ResourceLoader;import org.springframework.ui.freemarker.SpringTemplateLoader;import java.io.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.Map;/*** @Author: Xyf* @Date: /9/5 11:07*/public class Dome {@Autowiredprivate ResourceLoader resourceLoader;/**** @param map 模板所需数据* @param name 生成pdf文件名* @param templatesName 模板名* @return* @throws Exception*/public String exportToWord(Map<String,Object> map, String name, String templatesName) throws Exception {String osName = System.getProperties().getProperty("os.name");//提前生成wordString fix=(osName.equalsIgnoreCase("Linux")?"/home/":"E:\\pdf\\测试2")+name+".doc";File file = new File(fix);String PDFfileName =null;Writer out =null;try {//读取ftl文件,填充数据后写入提前生成的word中SpringTemplateLoader templateLoader = new SpringTemplateLoader(resourceLoader, "classpath:templates");Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);configuration.setTemplateLoader(templateLoader);configuration.setDefaultEncoding("UTF-8");Template template = configuration.getTemplate(templatesName+".ftl");out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"), 10240);template.process(map, out);out.close();out=null;//如果不需要pdf后面这个个方法可以不用调用了//直接 PDFfileName=fix; 就行了//生成pdfPDFfileName = word2Pdf(file.getCanonicalPath(), null);return PDFfileName;} catch (Exception e) {e.printStackTrace();throw e;} finally {if(out!=null){out.close();}//下载完成删除临时文件if(Files.exists(Paths.get(fix))){Files.delete(Paths.get(fix));}}}/*** @Description: 验证aspose.word组件是否授权:无授权的文件有水印标记*/public static boolean getLicense() {boolean result = false;try {String s = "<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>";ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes());//InputStream inputStream = Xml2Word2Pdf.class.getClassLoader().getResourceAsStream("\\license.xml");com.aspose.words.License license = new com.aspose.words.License();license.setLicense(inputStream);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 使用aspose.word把word文档转为pdf文档** @param sourceFile word文档绝对路径(如:D:/templates/order.doc)* @param destFile pdf文档绝对路径(如:D:/templates/order.pdf)*/public static String word2Pdf(String sourceFile, String destFile) throws Exception {destFile = StringUtils.isEmpty(destFile) ? sourceFile.replace(".doc", ".pdf") : destFile;// 验证License 若不验证则转化出的pdf文档会有水印产生if (!getLicense()) {throw new Exception("生成PDF文档,验证License失败!");}FileOutputStream os = null;try {long old = System.currentTimeMillis();File file = new File(destFile); //新建一个空白pdf文档os = new FileOutputStream(file);String osName = System.getProperties().getProperty("os.name");if(osName.equalsIgnoreCase("Linux")){//指定中文字体目录,因为在linux里不支持中文字体,需要把windows的字体一起打包上去,// docker直接把字体文件复制到docker里面就好了,不是docker直接把字体文件放的服务器上就行//怎么找字体文件百度一下 aspose.word linux中文字体就好了FontSettings.setFontsFolder("/home/Fonts"+File.separator, true);}Document doc = new Document(sourceFile); // 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();throw new Exception("生成PDF文档失败!");}finally {if (os != null) {try {os.flush();os.close();} catch (IOException e) {e.printStackTrace();}}}return destFile;}}

总结

本文最主要的目的是为了实现只有一个word模板的情况下实现动态生成pdf,还有很多可以改进的地方,比如最后生成的url可以转成在线的等等

jar包maven可能会下载不下来

aspose-words-15.8.0-jdk16.jar

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。