说明:需要在服务器安装一个openoffice 软件,通过端口访问该软件。在这个软件中将office文档转换成pdf格式。
1.到https://www.openoffice.org/download/下载openoffice安装 建议使用中文版
2.在工程文件中添加maven依赖
<!--2.2.2以上才能转换docx,或xlsx-->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.icepdf/icepdf-core -->
<dependency>
<groupId>org.icepdf</groupId>
<artifactId>icepdf-core</artifactId>
<version>4.1.1</version>
</dependency>
(如果需要jar包建议新建一个maven工程配置依赖,自己获取jodconverter-2.2.2.jar )
(手工下载jodconverter-2.2.2.jar完整包,lib下有其依赖包)
3.代码
package com.mypackage;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import java.util.Properties;
import javax.imageio.ImageIO;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
public class OfficeToImage {
public static Logger logger = LoggerFactory.getLogger(new OfficeToImage().getClass());
public final static String pdfPath = "d://pdf//"; //pdf存放路径
public final static String picturePath = "d://picture//"; //图片存放路径
public static void main(String[] args){
// //运行之前需要在F:\office下新建MVC.docx,当然也可以换成是其他的路径
String sourceFile = "C:\\Users\\Administrator\\Desktop";
// String sourceFile = "D:\\你好.xlsx";
String commonPath = "C:\\Users\\Administrator\\Desktop"; //图片存放路径
// OfficeToImage wti = new OfficeToImage();
// System.out.println(wti.office2PDF(sourceFile,commonPath));
String RUL_PATH = Thread.currentThread()
.getContextClassLoader().getResource("").getPath()
.replace("%20", " ")
+ "openoffice.properties";
System.out.println("RUL_PATHRUL_PATH==========================="+RUL_PATH);
}
public static Integer office2PDF(String sourceFile,String commonPath) {
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return 0;// 找不到源文件, 则返回-1
}
File file = new File(sourceFile);
String filename = file.getName(); //获取文件名带后缀
String name = filename.substring(0,filename.indexOf("."));
String outFile = commonPath+name+"//";
System.out.println("outFile==========="+outFile);
// // 如果目标路径不存在, 则新建该路径
// File outputFile = new File(outFile);
// if (!outputFile.getParentFile().exists()) {
// outputFile.getParentFile().mkdirs();
// }
if(!new File(outFile).isDirectory()){
new File(outFile).mkdir();
System.out.println("新建上传文件夹");
}
String outFile1 = commonPath + name+"//" + name + ".pdf";
File outputFile = new File(outFile1);
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){ //如果windows环境 存在openoffice地址
Properties prop = new Properties();
FileInputStream fis = null;
String RUL_PATH = Thread.currentThread()
.getContextClassLoader().getResource("").getPath()
.replace("%20", " ")
+ "openoffice.properties";
fis = new FileInputStream(RUL_PATH);// 属性文件输入流
prop.load(fis);// 将属性文件流装载到Properties对象中
fis.close();// 关闭流
String OpenOffice_HOME = prop.getProperty("OpenOffice_HOME");
if (OpenOffice_HOME == null)
return -1;
// 如果从文件中读取的URL地址最后一个字符不是 '\',则添加'\'
if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {
OpenOffice_HOME += "\\";
}
// 启动OpenOffice的服务
String command = OpenOffice_HOME
+ "program\\soffice.exe"+" "+"-headless"+" "+"-accept=\"socket,host=127.0.0.1,port=8100;urp;\""+" "+"-nofirststartwizard";
Process pro = Runtime.getRuntime().exec(command);
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
try {
converter.convert(inputFile, outputFile);
} catch (Exception e) {
logger.error("文件转换错误"+e.getMessage());
System.out.println("文件转换错误");
return -1;
}
// close the connection
connection.disconnect();
// 关闭OpenOffice服务的进程
pro.destroy();
}else{ //linux环境 不存在openoffice地址
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
try {
converter.convert(inputFile, outputFile);
} catch (Exception e) {
logger.error("文件转换错误"+e.getMessage());
System.out.println("文件转换错误");
return -1;
}
// close the connection
connection.disconnect();
}
Integer imageCount = 0;
try {
imageCount = toImage(outFile1,commonPath, 2.5f);
deleteFile(outputFile);
} catch (PDFException e) {
logger.error("文件转换错误"+e.getMessage());
e.printStackTrace();
} catch (PDFSecurityException e) {
logger.error("文件转换错误"+e.getMessage());
e.printStackTrace();
}
return imageCount;
} catch (FileNotFoundException e) {
logger.error("文件转换错误"+e.getMessage());
e.printStackTrace();
return 0;
} catch (ConnectException e) {
logger.error("文件转换错误"+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
logger.error("文件转换错误"+e.getMessage());
e.printStackTrace();
}
return 0;
}
public static Integer toImage(String filePath, String imagePath, float zoom)
throws PDFException, PDFSecurityException, IOException {
Integer imageCount = 0;
Document document = new Document();
document.setFile(filePath);
float rotation = 0f;// 旋转角度
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, zoom);
RenderedImage rendImage = image;
try {
File file = new File(imagePath + i + ".jpg");
if (!file.exists()) {
file.mkdirs();
}
ImageIO.write(rendImage, "png", file);
imageCount++;
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
}
document.dispose();
return imageCount;
}
public static void deleteFile(File oldPath) {
if (oldPath.isDirectory()) {
System.out.println(oldPath + "是文件夹--");
File[] files = oldPath.listFiles();
for (File file : files) {
deleteFile(file);
}
}else{
oldPath.delete();
}
}
}