//代码中都有注释,使用注解的地方大家可以略过

package com.frank.demo.file.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import com.mongodb.gridfs.GridFSDBFile;

@Component
public class FlieToPdfUtil {

@Autowired
private GridFsTemplate fileRepository;

private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;

// 记录日志信息
private static Logger logger = LoggerFactory.getLogger(FlieToPdfUtil.class);

public ByteArrayOutputStream fileToPdf(String fileId) throws Exception {
GridFSDBFile gridFSDBFile = fileRepository.findOne(new Query(Criteria.where("_id").is(fileId)));
if (null != gridFSDBFile) {
String type = this.getFileSufix(gridFSDBFile.getFilename());
String folder = System.getProperty("java.io.tmpdir");
if (type.equalsIgnoreCase("doc") || type.equalsIgnoreCase("docx") || type.equalsIgnoreCase("txt") || type.equalsIgnoreCase("wps")) {
StringBuffer filePath = new StringBuffer();
String name = this.generateToken();
filePath.append(folder);
filePath.append(name);
filePath.append("." + type);
this.readFile(gridFSDBFile, filePath.toString());
StringBuffer pdfPath = new StringBuffer();
pdfPath.append(folder);
pdfPath.append(name);
pdfPath.append(".pdf");
this.wordToPDF(filePath.toString(), pdfPath.toString());
this.deleteFile(filePath.toString());
return this.getBytes(pdfPath.toString());
} else if (type.equalsIgnoreCase("ppt") || type.equalsIgnoreCase("pptx")) {
StringBuffer filePath = new StringBuffer();
String name = this.generateToken();
filePath.append(folder);
filePath.append(name);
filePath.append("." + type);
this.readFile(gridFSDBFile, filePath.toString());
StringBuffer pdfPath = new StringBuffer();
pdfPath.append(folder);
pdfPath.append(name);
pdfPath.append(".pdf");
this.pptToPDF(filePath.toString(), pdfPath.toString());
this.deleteFile(filePath.toString());
return this.getBytes(pdfPath.toString());
} else if (type.equalsIgnoreCase("xls") || type.equalsIgnoreCase("xlsx")) {
StringBuffer filePath = new StringBuffer();
String name = this.generateToken();
filePath.append(folder);
filePath.append(name);
filePath.append("." + type);
this.readFile(gridFSDBFile, filePath.toString());
StringBuffer pdfPath = new StringBuffer();
pdfPath.append(folder);
pdfPath.append(name);
pdfPath.append(".pdf");
this.excelToPDF(filePath.toString(), pdfPath.toString());
this.deleteFile(filePath.toString());
return this.getBytes(pdfPath.toString());
} else if (type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("png") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("gif")) {
StringBuffer filePath = new StringBuffer();
String name = this.generateToken();
filePath.append(folder);
filePath.append(name);
filePath.append("." + type);
this.readFile(gridFSDBFile, filePath.toString());
StringBuffer pdfPath = new StringBuffer();
pdfPath.append(folder);
pdfPath.append(name);
pdfPath.append(".pdf");
this.imgToPDF(filePath.toString(), pdfPath.toString());
this.deleteFile(filePath.toString());
return this.getBytes(pdfPath.toString());
} else {
InputStream is = gridFSDBFile.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
is.close();
baos.flush();
return baos;
}
} else {
throw new Exception("文件不存在!");
}
}

/**
* 删除单个文件

* @param sPath
*            被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}

/**
* 写入当前文件
*/
public void readFile(GridFSDBFile gridFSDBFile, String filePath) throws Exception {
InputStream is = gridFSDBFile.getInputStream();
FileOutputStream os = new FileOutputStream(filePath);
int index = 0;
while ((index = is.read()) != -1) {
os.write(index);
}
is.close();
os.close();
}

/**
* 获取pdf文件输出流
*/
public ByteArrayOutputStream getBytes(String filePath) {
File file = new File(filePath);
ByteArrayOutputStream out = null;
try {
FileInputStream in = new FileInputStream(file);
out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((in.read(b)) != -1) {
out.write(b, 0, b.length);
}
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this.deleteFile(filePath.toString());
return out;
}

/**
* 获取随机名称
*/
public String generateToken() throws Exception {
return UUID.randomUUID().toString().replace("-", "");
}

/***
* 判断文件类型

* @param fileName
* @return
*/
public String getFileSufix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
}

/**
* Word转PDF
*/
private void wordToPDF(String inputFile, String pdfFile) {
logger.info("启动 Word...");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = new Dispatch();
try {
logger.info("进入转换PDF程序");
app = new ActiveXComponent("Word.Application");
Dispatch xlo = (Dispatch) (app.getObject());
try {
logger.info("version=" + app.getProperty("Version"));
logger.info("version=" + Dispatch.get(xlo, "Version"));
} catch (Exception e) {
e.printStackTrace();
}
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.call(docs, "Open", inputFile).toDispatch();
logger.info("打开文档..." + inputFile);
logger.info("转换文档到 PDF..." + pdfFile);
File tofile = new File(pdfFile);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc, "SaveAs", pdfFile, // FileName
wdFormatPDF);
long end = System.currentTimeMillis();
logger.info("转换完成..用时:" + (end - start) + "ms.");

} catch (Exception e) {
logger.info("========Error:文档转换失败:" + e.getMessage());
} finally {
Dispatch.call(doc, "Close", false);
System.out.println("关闭文档");
if (app != null)
app.invoke("Quit", new Variant[] {});
// 如果没有这句话,winword.exe进程将不会关闭
ComThread.Release();
}

}

/**
* Excel转化成PDF
*/
private void excelToPDF(String inputFile, String pdfFile) {
ActiveXComponent ax = null;
Dispatch excel = null;
try {
ComThread.InitSTA(true);
logger.info("进入转换PDF程序");
ax = new ActiveXComponent("KET.Application");
logger.info("开始转换Excel为PDF...");
long start = System.currentTimeMillis();
ax.setProperty("Visible", false);
ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch excels = ax.getProperty("Workbooks").toDispatch();
excel = Dispatch.invoke(excels, "Open", Dispatch.Method, new Object[] { inputFile, new Variant(false), new Variant(false) }, new int[9]).toDispatch();
Dispatch sheet;
// 横向打印设置 多个Sheet
Dispatch sheets = Dispatch.get(excel, "Sheets").toDispatch();
// 获得几个sheet
int count = Dispatch.get(sheets, "Count").getInt();
System.out.println(count);
if (1 < count) {
sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get, new Object[] { new Integer(2) }, new int[1]).toDispatch();
} else {
sheet = Dispatch.get(excel, "ActiveSheet").toDispatch();
}
Dispatch pageSetup = Dispatch.get(sheet, "PageSetup").toDispatch();
Dispatch.put(pageSetup, "Orientation", new Variant(2)); // Variant(2)横向打印
// 设置边距
Dispatch.put(pageSetup, "CenterVertically", true);
// Dispatch.put(pageSetup, "LeftMargin", 0);
// Dispatch.put(pageSetup, "RightMargin", 0);
Dispatch.put(pageSetup, "TopMargin", 10);
Dispatch.put(pageSetup, "BottomMargin", 10);
Dispatch.put(pageSetup, "PrintGridlines", true);
// 设置打印纸张
// Dispatch.put(pageSetup, "PaperSize", 8);
// 设置缩放
// Dispatch.put(pageSetup, "Zoom", 49);
// 转换格式
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF格式=0
pdfFile, new Variant(xlTypePDF) // 0=标准 (生成的PDF图片不会变模糊)
// 1=最小文件
// (生成的PDF图片糊的一塌糊涂)
}, new int[1]);
long end = System.currentTimeMillis();
logger.info("转换完成..用时:" + (end - start) + "ms.");
} catch (Exception e) {
// TODO: handle exception
logger.info("========Error:文档转换失败:" + e.getMessage());
} finally {
Dispatch.call(excel, "Close", new Variant(false));
if (ax != null) {
ax.invoke("Quit", new Variant[] {});
ax = null;
}
ComThread.Release();
}
}

/**
* ppt转化成PDF
*/
private void pptToPDF(String inputFile, String pdfFile) {
ActiveXComponent app = null;
Dispatch ppt = new Dispatch();
try {
logger.info("进入转换PDF程序");
ComThread.InitSTA(true);
app = new ActiveXComponent("KWPP.Application");
// app.setProperty("Visible", false);
logger.info("开始转化PPT为PDF...");
long start = System.currentTimeMillis();
Dispatch ppts = app.getProperty("Presentations").toDispatch();
ppt = Dispatch.call(ppts, "Open", inputFile, true, // ReadOnly
// false, // Untitled指定文件是否有标题
false// WithWindow指定文件是否可见
).toDispatch();
Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, new Object[] { pdfFile, new Variant(ppSaveAsPDF) }, new int[1]);
long end = System.currentTimeMillis();
logger.info("转换完成..用时:" + (end - start) + "ms.");
} catch (Exception e) {
// TODO: handle exception
logger.info("========Error:文档转换失败:" + e.getMessage());
} finally {
Dispatch.call(ppt, "Close");
if (app != null)
app.invoke("Quit", new Variant[] {});
// 如果没有这句话,winword.exe进程将不会关闭
ComThread.Release();
}
}

private void imgToPDF(String imgFilePath, String pdfFilePath) {
File file = new File(imgFilePath);
if (file.exists()) {
Document document = null;
FileOutputStream fos = null;
try {
// 读取一个图片
Image image = Image.getInstance(imgFilePath);
float imageHeight = image.getScaledHeight();
float imageWidth = image.getScaledWidth();
int i = 0;
while (imageHeight > 500 || imageWidth > 500) {
image.scalePercent(100 - i);
i++;
imageHeight = image.getScaledHeight();
imageWidth = image.getScaledWidth();
}
image.setAlignment(Image.ALIGN_CENTER);
// 文档页面宽高为图片宽高
Rectangle rect = new Rectangle(imageWidth, imageHeight);
document = new Document(rect);
// 读取文件流,创建可读写的文件
fos = new FileOutputStream(pdfFilePath);
PdfWriter.getInstance(document, fos);
// 设置文档边距
document.setMargins(0, 0, 0, 0);
// 打开文档
document.open();
// 插入一个图片
document.add(image);
} catch (DocumentException de) {
System.out.println(de.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
document.close();
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Java 使用jacob实现各类办公文档(ppt,Excel,word,text,imge)转换成PDF相关推荐

  1. word文档通配符换行_Word中有哪些实用技巧?Word文件怎么转换成PDF文件?

    Word是我们大家日常办公和学习中使用最为频繁的一种工具.那么对于Word,很多人会觉得它很简单,打开就可以进行操作了.但事实是,很多人并没有掌握它真正的用法,尤其是Word使用过程中的一些技巧.Wo ...

  2. java 使用 freemarker模板 生成 word 并用 aspose 转换成PDF

    添加依赖: <!-- freemarker生成word文件--><dependency><groupId>org.springframework.boot</ ...

  3. office文档(ppt,excel,word,pdf等)在线预览

    使用第三方URL方式 html <iframe id="pactFrame" src="" width="100%" height=& ...

  4. Java 将HTML文件转换成PDF(Windows和linux)

    核心代码 package lijiong.pdf.htmltopdfv2;import java.io.IOException;public class PDFTool { //wkhtmltopdf ...

  5. jpg怎么转换成pdf文档

    JPG转换成PDF?JPG怎么转换成PDF文档?我们知道大部分的PDF格式的文档都不具有编辑功能,用户只能通过手写将PDF内容录入到Word文档中,但是遇到需要将JPG图片转换成PDF,该怎么办呢?下 ...

  6. 扫描件怎么转换成pdf文档?快来了解下手机扫描的方法

    在现代社会中,电子文档已经成为了我们日常生活中不可或缺的一部分.扫描件转换成PDF文档是其中一个非常重要的方面.那么,如何将扫描件转换成PDF文档,以及在手机上有哪些扫描的方法呢? 将扫描件转换为PD ...

  7. Java实现office办公文档在线预览(word、excel、ppt、txt等)

    文章目录 一.官网下载openOffice 安装包,运行安装(不同系统的安装请自行百度,这里不做过多描述) 二.pom中引入依赖 三.office文件转为pdf流的工具类 四.service层代码 五 ...

  8. 【愚公系列】2023年02月 .NET CORE工具案例-办公文档神器Toxy的使用

    文章目录 前言 一.办公文档神器Toxy的使用 1.安装对应的包 2.Word文档操作 2.1 普通文档解析 2.2 表格文档解析 3.Excel文件操作 4.PDF文档操作 5.图片文件操作 总结 ...

  9. 办公文档加密,企业文档加密,强制性透明加密技术,fasoft

    随着企事业单位的快速发展,文档以电子文档方式为企事业单位承载着越来越多重要的信息.而由于电子文档的容易散播性,导致企事业单位在外发给客户或合作伙伴的重要资料,都可能会在这交互的过程中被篡改.无序传播等 ...

最新文章

  1. Anaconda3+python3.7.10+TensorFlow2.3.0+PyQt5环境搭建
  2. jqgrid 让隐藏的列在编辑状态时出现且可编辑
  3. 第二章 数组名是一个指针常量吗?
  4. wp cron.php,wordpress定时任务(wp-cron.php)造成主机CPU比较高的解决办法
  5. C++:拷贝构造函数与深/浅拷贝
  6. 【今日CS 视觉论文速览】1 Jan 2019
  7. 非职业程序员的工具箱
  8. MySQL→数据库、启动连接数据库、SQL→DDL数据定义语言及数据类型、DML数据操作语言、DQL数据查询语言、数据库约束→主键、唯一、非空、默认、外键、SQL、三大范式及一多关系、视图、内外连接
  9. CSUOJ 1170 A sample problem
  10. ios整理(五)小应用-重力感应
  11. [译] 用行为经济学来传达付费应用订阅的价值
  12. 程序员眼中的中国传统文化-王阳明《传习录》3
  13. web - 常见浏览器及内核
  14. 蓝牙防丢器原理和作用
  15. mysql 实现api接口_一套免费MySQL数据库数据接口API,让项目开发更简单
  16. 这 5 本数据分析书籍,都是经典中的经典
  17. 电子计算机行业爆品打造,二类电商|爆品打造,不是你想造就能造
  18. 【杂乱的生活】如果IT界拉高了房价 该怨谁?
  19. c语言课程设计--图书/音乐管理系统
  20. Vue选项式 API 的生命周期选项和组合式 API

热门文章

  1. 我的一些美食相关照片
  2. 常见外贸英文缩写(上)
  3. 【Unity从零开始制作空洞骑士】①制作人物的移动跳跃转向以及初始的动画制作
  4. 关于在CSDN Blog公告栏加入Google搜索功能的问题
  5. pytorch 搭建 VGG 网络
  6. y70.第四章 Prometheus大厂监控体系及实战 -- Prometheus监控介绍(一)
  7. 在农村,读书是唯一的出路!
  8. java mysql主从复制_MySQL主从复制的实现过程
  9. html语义化有利于seo,HTML5语义化标签对SEO的影响
  10. 基于R语言的主成分分析理论与实例详解