word文件中需要转为pdf文件,word中的空格部分被程序后台动态填充,例如:

上图中带有【标】字样的位置,可以被替换为动态数据,最后被导出为pdf文件。

贴一下java工具类代码

所有过程按照下面两个java文件进行即可,1.首先调用Doc2Pdf中的方法。2.返回对应文件名。

Doc2Pdf.java文件

public class Doc2Pdf {public static boolean getLicense() {boolean result = false;try {//  license.xml应放在..\WebRoot\WEB-INF\classes路径下InputStream is = Doc2Pdf.class.getClassLoader().getResourceAsStream("license.xml");License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public static void doc2pdf(String Address) {if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();File file = new File("D:/bb.pdf");  //新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(Address);                    //Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {Doc2Pdf.doc2pdf("D:/aa.doc");}
}

DownloadUtils.java文件

public class DownloadUtils {private static final Logger log = LoggerFactory.getLogger(DownloadUtils.class);//配置信息private static Configuration configuration;//设置模板位置private static final String templateFolder = "/templates/";//生成的文件磁盘保存路径private static final String diskPath = "/root/upload/contract/goodsPrice/pdf/";static {configuration = new Configuration();configuration.setDefaultEncoding("utf-8");configuration.setClassForTemplateLoading(DownloadUtils.class, templateFolder);}/*** @Auther: Zhouxw* @Date: 2018-9-18 15:11* @Description: delFlag 是否删除该文件*/public static boolean download(String fileName, String diskPath, boolean delFlag, HttpServletRequest request, HttpServletResponse response) {InputStream bis = null;BufferedOutputStream out = null;// 获取输入流try {File file = new File(diskPath);if (!file.exists()) {return false;}bis = new BufferedInputStream(new FileInputStream(file));//配置响应configDownload(request, response, fileName);out = new BufferedOutputStream(response.getOutputStream());int len = 0;while ((len = bis.read()) != -1) {out.write(len);out.flush();}if (delFlag) {file.delete();}} catch (Exception e) {log.error("通用下载异常:{}", e);return false;} finally {if (out != null) {try {out.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (bis != null) {try {bis.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}}return true;}/*** @Auther: Zhouxw* @Date: 2018-9-25 14:59* @Description: 下载Mongo储存的文件*/public static boolean downloadFromMongo(String fileName, InputStream in, HttpServletRequest request, HttpServletResponse response) {InputStream bis = null;BufferedOutputStream out = null;/* 获取输入流 */try {bis = new BufferedInputStream(in);//配置响应configDownload(request, response, fileName);out = new BufferedOutputStream(response.getOutputStream());int len = 0;while ((len = bis.read()) != -1) {out.write(len);out.flush();}} catch (Exception e) {log.error("下载Mongo文件异常:{}", e);return false;} finally {if (out != null) {try {out.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (bis != null) {try {bis.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}}return true;}/*** @Auther: Zhouxw* @Date: 2019-7-5 17:11* @Description: 下载流文件*/public static boolean onLinePDF(String fileName, InputStream in, HttpServletRequest request, HttpServletResponse response) {InputStream bis = null;BufferedOutputStream out = null;/* 获取输入流 */try {bis = new BufferedInputStream(in);//配置响应configDownload(request, response, fileName, "inline");out = new BufferedOutputStream(response.getOutputStream());int len = 0;while ((len = bis.read()) != -1) {out.write(len);out.flush();}} catch (Exception e) {log.error("下载文件异常:{}", e);return false;} finally {if (out != null) {try {out.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (bis != null) {try {bis.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}}return true;}/*** @Auther: Lipf* @Date: 2018-11-1 16:34* @Description: 设置response头 为下载zip, 设置文件名. 应该在response写出之前被调用*/public static void configDownload(HttpServletRequest request, HttpServletResponse response, String fileName) {configDownload(request, response, fileName, "attachment");}/*** @param inline attachment 提示下载 ,inline在线预览* @Auther: Zhouxw* @Date: 2018-10-9 11:27* @Description: 设置response头 为下载zip, 设置文件名. 应该在response写出之前被调用*/public static void configDownload(HttpServletRequest request, HttpServletResponse response, String fileName, String inline) {String finalFileName = "";try {final String userAgent = request.getHeader("USER-AGENT").toLowerCase();if (userAgent != null) {if (userAgent.contains("msie") || (userAgent.indexOf("gecko") > 0 && userAgent.indexOf("rv:11") > 0)) {finalFileName = URLEncoder.encode(fileName, "UTF-8");} else if (userAgent.contains("mozilla") || userAgent.contains("chrome")) {finalFileName = new String(fileName.getBytes(), "ISO-8859-1");} else {finalFileName = URLEncoder.encode(fileName, "UTF-8");}} else {finalFileName = fileName;}} catch (UnsupportedEncodingException e) {log.error("设置响应头异常:{}", e);}/* 这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开 */response.setHeader("Content-Disposition", inline + "; filename=" + finalFileName);//response.setContentType("multipart/form-data");response.setContentType(getContentType(finalFileName));}/*** @Auther: Zhouxw* @Date: 2018-10-9 11:26* @Description: 封装压缩文件的方法*/public static void zipFile(File inputFile, ZipOutputStream zipoutputStream) {FileInputStream fis = null;BufferedInputStream bis = null;try {if (inputFile.exists()) { //判断文件是否存在if (inputFile.isFile()) {  //判断是否属于文件,还是文件夹//创建输入流读取文件fis = new FileInputStream(inputFile);bis = new BufferedInputStream(fis);//将文件写入zip内,即将文件进行打包ZipEntry ze = new ZipEntry(inputFile.getName()); //获取文件名zipoutputStream.putNextEntry(ze);//写入文件的方法,同上byte[] b = new byte[1024];long l = 0;while (l < inputFile.length()) {int j = bis.read(b, 0, 1024);l += j;zipoutputStream.write(b, 0, j);}} else {//如果是文件夹,则使用穷举的方法获取文件,写入zipFile[] files = inputFile.listFiles();for (int i = 0; i < files.length; i++) {zipFile(files[i], zipoutputStream);}}}} catch (Exception e) {log.error("压缩文件异常:{}", e);} finally {//关闭输入输出流if (null != fis) {try {fis.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (null != bis) {try {bis.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}}}/*** @param request* @param response* @param data     数据集* @param title    下载默认名称* @param ftlFile  模板名称* @throws IOException* @author: zhouxw* @date: 2018年5月16日 下午2:21:54* @Description: 根据ftl导出Word功能*/public static void exportWord(HttpServletRequest request,HttpServletResponse response,Object data,String title,String ftlFile) {File file = null;InputStream fin = null;ServletOutputStream out = null;try {Template freemarkerTemplate = configuration.getTemplate(ftlFile, "utf-8");// 调用工具类的createDoc方法生成Word文档file = createDoc(data, freemarkerTemplate);fin = new FileInputStream(file);// 设置浏览器以下载的方式处理该文件名String fileName = title + ".doc";// 配置响应configDownload(request, response, fileName);out = response.getOutputStream();byte[] buffer = new byte[512]; // 缓冲区int bytesToRead = -1;// 通过循环将读入的Word文件的内容输出到浏览器中while ((bytesToRead = fin.read(buffer)) != -1) {out.write(buffer, 0, bytesToRead);}} catch (IOException e) {log.error("导出Word异常:{}", e);} finally {if (fin != null) {try {fin.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (out != null) {try {out.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (file != null) {// 删除临时文件file.delete();}}}/*** @Auther: Zhouxw* @Date: 2019-4-9 9:32* @Description: 在线导出PDF(生成的word直接转PDF)*/public static String exportPDF(Object data,String ftlFile) {String fileName = null;File docFile = null;InputStream fin = null;FileOutputStream os = null;try {Template freemarkerTemplate = configuration.getTemplate(ftlFile, "utf-8");// 调用工具类的createDoc方法生成Word文档docFile = createDoc(data, freemarkerTemplate);fin = new FileInputStream(docFile);// 验证License 若不验证则转化出的pdf文档会有水印产生if (!Doc2Pdf.getLicense()) {return null;}long old = System.currentTimeMillis();fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";File tempFile = new File(diskPath);if (!tempFile.exists()) {tempFile.mkdirs();}File file = new File(diskPath + fileName);os = new FileOutputStream(file);//Address是将要被转化的word文档Document doc = new Document(fin);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换doc.save(os, SaveFormat.PDF);long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时} catch (Exception e) {log.error("导出Word异常:{}", e);} finally {if (fin != null) {try {fin.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (os != null) {try {os.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}if (docFile != null) {// 删除临时文件docFile.delete();}}return fileName;}/*** @param data* @param template* @return File* @author: zhouxw* @date: 2018年5月16日 下午2:19:58* @Description: 生成临时word文件*/private static File createDoc(Object data, Template template) {String time = System.currentTimeMillis() + "";String name = time + (int) ((Math.random() * 9 + 1) * 1000) + ".doc";File f = new File(name);Template t = template;Writer w = null;try {// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");t.process(data, w);} catch (Exception e) {log.error("生成Word文件异常:{}", e);} finally {if (w != null) {try {w.close();} catch (IOException e) {log.error("关闭流异常:{}", e);}}}return f;}/*** @Auther: Zhouxw* @Date: 2018-10-23 8:55* @Description: 对导出word内容特殊字符处理*/public static String specialCharacterForContent(String str) {log.info("特殊字符处理前:{}", str);String result = str.replace(";", ";").replace(",", ",").replace("&", "&amp;").replace("<", "&lt;");log.info("特殊字符处理后:{}", result);return result;}/*** @Auther: Zhouxw* @Date: 2018-10-23 8:55* @Description: 对导出文件名称特殊字符处理(参照windows对文件名特殊字符处理)*/public static String specialCharacterForTitle(String str) {log.info("特殊字符处理前:{}", str);String result = str.replace(":", ":").replace("/", "").replace("\\", "").replace("?", "?").replace(",", ",").replace("*", "").replace("<", "《").replace(">", "》").replace("\"", "'").replace("|", "").replace(";", "").replace("&amp", "").replace("&lt", "");log.info("特殊字符处理后:{}", result);return result;}/*** @Auther: Lipf* @Date: 2018-11-1 16:00* @Description: 根据“文件名的后缀”获取文件内容类型(而非根据File.getContentType()读取的文件类型)*/public static String getContentType(String returnFileName) {String contentType = "application/octet-stream";if (returnFileName.lastIndexOf(".") < 0) {return contentType;}returnFileName = returnFileName.toLowerCase();returnFileName = returnFileName.substring(returnFileName.lastIndexOf(".") + 1);if (returnFileName.equals("html") || returnFileName.equals("htm") || returnFileName.equals("shtml")) {contentType = "text/html";} else if (returnFileName.equals("apk")) {contentType = "application/vnd.android.package-archive";} else if (returnFileName.equals("sis")) {contentType = "application/vnd.symbian.install";} else if (returnFileName.equals("sisx")) {contentType = "application/vnd.symbian.install";} else if (returnFileName.equals("exe")) {contentType = "application/x-msdownload";} else if (returnFileName.equals("msi")) {contentType = "application/x-msdownload";} else if (returnFileName.equals("css")) {contentType = "text/css";} else if (returnFileName.equals("xml")) {contentType = "text/xml";} else if (returnFileName.equals("gif")) {contentType = "image/gif";} else if (returnFileName.equals("jpeg") || returnFileName.equals("jpg")) {contentType = "image/jpeg";} else if (returnFileName.equals("js")) {contentType = "application/x-javascript";} else if (returnFileName.equals("atom")) {contentType = "application/atom+xml";} else if (returnFileName.equals("rss")) {contentType = "application/rss+xml";} else if (returnFileName.equals("mml")) {contentType = "text/mathml";} else if (returnFileName.equals("txt")) {contentType = "text/plain";} else if (returnFileName.equals("jad")) {contentType = "text/vnd.sun.j2me.app-descriptor";} else if (returnFileName.equals("wml")) {contentType = "text/vnd.wap.wml";} else if (returnFileName.equals("htc")) {contentType = "text/x-component";} else if (returnFileName.equals("png")) {contentType = "image/png";} else if (returnFileName.equals("tif") || returnFileName.equals("tiff")) {contentType = "image/tiff";} else if (returnFileName.equals("wbmp")) {contentType = "image/vnd.wap.wbmp";} else if (returnFileName.equals("ico")) {contentType = "image/x-icon";} else if (returnFileName.equals("jng")) {contentType = "image/x-jng";} else if (returnFileName.equals("bmp")) {contentType = "image/x-ms-bmp";} else if (returnFileName.equals("svg")) {contentType = "image/svg+xml";} else if (returnFileName.equals("jar") || returnFileName.equals("var")|| returnFileName.equals("ear")) {contentType = "application/java-archive";} else if (returnFileName.equals("doc")) {contentType = "application/msword";} else if (returnFileName.equals("pdf")) {contentType = "application/pdf";} else if (returnFileName.equals("rtf")) {contentType = "application/rtf";} else if (returnFileName.equals("xls")) {contentType = "application/vnd.ms-excel";} else if (returnFileName.equals("ppt")) {contentType = "application/vnd.ms-powerpoint";} else if (returnFileName.equals("7z")) {contentType = "application/x-7z-compressed";} else if (returnFileName.equals("rar")) {contentType = "application/x-rar-compressed";} else if (returnFileName.equals("swf")) {contentType = "application/x-shockwave-flash";} else if (returnFileName.equals("rpm")) {contentType = "application/x-redhat-package-manager";} else if (returnFileName.equals("der") || returnFileName.equals("pem")|| returnFileName.equals("crt")) {contentType = "application/x-x509-ca-cert";} else if (returnFileName.equals("xhtml")) {contentType = "application/xhtml+xml";} else if (returnFileName.equals("zip")) {contentType = "application/zip";} else if (returnFileName.equals("mid") || returnFileName.equals("midi")|| returnFileName.equals("kar")) {contentType = "audio/midi";} else if (returnFileName.equals("mp3")) {contentType = "audio/mpeg";} else if (returnFileName.equals("ogg")) {contentType = "audio/ogg";} else if (returnFileName.equals("m4a")) {contentType = "audio/x-m4a";} else if (returnFileName.equals("ra")) {contentType = "audio/x-realaudio";} else if (returnFileName.equals("3gpp")|| returnFileName.equals("3gp")) {contentType = "video/3gpp";} else if (returnFileName.equals("mp4")) {contentType = "video/mp4";} else if (returnFileName.equals("mpeg")|| returnFileName.equals("mpg")) {contentType = "video/mpeg";} else if (returnFileName.equals("mov")) {contentType = "video/quicktime";} else if (returnFileName.equals("flv")) {contentType = "video/x-flv";} else if (returnFileName.equals("m4v")) {contentType = "video/x-m4v";} else if (returnFileName.equals("mng")) {contentType = "video/x-mng";} else if (returnFileName.equals("asx") || returnFileName.equals("asf")) {contentType = "video/x-ms-asf";} else if (returnFileName.equals("wmv")) {contentType = "video/x-ms-wmv";} else if (returnFileName.equals("avi")) {contentType = "video/x-msvideo";}return contentType;}}

缺少jar包可以找我私聊

Java后台代码word转pdf文件下载(类库参考)附jar包相关推荐

  1. java关于对于word或者pdf文件的批量下载实现,其中包括(Java实现创建word文档模板,根据模板导出word文档)

    本次需求是,pdf是表格类型的文件,我这里使用了word模板进行处理.但由于是多个文件一起导出,因此全部放到一个目录底下进行打包下载. ## 整体思路 /*** 下载思路:* 1.查询出数据后:* 2 ...

  2. Java开发中word转pdf那件事

    事件背景 由于项目需要,最新开始研究起word转pdf了,本以为应该是一件很简单的事情,网络上应该已经有很成熟的解决方案了,毕竟在电脑上使用wps或office操作只需要另存为pdf即可,结果一顿百度 ...

  3. 后台实现word转pdf输出文件流

    首先需要安装好LibreOffice,支持免费使用,安装包太大没法上传,可以去官网下载:https://zh-cn.libreoffice.org/download/download/ 根据系统选择需 ...

  4. java后台代码实现笛卡尔积

    java后台代码实现笛卡尔积

  5. 关于java中实现word转pdf

    1.java中实现word转pdf几种方式如下 1.使用jacob(Java COM Bridge)操作offfice的方式,基于这种方式无论是水印还是格式都可以完美转换:但是这个方式都只是基于win ...

  6. android studio开发十一 Library第三方类库源码, Jar包和SO库

    原创: 发现android里面不熟悉的东西太多了,查了好多资料,终于搞清楚 Library第三方类库源码, Jar包和SO库这些都是干什么的了,怎么使用它们了. [Library第三方类库源码] Ja ...

  7. Java通过JNI调用C++动态链接库dll,并打在jar包内 ——JNA-JNI(一)

    Java通过JNI调用C++动态链接库dll,并打在jar包内--JNA-JNI(一) 系列文章: Java通过JNI调用C++动态链接库dll,并打在jar包内 --JNA-JNI(一) Java使 ...

  8. java实现word、pdf文件下载功能

    在SpringMVC的开发过程中,有时需要实现文档的下载功能.文档的下载功能涉及到了java IO流操作的基础知识,下面本文详细介绍java如何实现后台文档下载功能. 首先根据文档在项目中的存储路径建 ...

  9. java代码word转pdf

    转载地址:https://blog.csdn.net/csdnFlyFun/article/details/79523262 ------------------------------------- ...

最新文章

  1. PyTorch入门与代码模板
  2. python微型web框架flask介绍
  3. 深入理解分布式技术 - 配置中心
  4. Tensorflow Object detection API 在 Windows10 配置
  5. 抢了个票,还以为发现了12306的系统BUG
  6. servlet下根据相对路径找资源
  7. CUDA C编程权威指南 第五章 共享内存和常量内存
  8. Python之认识世界
  9. oracle执行大sql,mybatis连接oracle执行sql语句出现ORA
  10. 流媒体音视频开发和架构等
  11. 抖音无水印解析网站源码
  12. 【小白写代码之九九乘法表,用C/C++来实现】
  13. VLAN-TAG超经典解释
  14. Chuck语言学习笔记——0.前言:我为什么要学习这门语言
  15. Neo4j 第二篇:图形数据库
  16. vue中引入高德地图并多点标注
  17. git中merge分支到master产生冲突
  18. 推荐 | PyPi官网发布第三方库:python-office,专为Python自动化办公而生。
  19. 计算机应用世界排名,全球计算机杂志排名
  20. Qt按键键值 与 相关字符串 的映射表

热门文章

  1. 通达信版弘历软件指标_通达信仿弘历收费指标
  2. 计算风险指标:最大回撤、计算风险收益指标:夏普比率、利用最大回撤和夏普比筛选基金、比较3只股票的夏普指数
  3. 微信小程序:常用功能6——点击图片,实现图片的预览功能wx.previewImage(Object object, boolean showmenu)
  4. linux安装jenkins启动卡在初始页面 | 插件下载不了,报SSL错误等问题避坑 | No valid crumb was included in request for /ajaxBuildQ
  5. CWnd::WindowProc的理解
  6. 四象限分析法分析你是否适合做管理
  7. 让苹果iOS的手机iPhone和电脑Safari浏览器支持油猴脚本
  8. uni-app(H5)拼图游戏
  9. 南昌大学计算机学硕和专硕,南昌大学同等学力是专硕还是学硕
  10. 图像测量技术:面积测量