最近在电子合同等项目中需要把word或者pdf转换成image,用到了openOffice把word转换pdf,以及把pdf转换成图片
感谢小伙伴张国清花费了三天时间来实现了此功能。下面我将把具体的步骤和注意事项说明。防止重复造*,最后我会把我的demo工程,以及对应的jar等发送到百度云。提供各位下载
传送门:openOffice word转pdf,pdf转图片优化版
优化版代码:https://gitee.com/liran123/transfer_easy_fast
优化版体验地址:http://47.100.196.204:8088
一、首先,列出maven依赖以及jar包
<!--PDF转图片-->
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-core</artifactId>
<version>6.2.2</version>
<exclusions>
<exclusion>
<groupId>javax.media</groupId>
<artifactId>jai_core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-viewer</artifactId>
<version>6.2.2</version>
</dependency>
<!--word转pdf-->
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>3.0.1</version>
</dependency>
<!--需要手动添加到本地仓库 word 转 pdf-->
<dependency>
<groupId>org.artofsolving.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>3.0-beta-4</version>
</dependency>
这里注意:你还一个需要把一个jar的文件夹(文章最下边有相应的百度云下载地址)你找到自己的maven仓库把对应的jar手动放入到 【repository/org/】目录下,在idea右边导入后会有有红色波浪线警告。整个可忽略,不影响使用
下图是对应怎么找到自己的maven repository路径
二、这里贴出详细的代码和配置,注意如果有的地方不正确或者不理解,欢迎评论或者在文章末尾下载我的demo工程来实际运行。以进一步详细熟悉
word转换pdf工具类
import org.apache.commons.lang3.StringUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern; /**
* FileName: OfficeToPdfUtil
* author: zhangguoqing
* Date: 2018/9/19 9:18
* 说明: word文件转换成pdf文件(必须安装Openoffice)
*/
@Component
public class OfficeToPdfUtil { static OfficeManager officeManager; private static ReentrantLock OfficeLock = new ReentrantLock(); @PostConstruct
public void init() {
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
// 设置OpenOffice.org 3的安装目录
config.setOfficeHome(getOfficeHome());
// 启动OpenOffice的服务
OfficeManager getOfficeManager = config.buildOfficeManager();
if (getOfficeManager == null) {
getOfficeManager.start();
}
officeManager = getOfficeManager;
} private static Logger logger = LoggerFactory.getLogger(OfficeToPdfUtil.class); /**
* 锁
*/
private static Lock lock = new ReentrantLock(); /**
* windows下openoffice安装地址
*/
private static String windowsOpenOfficeUrl;
/**
* linux下openoffice安装地址
*/
private static String linuxOpenOfficeUrl;
/**
* mac下opneoffice安装地址
*/
private static String macOpenofficeUrl = "/Applications/OpenOffice.org.app/Contents/"; /**
* 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件<br>
*
* @param inputFilePath 源文件路径,如:"e:/test.docx"
* @return 转换后的图片地址
*/
public static String officeToPdf(String inputFilePath) throws Exception {
try {
if (officeManager == null) {
//如果openOffice中途关闭了 再次启动 防止报错
officeManager = getOfficeManager();
}
if (StringUtils.isEmpty(inputFilePath)) {
logger.info("输入文件地址为空,转换终止!");
return null;
}
File inputFile = new File(inputFilePath);
// 转换后的pdf文件路径
String outputFilePath_end = getOutputFilePath(inputFilePath);
if (!inputFile.exists()) {
logger.info("输入文件不存在,转换终止!");
return null;
}
// 连接OpenOffice
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
return converterFile(inputFile, outputFilePath_end, inputFilePath, converter);
} catch (Exception e) {
logger.error("word转化pdf出错!", e);
throw e;
}
} /**
* @author: zhangguoqing
* @date: 2018/9/19 14:03
* @param: [inputFilePath] word源文件路径 如:"e:/test.docx"
* @return: java.util.List<java.lang.String> 转换后图片地址列表
* @Description: word转成图片
*/
public static List<String> officeToImg(String inputFilePath) {
try {
//word转成pdf
String pdfFilePath = officeToPdf(inputFilePath);
//pdf转图片
List<String> iamgeFilePath = PdfToImageUtil.pdfToIamge(pdfFilePath);
for (String string : iamgeFilePath) {
logger.info("图片地址:" + string);
}
//删除pdf文件
new File(pdfFilePath).delete();
return iamgeFilePath;
} catch (Exception e) {
logger.error("word转化图片出错!", e);
return null;
}
} /**
* 获取输出文件
*
* @param inputFilePath
* @return
*/
public static String getOutputFilePath(String inputFilePath) {
String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
return outputFilePath;
} /**
* 获取inputFilePath的后缀名,如:"e:/test.pptx"的后缀名为:"pptx"<br>
*
* @param inputFilePath
* @return
*/
public static String getPostfix(String inputFilePath) {
return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
} /**
* 连接OpenOffice.org 并且启动OpenOffice.org
*
* @return
*/
public static OfficeManager getOfficeManager() {
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
// 设置OpenOffice.org 3的安装目录
config.setOfficeHome(getOfficeHome());
// 启动OpenOffice的服务
OfficeManager getOfficeManager = config.buildOfficeManager();
getOfficeManager.start();
return getOfficeManager;
} /**
* 根据操作系统的名称,获取OpenOffice.org 3的安装目录<br>
* 如我的OpenOffice.org 3安装在:C:/Program Files (x86)/OpenOffice.org 3<br>
*
* @return OpenOffice.org 3的安装目录
*/
public static String getOfficeHome() {
String osName = System.getProperty("os.name");
logger.info("操作系统名称:" + osName);
if (Pattern.matches("Linux.*", osName)) {
return linuxOpenOfficeUrl;
} else if (Pattern.matches("Windows.*", osName)) {
return windowsOpenOfficeUrl;
} else if (Pattern.matches("Mac.*", osName)) {
return macOpenofficeUrl;
}
return null;
} /**
* @author: zhangguoqing
* @date: 2018/9/19 11:35
* @param: [inputFile, outputFilePath_end, inputFilePath, converter]
* @return: java.util.List<java.lang.String> 转换后的图片地址列表
* @Description: 文件转换
*/
public static String converterFile(File inputFile, String outputFilePath_end, String inputFilePath,
OfficeDocumentConverter converter) throws Exception {
File outputFile = new File(outputFilePath_end);
// 假如目标路径不存在,则新建该路径
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
//判断转换文件的编码方式,如果不是UTF-8,则改为UTF-8编码
converter.convert(inputFile, outputFile);
logger.info("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!");
if (outputFile.isFile() && outputFile.exists()) {
return outputFilePath_end;
} else {
throw new Exception("转换的目标文件不存在 路径" + outputFilePath_end);
}
} @Value("${officeToPdf.linuxOpenOfficeUrl}")
public void setLinuxOpenOfficeUrl(String linuxOpenOfficeUrl) {
OfficeToPdfUtil.linuxOpenOfficeUrl = linuxOpenOfficeUrl;
} @Value("${officeToPdf.windowsOpenOfficeUrl}")
public void setWindowsOpenOfficeUrl(String windowsOpenOfficeUrl) {
OfficeToPdfUtil.windowsOpenOfficeUrl = windowsOpenOfficeUrl;
} }
pdf转换image工具类
import org.apache.commons.lang3.StringUtils;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List; /**
* FileName: PdfToImageUtil
* Author: zhangguoqing
* Date: 2018/9/18 17:53
* 说明: PDF转图片
*/
@Component
public class PdfToImageUtil {
static Logger logger = LoggerFactory.getLogger(PdfToImageUtil.class); // 水印透明度
private static float alpha = 0.2f;
// 水印横向位置
private static int positionWidth = 150;
// 水印纵向位置
private static int positionHeight = 300;
// 水印文字字体
private static Font font = new Font("仿宋", Font.BOLD, 26);
// 水印文字颜色
private static Color color = Color.GRAY;
// 水印文字
private static String watermark; //图片宽度(做成可配置项)
private static Integer width;
//图片高度(做成可配置项)
private static Integer height;
//图片格式(做成可配置项)
private static String imgType; public PdfToImageUtil() {
} /**
* 有参构造,传参水印文字,生成图片时根据是否传参选择是否生成水印
*
* @param watermark 水印内容
*/
public PdfToImageUtil(String watermark) {
this.watermark = watermark;
} //设置水印
public static BufferedImage setGraphics(BufferedImage bfimage) {
Graphics2D g = bfimage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// 5、设置水印文字颜色
g.setColor(color);
// 6、设置水印文字Font
g.setFont(font);
// 7、设置水印文字透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
//设置旋转
g.rotate(-Math.PI / 6);
g.drawString(watermark, 0, (bfimage.getHeight() / 2) * 1);
// 9、释放资源
g.dispose();
return bfimage;
} /**
* @author: zhangguoqing
* @date: 2018/9/18 17:55
* @param: [inputFile] pdf文件路径
* @return: java.util.List<java.lang.String> 图片地址列表
* @Description: pdf文件转图片
*/
public static List<String> pdfToIamge(String inputFile) {
//获取inputFile的后缀名前的内容,如:"e:/test.pptx"的后缀名为:"e:/test"
String imgPath_start = inputFile.substring(0, inputFile.lastIndexOf(".")); List<String> list=null;
Document document = null;
try { document = new Document();
document.setFile(inputFile);
float rotation = 0; //旋转角度
int maxPages = document.getPageTree().getNumberOfPages(); new ArrayList(maxPages);
for (int i = 0; i < maxPages; i++) {
//zoom 缩放比例 ,记住这里调清晰度,我用的是8.5超清晰,9以上就报错了
BufferedImage bfimage = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, 2.1f);
//设置图片的宽和高
Image tempImage = bfimage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage biTemp = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics gTemp = biTemp.getGraphics();
gTemp.drawImage(tempImage, 0, 0, null);
//加水印
if (StringUtils.isNotBlank(watermark)) {
biTemp = setGraphics(biTemp);
}
RenderedImage rendImage = biTemp;
//拼接图片地址
String imgPath = imgPath_start + "_" + i + "." + imgType;
ImageIO.write(rendImage, imgType, new File(imgPath));
bfimage.flush();
list.add(imgPath);
}
} catch (Exception e) {
logger.error("pdf转化图片出错!", e);
} if (document != null) {
document.dispose();
}
return list;
} @Value("${pdfToImg.imgWidth}")
public void setWidth(Integer width) {
PdfToImageUtil.width = width;
} @Value("${pdfToImg.imgHeight}")
public void setHeight(Integer height) {
PdfToImageUtil.height = height;
} @Value("${pdfToImg.imgType}")
public void setImgType(String imgType) {
PdfToImageUtil.imgType = imgType;
}
}
spring boot yml配置文件
#word转pdf
officeToPdf:
#linux下openoffice安装地址
linuxOpenofficeUrl: /opt/openoffice4
#windows下openoffice安装地址 默认 请不要改变 (安装在哪个盘符都是这样)
windowsOpenofficeUrl: C:\Program Files (x86)\OpenOffice 4
#pdf转图片
pdfToImg:
#图片宽度
imgWidth: 1080
#图片高度
imgHeight: 1920
#图片格式
imgType: png
三、最后说明一下oppenOffice安装时候的注意事项
windows下(我的是win10)oppenOffice在安装时候一路确定就可以,
在linux我在自己的阿里云Centos7.4上安装l选择 【download full installation】,具体步骤如下:
1、首先linux上安装需要把下面的安装包下载
2、然后解压 运行命令解压文件:tar -xzvf Apache_OpenOffice_4.1.5_Linux_x86-64_install-rpm_zh-CN.tar.gz
3、然后运行安装命令:cd zh-CN/RPMS/ rpm -ivh *.rpm
四、最后提供大家下载对应的工程demo和对应的jar包,以及oppenoffice下载的安装包
链接:https://pan.baidu.com/s/1RQQgmeSIpEiJVPkKVC2zuw 密码:ttp4
再次注意:maven jar 对应直接解压放入到org目录下,然后刷新maven依赖或者重启ide
最后请大家转文章时不要复制粘贴一部分导致别人看不懂。如果我写的哪里有不懂了直接评论刷一下,看到我会及时回复的。