所需jar包地址

        <!-- java 读取word文件里面的加颜色的字体  转pdf 使用  --><dependency><groupId> e-iceblue </groupId><artifactId>spire.doc.free</artifactId><version>3.9.0</version></dependency><!--poi 的相关组件 --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><!-- 不添加此包会提示错误 :   org.openxmlformats.schemas.wordprocessingml.x2006.main.FontsDocument$Factory   --><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>org.apache.poi.xwpf.converter.pdf</artifactId><version>1.0.6</version></dependency><!-- 用于  word 转pdf  --><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>xdocreport</artifactId><version>2.0.2</version></dependency><!-- pdf 添加水印  对PDF文件的操作 --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.1</version></dependency><!-- PDF文件 字体 防止中文乱码  --><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><!--基于 poi实现word数据的替换 --><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.9.1</version></dependency><!--如果下载jar失败,说明下载jar失败,需要以下的maven依赖[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException--> <repository><id>com.e-iceblue</id><url>http://repo.e-iceblue.cn/repository/maven-public/</url></repository></repositories><!--        <dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.25</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId><version>1.0.6</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.document</artifactId><version>2.0.2</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>org.apache.poi.xwpf.converter.core</artifactId><version>1.0.6</version></dependency>--><!-- 打包使用,需要配置 --><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><!-- 打包时会将本地jar一起打包 --><configuration><includeSystemScope>true</includeSystemScope></configuration></plugin></plugins></build>

执行代码main方法运行


import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.*;public class TestWordToPDF {public static void main(String[] args) throws Exception {long start = System.currentTimeMillis();String docxPath =  "C:\\Users\\admin-xu\\Desktop\\11\\test.docx";String pdfPath =  "C:\\Users\\admin-xu\\Desktop\\11\\test2.pdf";File file = new File( docxPath);InputStream inputStream = new FileInputStream(file);ByteArrayOutputStream pdfBaos = new ByteArrayOutputStream();XWPFDocument xwpfDocument = new XWPFDocument(inputStream);fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(xwpfDocument, pdfBaos, PdfOptions.create());inputStream.close();xwpfDocument.close();byte[] pdfArray = null;pdfArray = pdfBaos.toByteArray();pdfBaos.close();InputStream pdfInputStream = new ByteArrayInputStream( pdfArray ) ;FileOutputStream fileOutputStream = new FileOutputStream(pdfPath);addWaterMark(pdfInputStream , fileOutputStream);long end = System.currentTimeMillis();System.out.println("执行时间: " + ((end - start) / 1000) + "秒");}//给PDF文件添加水印public static void addWaterMark(InputStream pdfInputStream ,   FileOutputStream fileOutputStream) {try {// 原PDF文件PdfReader reader = new PdfReader(pdfInputStream);// 输出的PDF文件内容PdfStamper pdfStamper = new PdfStamper(reader,   fileOutputStream );// 字体 来源于 itext-asian JAR包BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);PdfGState pdfGState = new PdfGState();// 设置透明度pdfGState.setFillOpacity(0.2f);pdfGState.setStrokeOpacity(0.4f);int totalPage = reader.getNumberOfPages() + 1;for (int i = 1; i < totalPage; i++) {// 内容上层
//          PdfContentByte content = stamper.getOverContent(i);// 内容下层PdfContentByte pdfContentByte = pdfStamper.getUnderContent(i);pdfContentByte.beginText();// 字体添加透明度pdfContentByte.setGState(pdfGState);// 添加字体大小等pdfContentByte.setFontAndSize(baseFont, 20);// 添加范围pdfContentByte.setTextMatrix(70, 200);//  具体位置 内容   多少行  多少列  旋转多少度 共360度for (int a = 0; a < 3; a++) { // 一页几排for (int j = 0; j < 3; j++) { // 一排几个int x =  70 + 170 * j ;   // 横向  宽int y =  170 + 200 *  a ;  // 纵向  高pdfContentByte.showTextAligned(Element.ALIGN_BOTTOM, "机密文件"  , x, y, 45); // 45 是水印旋转的角度}}pdfContentByte.endText();}// 关闭pdfStamper.close();reader.close();} catch (Exception e) {e.printStackTrace();}}
}

转换前的word

转换后的 pdf

执行结果和时间,项目中实际测试大概是5-6秒左右(和服务器性能相关)

实际代码使用,通过浏览器下载

// 转换后 通过浏览器下载// word 替换数据后 下载   //     /replaceWordToPDF/exportWordPDF@GetMapping(value = "/exportWordPDF")public R<?> exportWordTest(@RequestParam Map<String , Object> mapCon, HttpServletResponse response) throws Exception {long a1 = System.currentTimeMillis();R resultBody = replaceWordDataService.replaceWord( mapCon );if(resultBody.getCode() == 0 ){byte[] array = null;ExportWordDTO data = (ExportWordDTO) resultBody.getData();XWPFTemplate template = data.getXwpfTemplate();ByteArrayOutputStream baos = new ByteArrayOutputStream();template.writeAndClose( baos );//文档写入流array = baos.toByteArray();baos.close();template.close();// 替换后的word转流InputStream inputStream = new ByteArrayInputStream( array ) ;ByteArrayOutputStream pdfBaos = new ByteArrayOutputStream();long  a2   =  System.currentTimeMillis();//  word 转pdfXWPFDocument xwpfDocument = new XWPFDocument(inputStream);fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(xwpfDocument, pdfBaos, PdfOptions.create());inputStream.close();xwpfDocument.close();byte[] pdfArray = null;pdfArray = pdfBaos.toByteArray();pdfBaos.close();// pdf 文件InputStream pdfInputStream = new ByteArrayInputStream( pdfArray ) ;response.setContentType("application/octet-stream");response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(  data.getOutFileName()+".pdf", "UTF-8"));OutputStream out = response.getOutputStream();long  a3   =  System.currentTimeMillis();// 添加水印// 原PDF文件PdfReader reader = new PdfReader(pdfInputStream);// 输出的PDF文件内容PdfStamper stamper = new PdfStamper(reader, out);// 字体 来源于 itext-asian JAR包BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);PdfGState gs = new PdfGState();// 设置透明度gs.setFillOpacity(0.2f);gs.setStrokeOpacity(0.4f);int totalPage = reader.getNumberOfPages() + 1;System.out.println( totalPage );for (int i = 1; i < totalPage; i++) {// 内容上层
//          PdfContentByte content = stamper.getOverContent(i);// 内容下层PdfContentByte content = stamper.getUnderContent(i);content.beginText();// 字体添加透明度content.setGState(gs);// 添加字体大小等content.setFontAndSize(baseFont, 20);// 添加范围content.setTextMatrix(70, 200);// 具体位置 内容 旋转多少度 共360度   复制艺术字并设置多行多列位置 ( 设置几排  )  //  多少列for (int a = 0; a < 3; a++) { // 一页几排for (int j = 0; j < 3; j++) { // 一排几个int x =  70 + 170 * j ;   // 横向  宽int y =  170 + 200 *  a ;  // 纵向  高content.showTextAligned(Element.ALIGN_BOTTOM, "户用光伏电站签约专用"  , x, y, 45);}}content.endText();}// 关闭stamper.close();reader.close();pdfInputStream.close();out.close();long  a4   =  System.currentTimeMillis();System.out.println("word替换时间: " + ((a2 - a1) ) + "毫秒");System.out.println("word转pdf时间: " + ((a3 - a2) ) + "毫秒");System.out.println("添加水印时间: " + ((a4 - a3) ) + "毫秒");System.out.println("共计用时: " + ((a4 - a1) ) + "毫秒");PoitlIOUtils.closeQuietlyMulti(template,  out);return null;}else {return R.fail().msg(resultBody.getMsg());}}

获取转换后的pdf byte[]数组数组

注意这里有个坑 在关闭流的时候才往(输出流)写内容了,上面只是定义 并没有写到输入流 ByteArrayOutputStream,放到close上面是没数据的,只能放到 close 的下面,因为这一步才开始写数据

// word 替换数据后 转换 pdf 添加水印后 获取字节数组 通过字节数组上传到文件服务器 @GetMapping(value = "/exportWordTestUrl")public R<?> exportWordTestUrl(@RequestParam Map<String , Object> mapCon  ) throws Exception {R resultBody = replaceWordDataService.replaceWord( mapCon );if(resultBody.getCode() == 0 ){byte[] array = null;ExportWordDTO data = (ExportWordDTO) resultBody.getData();XWPFTemplate template = data.getXwpfTemplate();ByteArrayOutputStream baos = new ByteArrayOutputStream();template.writeAndClose( baos );//文档写入流array = baos.toByteArray();baos.close();template.close();// 替换后的word转流InputStream inputStream = new ByteArrayInputStream( array ) ;ByteArrayOutputStream pdfBaos = new ByteArrayOutputStream();//  word 转pdfXWPFDocument xwpfDocument = new XWPFDocument(inputStream);fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(xwpfDocument, pdfBaos, PdfOptions.create());inputStream.close();xwpfDocument.close();byte[] pdfArray = null;pdfArray = pdfBaos.toByteArray();pdfBaos.close();// pdf 文件InputStream pdfInputStream = new ByteArrayInputStream( pdfArray ) ;ByteArrayOutputStream out = new ByteArrayOutputStream();// 添加水印// 原PDF文件PdfReader reader = new PdfReader(pdfInputStream);// 输出的PDF文件内容PdfStamper stamper = new PdfStamper(reader,  out );// 字体 来源于 itext-asian JAR包BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);PdfGState gs = new PdfGState();// 设置透明度gs.setFillOpacity(0.2f);gs.setStrokeOpacity(0.4f);int totalPage = reader.getNumberOfPages() + 1;for (int i = 1; i < totalPage; i++) {// 内容上层
//          PdfContentByte content = stamper.getOverContent(i);// 内容下层PdfContentByte content = stamper.getUnderContent(i);content.beginText();// 字体添加透明度content.setGState(gs);// 添加字体大小等content.setFontAndSize(baseFont, 20);// 添加范围content.setTextMatrix(70, 200);// 具体位置 内容 旋转多少度 共360度   复制艺术字并设置多行多列位置 ( 设置几排  )  //  多少列for (int a = 0; a < 3; a++) { // 一页几排for (int j = 0; j < 3; j++) { // 一排几个int x =  70 + 170 * j ;   // 横向  宽int y =  170 + 200 *  a ;  // 纵向  高content.showTextAligned(Element.ALIGN_BOTTOM, "户用光伏电站签约专用"  , x, y, 45);}}content.endText();}pdfInputStream.close();// 注意这里有个坑  在关闭流的时候才往(输出流)写内容了,上面只是定义 并没有写到输入流   ByteArrayOutputStream,放到close上面是没数据的,只能放到 close 的下面,// 因为这一步才开始写数据stamper.close();reader.close();byte[] bytes =  out.toByteArray();out.close();PoitlIOUtils.closeQuietlyMulti(template,  out);R<ResultFileModel> upload = remoteFileService.upload(bytes, 1, applicationName,  "户光伏电站签约专用.pdf");if (null !=  upload && upload.getCode() == 0){// 将url 存入数据库ResultFileModel fileModel = upload.getData();String path = fileModel.getAddress() +    fileModel.getPath();replaceWordDataService.updatePdfUrl( path ,    mapCon.get("-data_id-") .toString()  );return R.ok().data("添加成功");}else {return R.fail().msg( "文件上传失败!" );}}return R.fail().msg(resultBody.getMsg());}

另外一种方法

java word转换pdf(先自定义添加水印 后转换pdf)_My--Style的博客-CSDN博客

java word转pdf 后通过 PdfReader 和 PdfStamper对pdf添加水印 通过poi等组件实现相关推荐

  1. java word openoffice_java 使用openoffice 转换文档,成.pdf,实现在线预览效果

    1. 下载 openoffice 地址 https://pan.baidu.com/s/1dfpoG6zlawoW1pqpDvBL0A 密码: v4ej 如果上面的地址无法访问请访问这个地址:下载地址 ...

  2. PPT转PDF后,ppt的动画分pdf多页显示方法(适用于office做的动画)

    1.office打开ppt 2.先点颜色,在点宏 3.输入宏名,点创建 4.全选,粘贴以下代码 Option ExplicitSub AddElements() Dim shp As ShapeDim ...

  3. java使用poi-tl导出word及转换PDF后的合并导出pdf

    1.背景 为某单位开发的一款项目申报审批系统,用户需求在申报阶段填写的信息资料能够导出PDF.且项目申报的报告正文为用户上传,所以需要合并导出. 2.问题 在项目初期阶段使用的是PDF的预设模板导出, ...

  4. Java word转pdf Linux/windows跨平台 格式完美(利用命令行调用libreoffice)

    参考了里面的libreoffice的用法:https://blog.csdn.net/qwert678000/article/details/72770109 需求描述 最近在做word报表的自动生成 ...

  5. Java WORD转换PDF 并添加水印 (附赠jar提取链接)

    Java WORD转换PDF 并添加水印 直接上代码 实现功能 docx文档转换为PDF 转换之后排版不混乱 使用工具(Jar包) aspose-words-15.8.0-jdk16.jar(用于PD ...

  6. 关于FreeMarker生成word文档后转换为pdf得解决方法及常见问题

    关于FreeMarker生成word文档后转换为pdf得解决方法及常见问题 最近在做一个项目要求之前下载出的word简历直接变成pdf 格式进行展现.因为格式比较复杂,所以采用的时模板并用Freema ...

  7. Java word动态数据填充并转为pdf最详细的讲解附带项目

    Java Word数据动态填充,并将word转为pdf 适用范围: 1.已有word模板,word中的一些数据需要动态生成. 2.word转为pdf 本文章讲解的内容是一个完整的适用流程.就是首先是一 ...

  8. java word转pdf,docx4j转pdf,docx4j导出pdf乱码,docx4j导出pdf丢失插画和图片,aspose将word转pdf 一共两种方法

    前言:一共有docx4j转pdf,aspose转pdf两种方式,不需要设置模板!!! java转pdf目前本人使用有两种方法,下面是方法代码 ps:因为本人是云桌面开发,所以只作截图,具体代码需要自己 ...

  9. Java word转pdf(替换变量,转图片)

    菜鸟一个,不算原创,学习后的小结.有不足之处,请大家多多指教 Java word转pdf中遇到的问题: 1.在网上找到了一种方法,利用aspose-words,转换效果好但是有两个问题:一.转换时间长 ...

最新文章

  1. PCL:英文参考链接
  2. Python3基础教程:元类详解
  3. PyTorch:MNIST数据集手写数字识别
  4. 把strassen乘法调出来了...
  5. BZOJ4205卡牌配对——最大流+建图优化
  6. java 分页原理_关于javaweb分页原理
  7. Django讲课笔记04:Django项目的调试
  8. 【今日所得】1.29。。。
  9. 当索尼停产单反:好产品是怎么被时代「消融」的?
  10. Linux修改服务器密码
  11. TPP并不可怕,可怕的是我们开始自我封闭
  12. 每周一看:16份文档资料,程序员软硬实力全概览,总有一个适合你
  13. 异常:Mapper method 'com.***.delByNumber' has an unsupported return type: class java.lang.String
  14. ps,ai,cdr平面设计教程,全套!基础到精通,小编亲看教程,推荐!
  15. 蓦然回首,十余年的程序员生涯最后就只剩下了这些!希望我犯过的错误你不要再犯!
  16. 机器学习sklearn之预估器(estimator)使用
  17. Seata 极简入门
  18. potplay播放器录制音频
  19. 【知识点】Python 的np.prod函数详解
  20. IOS编译报错:objc-class-ref........

热门文章

  1. 小手一敲,让JS Map现原形
  2. 利用Python子进程关闭Excel自动化过程出现的弹窗
  3. 为什么用了这么多社交软件,你还是要回家相亲
  4. 互联网快讯:百度发布青春版“Wonder”App,;极米2021双十二圆满收官;华为笔记本新品将发布
  5. heu oj 1011 square
  6. 甘肃省天水市计算机培训班,甘肃天水秦州区文化馆举办首期天水传统菜培训班...
  7. C语言:各种数据类型转换函数
  8. Whole Word Masking (wwm) BERT PaddlePaddle常用预训练模型加载
  9. 中职计算机图形图像课程标准,计算机图形与图形图像处理技术的相互结合
  10. USB 为什么一般选择48MHz