注:这里只能转换docx文件,doc不行,源码在文末。

可以在windows,linux上运行,增加了内容替换功能,因为有些文档内容需要我们用代码来动态生成。

下面是具体操作步骤:

  • maven依赖
<!-- docx转pdf --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.11</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.1</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.3</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>org.apache.poi.xwpf.converter.pdf</artifactId><version>1.0.6</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId><version>1.0.6</version></dependency><dependency><groupId>org.docx4j</groupId><artifactId>docx4j-ImportXHTML</artifactId><version>3.2.0</version></dependency><!-- docx转pdf end -->
  • java代码
package com.gitee.docx2pdf;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;/*** 文档工具类*/
public class DocUtil {public static void main(String[] args) throws Exception {String docx = "1.docx";String pdf = "1.pdf";// 直接转换InputStream docxStream = DocUtil.class.getClassLoader().getResourceAsStream(docx);byte[] pdfData = docxToPdf(docxStream);FileUtils.writeByteArrayToFile(new File(pdf), pdfData);// 替换内容后转换例子InputStream docxStream2 = DocUtil.class.getClassLoader().getResourceAsStream("2.docx");Map<String, String> data = new HashMap<String, String>();data.put("{title}", "标题内容");data.put("{username}", "张三");byte[] pdfData2 = bindDocxDataAndToPdf(docxStream2, data);FileUtils.writeByteArrayToFile(new File("data.pdf"), pdfData2);System.out.println("finished.");}/*** 替换docx文件内容,并转换成PDF* *@param input*@param data*@return*@throws Exception*/public static byte[] bindDocxDataAndToPdf(InputStream input, Map<String, String> data) throws Exception {byte[] replacedContent = replaceDocxContent(input, data);byte[] pdfData = docxToPdf(new ByteArrayInputStream(replacedContent));return pdfData;}/*** docx转成pdf* *@param docxStream*            docx文件流*@return 返回pdf数据*@throws Exception*/public static byte[] docxToPdf(InputStream docxStream) throws Exception {ByteArrayOutputStream targetStream = null;XWPFDocument doc = null;try {doc = new XWPFDocument(docxStream);PdfOptions options = PdfOptions.create();// 中文字体处理options.fontProvider(new IFontProvider() {@Overridepublic Font getFont(String familyName, String encoding, float size, int style, java.awt.Color color) {try {BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font fontChinese = new Font(bfChinese, 12, style, color);if (familyName != null)fontChinese.setFamily(familyName);return fontChinese;} catch (Exception e) {e.printStackTrace();return null;}}});targetStream = new ByteArrayOutputStream();PdfConverter.getInstance().convert(doc, targetStream, options);return targetStream.toByteArray();} catch (IOException e) {throw new Exception(e);} finally {IOUtils.closeQuietly(targetStream);}}/*** docx转换成html内容* *@param docxIn*            docx文件输入流*@return*@throws Exception*/public static byte[] docxToHtml(InputStream docxIn) throws Exception {ByteArrayOutputStream out = null;try {XWPFDocument document = new XWPFDocument(docxIn);XHTMLOptions options = XHTMLOptions.create();out = new ByteArrayOutputStream();XHTMLConverter.getInstance().convert(document, out, options);return out.toByteArray();} catch (IOException e) {throw new Exception(e);} finally {IOUtils.closeQuietly(out);}}/*** 替换docx内容* *@param in*            docx输入流*@param map*            替换键值对*@return 返回替换后的文件流*@throws Exception*/public static byte[] replaceDocxContent(InputStream in, Map<String, String> map) throws Exception {// 读取word模板XWPFDocument hdt = null;ByteArrayOutputStream out = null;try {hdt = new XWPFDocument(in);// 替换段落内容List<XWPFParagraph> paragraphs = hdt.getParagraphs();replaceParagraphsContent(paragraphs, map);// 替换表格内容List<XWPFTable> tables = hdt.getTables();// 读取表格for (XWPFTable table : tables) {int rcount = table.getNumberOfRows();// 遍历表格中的行for (int i = 0; i < rcount; i++) {XWPFTableRow row = table.getRow(i);// 遍历行中的单元格List<XWPFTableCell> cells = row.getTableCells();for (XWPFTableCell cell : cells) {List<XWPFParagraph> cellParagraphs = cell.getParagraphs();replaceParagraphsContent(cellParagraphs, map);}}}out = new ByteArrayOutputStream();hdt.write(out);return out.toByteArray();} catch (IOException e) {throw new Exception(e.getMessage());} finally {IOUtils.closeQuietly(out);}}private static void replaceParagraphsContent(List<XWPFParagraph> paragraphs, Map<String, String> map) {for (XWPFParagraph paragraph : paragraphs) {List<XWPFRun> runs = paragraph.getRuns();for (XWPFRun run : runs) {String text = run.getText(0);if (text != null) {boolean isSetText = false;for (Entry<String, String> entry : map.entrySet()) {String key = entry.getKey();if (text.indexOf(key) != -1) {// 在配置文件中有这个关键字对应的键String value = entry.getValue();if (value == null) {throw new RuntimeException(key + "对应的值不能为null");}// 文本替换text = text.replace(key, value);isSetText = true;}}if (isSetText) {run.setText(text, 0);}}}}}
}
  • 添加字体资源文件

把字体资源文件添加到resources下面,具体内容在下面的源码中可查看。
这里的资源文件是直接从itextasian-1.5.2.jar下拷贝过来的,因为itextasian-1.5.2.jar在中央仓库已经下载不到了。

最后运行DocUtil 中的main方法进行测试。

源代码:点击前往

docx文档转pdf文件相关推荐

  1. java使用Aspose.words实现word文档转pdf文件

    引入原因: 感觉openOffice问题还是比较多的. 1. 比如经常出现8100端口问题,虽然kill了就行,但是还是多了一份操作. 2. 出现少数docx无法预览的问题.(已经修改过源码兼容doc ...

  2. 如何将CSDN文档输出PDF文件?

    简 介: 根据生成文档的需要,在CSDN上寻找一些介绍将MARKDOWN文档生成PDF博文.根据他们介绍的方法,测试打印的效果.特别是对于CSDN新增加的一些显示元素的清理,可以生成更加干净完整的PD ...

  3. 将Word文档转换为PDF文件的步骤和技巧

    在日常工作和学习中,我们经常需要将Word文档转换为PDF文件.PDF文件的格式稳定.排版精美.易于共享等特点使其成为了许多场合下的首选文件格式.在本文中,我将为大家介绍将Word文档转换为PDF文件 ...

  4. 微信公众号怎么添加附件?比如word文档,pdf文件等

    微信公众号怎么添加附件?比如word文档,pdf文件等 我们都知道创建一个微信公众号,在公众号中发布一些文章是非常简单的,但公众号添加附件下载的功能却被限制,如今可以使用小程序"微附件&qu ...

  5. java docx转pdf_java word/doc/docx文档转PDF 加水印

    本文实例讲述了java实现word文档转pdf并添加水印的方法.分享给大家供大家参考,具体如下: 前段时间,项目需要将上传的Word文档在浏览器浏览,思来想去,把word文档转成pdf就好了,于是乎研 ...

  6. 如何在LibreOffice中使用所有者和用户密码保护文档和PDF文件

    There are two ways to protect a PDF file: an owner password and a user password. We'll explain the p ...

  7. doc转pdf java不失真_java使用Aspose实现 word文档转pdf文件高效不失真

    java使用Aspose word文档转pdf功能实现 主要步骤 使用Aspose进行文档转换,首先引入相应的jar包到系统环境 项目resource下导入license.xml文件 使用Aspose ...

  8. 【PPT】PPT文档导出PDF文件时,去掉右上角时间

    PPT文档需要导出为PDF文件时,右上角页眉会出现时间戳,有时候不需要时间,如何去掉时间戳呢? Win10+Office2019 当需要将多页PPT打印在一张纸上时,右上角页眉会自动出现当前时间戳20 ...

  9. java命令行利用libreoffice将office文档转换为pdf文件失败的解决方案

    原因:libreoffice同时只支持两个文档转换的命令行,多于两个的命令行不会进行文档转换. 解决方案:在线程池的线程中,利用java阻塞队列BlockingQueue,设置容量为2,同时只允许两个 ...

最新文章

  1. android频道编辑实现_短说频道功能详解—构建你社区的小门户
  2. centos7 安装python3
  3. 基于MapWinGis的开发探索(三)--改善缩放、渲染、显示文本
  4. python变量输出到文件_使用函数将多个变量写入文件
  5. Java面试题 20在面向对象编程里,经常使用is-a来说明对象之间的继承关系
  6. mysql 快速插入(insert)多条记录
  7. Lsky Pro兰空图床程序网站PHP源码
  8. CLR via C#
  9. html中单选怎么写,在HTML中select标签怎样实现单选和多选
  10. linux的O的字体让我满意那些
  11. C#_MVC 自定义AuthorizeAttribute实现权限管理
  12. 使用valgrind检查内存越界
  13. 网易云通信 java 登录,网易云IM(即时通讯) 集成指南(Android)
  14. 硬盘检测重映射扇区计数失败
  15. ARGB颜色与int相互转换
  16. Oracle 21版Database In-Memory LivaLabs实验(上)
  17. JWT无状态登录+跨域问题
  18. 绩效(不同部门)修正
  19. 世界上第一台计算机内存容量,29、世界上第一台电子计算机ENIAC诞生于.doc
  20. dw连接mysql数据库原理_Dreamweaver中连接SQL Server数据库代码

热门文章

  1. VScode远程连接下,无法写入文件问题解决。
  2. STM32串口通信(串口中断、FIFO机制)之安富莱代码学习笔记
  3. java给教师排课模块,java选排课系统
  4. 丹佛斯变频器al13故障_丹佛斯变频器FC302显示A33故障代码维修案例
  5. 迟滞比较器Hysteresiswindow和comparator(窗口比较器)原理
  6. java版的短信接口封装,免费送给你,自带200条短信
  7. 【设计原则】KISS原则与YAGNI原则
  8. 网页UI 素材 资源
  9. 我们为什么鄙视Facebook
  10. Facebook数据泄露事件解读