环境准备

1、Office(wps无法转换)
2、window服务
3、pom依赖

        <!-- PDF-jacob --><dependency><groupId>net.sf.jacob-project</groupId><artifactId>jacob</artifactId><version>1.14.3</version></dependency><!-- PDF-ITEXT --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.3.4</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>

4、2个配置文件
jacob-1.14.3-x64.dll(对应jacob依赖版本)
放置于jdk对应bin目录下:

msyh.ttf (写水印的字体)
放置于对应目录下(因为将文件放置于项目中resource下,在打包时会把该文件编 译,会造成文件损坏,所以我这边用的是绝对路径)

配置文件链接: https://pan.baidu.com/s/1MeUHMzexEScDvwSqGQa3pQ 提取码: qwer

具体转换代码

PDFHelper

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.net.URL;
//import com.joinfun.utils.helper.FileHelper;public class PDFHelper {private static Logger logger = LoggerFactory.getLogger(PDFHelper.class);//private static String OWNER_PASS = "HLPass1234";private static String USER_PASS = "HLPass1234";private static final int wordFormatPDF = 17;// WORD转PDF格式private static final int pptSaveAsPDF = 32;// PPT转PDF格式private static final int wdDoNotSaveChanges = 0;// 不保存待定的更改/*** WORD转PDF* * @param source* @param target* @throws Exception*/public static void word2pdf(String source, String target) throws Exception {ComThread.InitSTA();// 初始化com的线程ActiveXComponent app = null;try {logger.info("运行WORD");app = new ActiveXComponent("Word.Application");app.setProperty("Visible", false);Dispatch docs = app.getProperty("Documents").toDispatch();logger.info("打开WORD文件:" + source);Dispatch doc = Dispatch.call(docs, "Open", source, false,// ConfirmConversionstrue // ReadOnly).toDispatch();logger.info("删除旧的目标文件:" + target);deleteOldFile(target);logger.info("SAVE AS方式转换PDF文件:" + target);Dispatch.call(doc, "SaveAs", target, wordFormatPDF);logger.info("CLOSE");Dispatch.call(doc, "Close", false);} catch (Exception e) {logger.error("WORD-PDF转换失败:" + e.getMessage());throw e;} finally {if (app != null) {app.invoke("Quit", wdDoNotSaveChanges);}ComThread.Release();// 释放com的线程}}private static void deleteOldFile(String target) {File tofile = new File(target);if (tofile.exists()) {tofile.delete();}}private static void deleteOldFile(String target , int page) {for(int i = 1 ; i <= page; i++){File tofile = new File(target + i + ".swf");if (tofile.exists()) {tofile.delete();}}      }public static int getPdfPageCount(File file) throws IOException{PdfReader reader = null;FileInputStream fs = null;try{fs = new FileInputStream(file);reader = new PdfReader(fs);int pageCount = reader.getNumberOfPages();return pageCount;} catch(Exception e1){return 0;} finally{if(reader != null){reader.close();}if(fs != null){fs.close();}}}public static void xls2pdf(String source, String target) throws Exception {ComThread.InitSTA();// 初始化com的线程ActiveXComponent app = null;try {logger.info("运行EXCEL");app = new ActiveXComponent("Excel.Application");app.setProperty("Visible", new Variant(false));Dispatch workbooks = app.getProperty("Workbooks").toDispatch();logger.info("打开EXCEL文件:" + source);Dispatch workbook = Dispatch.invoke(workbooks,"Open",Dispatch.Method,new Object[]{source, new Variant(false),new Variant(true)}, new int[1]).toDispatch();logger.info("删除旧的目标文件:" + target);deleteOldFile(target);logger.info("SAVE AS方式转换PDF文件:" + target);Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[]{target, new Variant(57), new Variant(false),new Variant(57), new Variant(57), new Variant(false),new Variant(true), new Variant(57), new Variant(true),new Variant(true), new Variant(true)}, new int[1]);logger.info("CLOSE");Dispatch.call(workbook, "Close", false);} catch (Exception e) {logger.error("EXCEL-PDF转换失败:" + e.getMessage());throw e;} finally {if (app != null) {app.invoke("Quit", new Variant[]{});}ComThread.Release();// 释放com的线程}}public static void ppt2pdf(String source, String target) throws Exception {ComThread.InitSTA();// 初始化com的线程ActiveXComponent app = null;try {app = new ActiveXComponent("Powerpoint.Application");Dispatch presentations = app.getProperty("Presentations").toDispatch();logger.info("打开PPT文件:" + source);Dispatch presentation = Dispatch.call(presentations, "Open",source, true,// ReadOnlytrue,// Untitled 指定文件是否有标题。false // WithWindow 指定文件是否可见。).toDispatch();logger.info("删除旧的目标文件:" + target);deleteOldFile(target);logger.info("SAVE AS方式转换PDF文件:" + target);Dispatch.call(presentation, "SaveAs", target, pptSaveAsPDF);logger.info("CLOSE");Dispatch.call(presentation, "Close");} catch (Exception e) {logger.error("PPT-PDF转换失败:" + e.getMessage());throw e;} finally {if (app != null) {app.invoke("Quit");}ComThread.Release();// 释放com的线程}}public static void pdf2swf(String source, String target, boolean isFocusBitmap) throws Exception {File sourceFile = new File(source);if(!sourceFile.exists()){throw new Exception("源文件不存在:" + source);}deleteOldFile(target); //删除旧的目标文件int pageCount = getPdfPageCount(sourceFile); //PDF 页数
//      long fileSize = FileHelper.getFileSize(sourceFile); //PDF 文件大小long fileSize = FileUtil.size(sourceFile); //PDF 文件大小Process process = null;try{source = "\"" + source + "\"";target = "\"" + target + "\"";if(isFocusBitmap){System.out.println("使用BITMAP方式转化");process = Runtime.getRuntime().exec("C:/SWFTools/pdf2swf.exe " + source + " -o " + target + " -T 9 -s bitmap -s languagedir=C:\\xpdf\\chinese");} else {if(pageCount < 15 && fileSize < 5171018){System.out.println("使用普通方式转化");process = Runtime.getRuntime().exec("C:/SWFTools/pdf2swf.exe " + source + " -o " + target + " -T 9 -s languagedir=C:\\xpdf\\chinese");} else if (pageCount < 1000 && fileSize < 22138904l){System.out.println("使用POLY2BITMAP方式转化");process = Runtime.getRuntime().exec("C:/SWFTools/pdf2swf.exe " + source + " -o " + target + " -T 9 -s poly2bitmap -s languagedir=C:\\xpdf\\chinese");} else {System.out.println("使用BITMAP方式转化");process = Runtime.getRuntime().exec("C:/SWFTools/pdf2swf.exe " + source + " -o " + target + " -T 9 -s bitmap -s languagedir=C:\\xpdf\\chinese");}}StreamGobbler sg1 = new StreamGobbler(process.getInputStream(), "Console");StreamGobbler sg2 = new StreamGobbler(process.getErrorStream(), "Error");sg1.start();sg2.start();int result = process.waitFor();if (result == 0){//                try {//                  process.destroy();//             } catch (Exception e) {//                    e.printStackTrace();//               }}} finally {if(process != null){try {process.destroy();} catch (Exception e) {e.printStackTrace();}}}}public static int pdf2swf(String source, String target) throws Exception {File sourceFile = new File(source);if(!sourceFile.exists()){throw new Exception("源文件不存在:" + source);}int pageCount = getPdfPageCount(sourceFile); //PDF 页数deleteOldFile(target, pageCount); //删除旧的目标文件Process process = null;try{source = "\"" + source + "\"";target = "\"" + target + "%.swf" + "\"";process = Runtime.getRuntime().exec("C:/SWFTools/pdf2swf.exe " + source + " -o " + target + " -T 9 -s languagedir=C:\\xpdf\\chinese");StreamGobbler sg1 = new StreamGobbler(process.getInputStream(), "Console"); StreamGobbler sg2 = new StreamGobbler(process.getErrorStream(), "Error");sg1.start();sg2.start();process.waitFor();  } finally {if(process != null){try {process.destroy();} catch (Exception e) {e.printStackTrace();}}}return pageCount;}@SuppressWarnings("unused")private static String loadStream(InputStream in) throws IOException {int ptr = 0;in = new BufferedInputStream(in);StringBuffer buffer = new StringBuffer();while ((ptr = in.read()) != -1) {buffer.append((char) ptr);}return buffer.toString();}public static void notAllowPrint(String inputFile, String outFile) throws Exception {PdfReader reader = new PdfReader(inputFile);notAllowPrint(reader, outFile);}public static void notAllowPrint(InputStream inputStream, String outFile) throws Exception {PdfReader reader = new PdfReader(inputStream);notAllowPrint(reader, outFile);}public static void notAllowPrint(PdfReader reader, String outFile) throws Exception {PdfEncryptor.encrypt(reader, new FileOutputStream(outFile), null,USER_PASS.getBytes(), PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_FILL_IN | PdfWriter.ALLOW_SCREENREADERS, false);}public static void waterMarkByImg(String inputFile, String outputFile, String confidentialLevelId) throws Exception {PdfReader reader = new PdfReader(inputFile);FileOutputStream outputStream = new FileOutputStream(outputFile);PdfStamper stamper = new PdfStamper(reader, outputStream);URL url = PDFHelper.class.getResource("/dcc-water-mark-img/Confidential_" + confidentialLevelId + ".gif");if (url == null) {url = PDFHelper.class.getClassLoader().getResource("/dcc-water-mark-img/Confidential_" + confidentialLevelId + ".gif");}Image image = Image.getInstance(url.getPath());image.setRotationDegrees(40);image.scalePercent(100);float imgWidth = image.getWidth();float imgHeight = image.getHeight();int total = reader.getNumberOfPages() + 1;float pageWidth = 0;float pageHeight = 0;PdfContentByte under;for (int i = 1; i < total; i++) {pageWidth = reader.getPageSize(i).getWidth();pageHeight = reader.getPageSize(i).getHeight();under = stamper.getOverContent(i);PdfGState gs = new PdfGState();gs.setFillOpacity(0.3f);// 设置透明度为0.2under.setGState(gs);image.setAbsolutePosition(pageWidth/2 - imgWidth/2, pageHeight/2 - imgHeight/2 - 40 * 2);under.addImage(image);}stamper.close();}public static void waterMark(String inputFile, String outputFile, String waterMarkName) throws Exception {PdfReader reader = new PdfReader(inputFile);FileOutputStream outputStream = new FileOutputStream(outputFile);PdfStamper pdfStamper = new PdfStamper(reader, outputStream);PdfContentByte content = null;Rectangle pageRect = null;PdfGState gs = new PdfGState();// 设置字体//BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//      URL url = PDFHelper.class.getResource("/msyh.ttf");
//      URL url = PDFHelper.class.getClassLoader().getResource("msyh.ttf");String ttfPath="D://app/attach/msyh.ttf";BaseFont base = BaseFont.createFont(ttfPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);if (base == null || pdfStamper == null) { return; }// 设置透明度为0.4gs.setFillOpacity(0.2f);gs.setStrokeOpacity(0.2f);int toPage = pdfStamper.getReader().getNumberOfPages();for (int i = 1; i <= toPage; i++) {pageRect = pdfStamper.getReader().getPageSizeWithRotation(i);// 计算水印X,Y坐标float x = pageRect.getWidth() / 2;float y = pageRect.getHeight() / 2;// 获得PDF最顶层content = pdfStamper.getOverContent(i);content.saveState();// set Transparencycontent.setGState(gs);content.beginText();content.setColorFill(BaseColor.GRAY);content.setFontAndSize(base, 60);// 水印文字成45度角倾斜content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, 45);content.endText();}pdfStamper.close();outputStream.close();reader.close();}public static void waterMark4contract(String inputFile, String outputFile, String waterMarkName) throws Exception {PdfReader reader = new PdfReader(inputFile);FileOutputStream outputStream = new FileOutputStream(outputFile);PdfStamper pdfStamper = new PdfStamper(reader, outputStream);PdfContentByte content = null;Rectangle pageRect = null;PdfGState gs = new PdfGState();// 设置字体BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//BaseFont base = BaseFont.createFont("/msyh.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);if (base == null || pdfStamper == null) { return; }// 设置透明度为0.4gs.setFillOpacity(0.3f);gs.setStrokeOpacity(0.3f);int toPage = pdfStamper.getReader().getNumberOfPages();for (int i = 1; i <= toPage; i++) {pageRect = pdfStamper.getReader().getPageSizeWithRotation(i);// 计算水印X,Y坐标float x = pageRect.getWidth() / 2;float y = pageRect.getHeight() / 2;// 获得PDF最顶层content = pdfStamper.getOverContent(i);content.saveState();// set Transparencycontent.setGState(gs);content.beginText();content.setColorFill(BaseColor.GRAY);float fontSize = 60;if(waterMarkName.length() > 10){fontSize = fontSize - (waterMarkName.length() / 5 * 4);}fontSize = fontSize - ((waterMarkName.getBytes("UTF-8").length - waterMarkName.length()) / 7 * 1);content.setFontAndSize(base, fontSize);// 水印文字成45度角倾斜content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, -45);content.endText();}pdfStamper.close();}public static void main(String[] args){//      try {try {
//          PDFHelper.word2pdf("D://root/word.docx", "D://root/word.pdf");
//          PDFHelper.xls2pdf("D://root/test.xlsx", "D://root/excel.pdf");} catch (Exception e) {e.printStackTrace();}//         PDFHelper.ppt2pdf("d:/test/ppt.pptx", "d:/test/ppt.pdf");//          PDFHelper.pdf2swf("d:/test/word.pdf", "d:/test/word.swf");//     } catch (Exception e) {//            e.printStackTrace();//       }try {//waterMarkByImg("d:/1.pdf", "d:/2.pdf", "52");waterMark4contract("c:/1.pdf", "c:/2.pdf", "上海宏利宏利斯蒂芬李经理阿萨德房间里艾丝凡");} catch (Exception e) {e.printStackTrace();}}
}

StreamGobbler

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;public class StreamGobbler extends Thread {InputStream is;String type;private Log log = LogFactory.getLog("[SG]");private static int i = 1;private static int j = 1;StreamGobbler(InputStream is, String type) {this.is = is;this.type = type;}public void run() {try {InputStreamReader isr = new InputStreamReader(is);BufferedReader br = new BufferedReader(isr);i++;j++;String line = null;while ((line = br.readLine()) != null) {if (type.equals("Error")) {log.error(line);}else{log.info(line);}}} catch (IOException ioe) {ioe.printStackTrace();}}}

调用

//sourceFile 可以是xlsx、xls、doc、docx、ppt、pptx
File sourceFile = FileUtil.file("D://root/test.xlsx");
File targetFile = FileUtil.file("D://root/test.pdf");
//根据具体转换调用具体的转换方法,例如:
PDFHelper.xls2pdf(sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());

java 实现office转换pdf相关推荐

  1. Java实现office转PDF文件支持全部转换及Excel转换乱码和格式错乱解决

    本人用的时springboot + LiberOffice ,根据需要进行代码调整 1.所需软件:LiberOffice,可到管网下载,它支持Linux与Owindows系统,挺好用 官网地址:下载 ...

  2. java操作office和pdf文件java读取word,excel和pdf文档内容

    在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...

  3. Java实现图片转换PDF文件

    文章目录 引入依赖 前端页面 控制层接口 PDF工具类 页面效果 最近因为一些事情,需要将一张简单的图片转换为PDF的文件格式,在网上找了一些工具,但是这些工具不是需要注册账号,就是需要下载软件. 而 ...

  4. java jacob pdf_JAVA jacob office转换pdf代码

    private static final int wdFormatPDF = 17; private static final int xlTypePDF = 0; private static fi ...

  5. Java使用SWFTools转换PDF为SWF

    上一篇文章说道,我的一个Android项目里需要查看word和pdf文档,由于在移动终端转换格式比较费劲,所以我选择在服务器端转换.针对word我选择转换为html,在上一篇文章中已经说得很清楚了,那 ...

  6. java对office、pdf文档在线预览解析(融合进项目中)

    最近在项目中要做一个文档的预览,在网上搜了好多demo,都可以实现其功能,但是放在自己的项目中有点复杂. 先说明本人的开发环境(win7+tomcat7+maven+svn+myeclipse),接下 ...

  7. Java程序员从笨鸟到菜鸟之(一百零四)java操作office和pdf文件(二)利用POI实现数据导出excel报表...

    在上一篇博客中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅仅简单的读取office中的数据.尤其是在生 ...

  8. Java程序员从笨鸟到菜鸟之(一百零六)java操作office和pdf文件(四)页面列表导出cvs,excel、pdf报表.

    在平常的开发中我们常常遇到不仅仅只是导出excel报表的情况.有时候也需要导出pdf或者CSV报表.其实原理都差不多.刚开始本来不打算也这篇博客介绍这个的.感觉这篇博客和前面的博客有点雷同.原理基本都 ...

  9. Java抽取Office、PDF的四件兵器

    很多人问到如何抽取word.excel.pdf等文件,在这里我总结一下抽取word.pdf的几种方法. 1.用jacob. 其实jacob是一个bridage,连接java和com或者win32函数的 ...

最新文章

  1. Windows中SQLite的编译及编程
  2. 不起眼的夫妻店,为何会被阿里、京东、苏宁同时盯上?
  3. 查看docker的端口映射情况
  4. sklearn自学指南(part26)--最近邻算法
  5. tablayout支持改变选中文字大小,支持左右滑动,支持viewpager,支持三角可移动指示器...
  6. Html5和Css3扁平化风格网页
  7. 二隐层的神经网络实现MNIST数据集分类
  8. datax参数设置_DataX Web数据增量同步配置说明
  9. Linux下如何编译并运行C程序
  10. 虚拟主机中,不修改IIS设置,在IIS6下运行MVC架构的网站
  11. IntelliJ IDEA设置TortoiseSVN插件(Cannot run program svn)
  12. Jmeter(三十八)while控制器实现ssh三次重连
  13. 计算机系统感染了病毒怎么办,老司机教你电脑感染了病毒怎么解决
  14. 【Vue 基础知识】keep-alive是什么?怎么用?
  15. [植树造林小游戏1.1]
  16. innerHTML,outerHTML innerHTML
  17. virtualBox提高性能方法
  18. 电子计算机工作原理及设计思想为什么理论,动态偏振控制器的工作原理、系统设计及应用...
  19. Linux 块设备 EMMC 驱动介绍
  20. 南京邮电大学电工电子(数电)实验报告——周期信号的频谱分析 连续时间系统模拟

热门文章

  1. 2021年危险化学品经营单位主要负责人考试资料及危险化学品经营单位主要负责人考试技巧
  2. [递推] 51Nod1383 整数分解为2的幂
  3. 计算机软考网络工程师 查询,计算机软考网络工程师考试成绩查询指南
  4. 金融数据智能峰会 | 数据规模爆炸性增长,企业如何进行精准决策?云原生数据仓库数据化运营实战分享
  5. 用C语言中的结构体实现简单的学生成绩管理系统
  6. webgoat全关教程手册
  7. 悲观的人更容易获得好的感觉
  8. CentOS6.5安装部署***服务器
  9. java 校验图片的大小、尺寸、比例
  10. 计算机勾兑双绝是谁发明,勾兑大师范玉平之“舌尖上的五粮液”