最近因为公司业务需求需要实现线上预览,查找了很多资料.现在为了方便大家所以做个汇总
方便大家以免大家走弯路
开发工具是idea 框架是SSM第三方工具openOffice
注意事项:
1.openOffice和jodconverter版本问题,openOffice版本低可能不支持07版office也就是(.docx.xlsx.pptx)所以直接下载最先版本,jodconverter如果低于2.2.2一定不支持07版office所以一定要是2.2.2以及以上而且2.2.2开始不支持pom.xml直接下载所以需要直接将包导入到程序里,因为我自己用的是idea所以只介绍idea,如果是eclipse需要自己摸索,但是不难.
2.openOffice可以将文档转换为pdf文件和html文件,但是xlsx和xls转成pdf文件后表格会存在很大的问题,
3.如果表格的一个框内的字数过多会被下一行遮盖,当转成pdf以后不会自动换行所以还是会被遮盖.
4.当被转换为html时doc 和docx中的样式的地址不对所以不能定位到图片地址所以样式不对
5.PPT和PPTX不能转换.所以为了兼容所以折中处理了一下:如果是.pdf.txt..jpg.png.gif文件不做处理直接获取文件流吐给前端,如果是ppt或者PPTX通过openOffice转换为pdf文件然后将文件流给前端,如果是其他文件转换为html文件,但是前面提到如果doc或者docx转换为html后其中的样式的图片地址会定位不到地址所以需要对其特殊处理方法是将doc转换为html文件后将其文件读取成文件流再将其转换为字符串.替换其中的样式图片地址,再将其转换为流给前端.是不是很复杂,如果你有更方便的方法可以贴出来一起探讨,方便其他人再走弯路.
6.还有一点doc转换成html文件在转成字符串,再转成流时会采用"gb2312"的编码格式需要你在转换的过程中定义一下否则出来时乱码
具体流程
1.下载安装openoffice,安装后启动服务,网上有很多介绍所以我就不详细写了.
2.导入jodconverter包(2.2.2以上)这个也是自己下载
3
/**
* 文件预览
*/
@RequestMapping(method = RequestMethod.GET, value = "filePreview")
public void filePreview(HttpServletRequest request, HttpServletResponse response, Map model, String filePath) throws UnsupportedEncodingException {
String fileAstrictType = ".pdf,.txt,.jpg,.png,.gif";
String Ext = filePath.substring(filePath.lastIndexOf("."), filePath.length());
File file = new File(filePath.trim());
String outFileExt =null;
try {
InputStream is=null;
if (!Arrays.
asList(fileAstrictType.split(",")).contains(Ext)) {
if(Ext.equals(".ppt")||Ext.equals(".pptx")){
outFileExt=".pdf";
DocConverter d = new DocConverter(filePath,outFileExt);
d.conver();
filePath = d.getpdfPath();
file = new File(filePath);
is = new FileInputStream(file);
}else {
String outPath = filePath.substring(0, filePath.lastIndexOf("."));
String htmlStr = Doc2Html.toHtmlString(file, outPath);
HttpResponse ret = new HttpResponse();
ret.setData(htmlStr);
is = new ByteArrayInputStream(htmlStr.getBytes("gb2312"));
}
}else {
is=new FileInputStream(file);
}
byte[] fileData = IOUtils.toByteArray(is);
OutputStream out = response.getOutputStream();
IOUtils.write(fileData, out);
is.close();
out.close();
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
com.artofsolving
jodconverter
2.2.2
system
${project.basedir}/src/main/webapp/WEB-INF/lib/jodconverter-2.2.2.jar
package com.huaxin.udisk.utils;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.*;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import java.io.*;
/**
* Created by udisk.
* User: ${tanhao}
* Date: 2017/2/6 14:17
*/
public class DocConverter {
/*
* doc docx格式转换
* @author Administrator
*/
private static final int environment=1;//环境1:windows 2:linux(涉及pdf2swf路径问题)
private String fileString;
private String outputPath="";//输出路径,如果不设置就输出在默认位置
private String fileName;
private File pdfFile;
// private File swfFile;
private File docFile;
public DocConverter(String fileString ,String outFileExt)
{
ini(fileString,outFileExt );
}
/*
* 重新设置 file
* @param fileString
*/
public void setFile(String fileString ,String outFileExt)
{
ini(fileString , outFileExt);
}
/*
* 初始化
* @param fileString
*/
private void ini(String fileString ,String outFileExt)
{
this.fileString=fileString;
fileName=fileString.substring(0,fileString.lastIndexOf("."));
docFile=new File(fileString);
pdfFile=new File(fileName+outFileExt);
}
/*
* 转为PDF
* @param file
*/
private void doc2pdf() throws Exception
{
if(docFile.exists())
{
if(!pdfFile.exists())
{
OpenOfficeConnection connection=new SocketOpenOfficeConnection(8100);
try
{
connection.connect();
DocumentConverter converter=new OpenOfficeDocumentConverter(connection);
converter.convert(docFile,pdfFile);
//close the connection
connection.disconnect();
System.out.println("****pdf转换成功,PDF输出:"+pdfFile.getPath()+"****");
}
catch(java.net.ConnectException e)
{
//ToDo Auto-generated catch block
e.printStackTrace();
System.out.println("****swf转换异常,openoffice服务未启动!****");
throw e;
}
catch(com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e)
{
e.printStackTrace();
System.out.println("****swf转换器异常,读取转换文件失败****");
throw e;
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
}
else
{
System.out.println("****已经转换为pdf,不需要再进行转化****");
}
}
else
{
System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");
}
}
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 boolean conver()
{
if(pdfFile.exists())
{
System.out.println("****swf转换器开始工作,该文件已经转换为pdf****");
return true;
}
if(environment==1)
{
System.out.println("****swf转换器开始工作,当前设置运行环境windows****");
}
else {
System.out.println("****swf转换器开始工作,当前设置运行环境linux****");
}
try {
doc2pdf();
/*pdf2swf();*/
} catch (Exception e) {
// TODO: Auto-generated catch block
e.printStackTrace();
return false;
}
if(pdfFile.exists())
{
return true;
}
else {
return false;
}
}
/*
* 返回文件路径
* @param s
*/
public String getpdfPath()
{
if(pdfFile.exists())
{
String tempString =pdfFile.getPath();
tempString=tempString.replaceAll("\\\\", "/");
return tempString;
}
else{
return "";
}
}
/*
* 设置输出路径
*/
// public void setOutputPath(String outputPath)
// {
// this.outputPath=outputPath;
// if(!outputPath.equals(""))
// {
// String realName=fileName.substring(fileName.lastIndexOf("/"),fileName.lastIndexOf("."));
// if(outputPath.charAt(outputPath.length())=='/')
// {
// swfFile=new File(outputPath+realName+".swf");
// }
// else
// {
// swfFile=new File(outputPath+realName+".swf");
// }
// }
// }
// public static void main(String s[])
// {
// DocConverter d=new DocConverter("c:/temp/111.ppt");
// d.conver();
// }
}
package com.huaxin.udisk.utils;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.*;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import java.io.*;
import java.net.ConnectException;
/**
* Created by udisk.
* User: ${tanhao}
* Date: 2017/2/21 18:49
*/
public class Doc2Html {
/**
* 将word文档转换成html文档
*
* @param docFile
* 需要转换的word文档
* @param filepath
* 转换之后html的存放路径
* @return 转换之后的html文件
*/
public static File convert(File docFile, String filepath) {
// 创建保存html的文件
File htmlFile = new File(filepath + ".html");
// 创建Openoffice连接
OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
try {
// 连接
con.connect();
} catch (ConnectException e) {
System.out.println("获取OpenOffice连接失败...");
e.printStackTrace();
}
// 创建转换器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
// 转换文档问html
converter.convert(docFile, htmlFile);
// 关闭openoffice连接
con.disconnect();
return htmlFile;
}
/**
* 将word转换成html文件,并且获取html文件代码。
*
* @param docFile
* 需要转换的文档
* @param filepath
* 文档中图片的保存位置
* @return 转换成功的html代码
*/
public static String toHtmlString(File docFile, String filepath) {
// 转换word文档
File htmlFile = convert(docFile, filepath);
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(htmlFile),"gb2312"));
while (br.ready()) {
htmlSb.append(br.readLine());
}
br.close();
// 删除临时文件
htmlFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// HTML文件字符串
String htmlStr = htmlSb.toString();
// 返回经过清洁的html文本
return clearFormat(htmlStr, filepath);
}
/**
* 清除一些不需要的html标记
*
* @param htmlStr
* 带有复杂html标记的html语句
* @return 去除了不需要html标记的语句
*/
protected static String clearFormat(String htmlStr, String docImgPath) {
String imgPath = docImgPath.substring(0,docImgPath.lastIndexOf("/")+1);
/*// 获取body内容的正则
String bodyReg = "";
Pattern bodyPattern = Pattern.compile(bodyReg);
Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
if (bodyMatcher.find()) {
// 获取BODY内容,并转化BODY标签为DIV
htmlStr = bodyMatcher.group().replaceFirst("
", "
"); }*/ // 调整图片地址 htmlStr = htmlStr.replaceAll("转换成
保留样式 // content = content.replaceAll("(
]*>.*?)(<\\/P>)", // "
"); // 把转换成并删除样式 // htmlStr = htmlStr.replaceAll("(
]*)(>.*?)(<\\/P>)", "
"); // 删除不需要的标签 // htmlStr = htmlStr // .replaceAll( // "<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*?>", // ""); // // 删除不需要的属性 // htmlStr = htmlStr // .replaceAll( // "<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>", // "<$1$2>"); return htmlStr; } }