做过几个word转pdf的项目,首先需要在本地下载openOffice,这个是我们转换的工具,调用openOffice的命令使文件完成转换.
需要用到的jar包jodconverter-2.2.2.jar,jodconverter-cli-2.2.2.jar,juh-3.0.1.jar,jurt-3.0.1.jar,ridl-3.0.1.jar,unoil-3.0.1.jar。
下面是代码
package com.mq.zhph.preview;
import java.io.File;
import java.net.ConnectException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
/**
* 将txt、java、odt、doc、docx、ppt、pptx或pdf格式的文件转换swf文件工具类。
*
* @author HH
*/
public class ConverterTool {
private static Log log = LogFactory.getLog(ConverterTool.class);
//判断系统
public static String getCommond(){
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){
return "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe -headless - accept=\"socket,host=127.0.0.1,port=8100;urp;\";
}
return "/opt/openoffice4/program/soffice -headless - accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard &";
}
/**
* 转换主方法
*/
public static String conver2Pdf(String filePath) {
log.info("转换前 filePath = "+filePath);
String fileSuffix = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();//获取文件的后缀。
String fileName = filePath.substring(0, filePath.lastIndexOf("."));//包含了存储路径的文件名(不包括文件的扩展名)。
// 用于处理TXT文档转化为PDF格式乱码,获取上传文件的名称(不需要后面的格式)
if(fileSuffix.equals(".pdf")){//如果上传的文件是pdf文档
return filePath;
}else if(fileSuffix.matches(".odt|.doc|.docx|.ppt|.pptx|.xls|.xlsx")){
if(new File(fileName + ".pdf").exists()){
return fileName + ".pdf";
}else if (conver2Pdf(filePath,fileName + ".pdf")){//将odt、doc、docx、ppt或pptx格式的文件转换为pdf文件。
//new File(filePath).delete();//删除odt、doc、docx、ppt或pptx源文件。
return fileName + ".pdf";
}else{
log.info("转换失败....");
}
}
return "faild";
}
/**
* 将odt、doc、docx、ppt或pptx格式的文件转换为pdf文件,如果文件后缀是pdf,则直接返回true。
*
* fileSuffix 文件的后缀。
*/
private static boolean conver2Pdf(String sourceFilePath, String pdfFileSavePath){
File sourceFile = new File(sourceFilePath);
if (sourceFile.exists()) {
String command = getCommond();
log.info("command===>>>"+command);
try {
Process process = Runtime.getRuntime().exec(command);//启动OpenOffice的服务
OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
connection.connect();
if(connection.isConnected()){//如果连接成功
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(sourceFile, new File(pdfFileSavePath));
connection.disconnect();// close the connection
process.destroy();// 封闭OpenOffice服务的进程
log.info("****pdf转换成功,PDF输出:" + pdfFileSavePath+ "****");
return true;
}else{
return false;//swf转换器异常,openoffice连接失败!
}
} catch (ConnectException e) {
e.printStackTrace();
log.info("****pdf转换器异常,openoffice服务未启动!****");
return false;
} catch (OpenOfficeException e) {
e.printStackTrace();
log.info("****pdf转换器异常,读取转换文件失败****");
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else {
log.info("****pdf转换器异常,需要转换的文档不存在,无法转换****");
return false;
}
}
public static void main(String[] args) {
System.out.println(getCommond());
}
}
----------------------输出到浏览器---------------------
<%@page import="java.net.URLEncoder"%>
<%@page import="com.mq.zhph.preview.ConverterTool"%>
<%@page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
String title = "在线预览";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><%=title %></title>
<base href="<%=basePath%>">
<script type="text/javascript">document.write("<title>标题1</title>");</script>
<%
out.clear();
out = pageContext.pushBody();
response.setContentType("application/pdf");
try {
String strPdfPath = ConverterTool.conver2Pdf("需要被转换的文件路径");
System.out.println("strPdfPath = " + strPdfPath);
if (strPdfPath != null && strPdfPath.equals("faild")) {
out.print(strPdfPath + " file not exites!");
return;
}
//file is extis
File file = new File(strPdfPath);
if (file.exists()) {
DataOutputStream temps = new DataOutputStream(response.getOutputStream());
DataInputStream in = new DataInputStream(new FileInputStream(strPdfPath));
byte[] b = new byte[2048];
while ((in.read(b)) != -1) {
temps.write(b);
temps.flush();
}
in.close();
temps.close();
} else {
out.print(strPdfPath + " file not exites!");
}
} catch (Exception e) {
out.println(e.getMessage());
}
%>
</head>
<body>
</body>
</html>