jacob+itext实现Word、Excel、Ppt在线预览
本⼈技术⼩⽩⼀枚,前些天Boss让我写⼀个office在线预览的⼀个功能,各种资料,总结⼀下我觉得⽐较好⽤的⽅法
⽹上⼤概有这⼏种office在线预览的⽅法
第⼀种
利⽤office online实现在线预览
Office平台提供了通过url的指向达到预览效果
后⾯的src填写⽂档上传到服务器的地址,地址需要通过⽤URLEncode进⾏编译
例:
参照链接:
优点:这个功能由Office提供所以只需要拼接地址
缺点:⽂档的访问地址不能直接使⽤ ip,需要通过域名访问,并且端⼝必须是 80 端⼝,
Word、ppt⽂档的⼤⼩不能超过10M,Excel不能超过5M
第⼆种
1.通过第三⽅⼯具openoffice,将word、excel、ppt、txt等⽂件转换为pdf⽂件,
2.通过swfTools将pdf⽂件转换成swf格式的⽂件;
3.通过FlexPaper⽂档组件在页⾯上进⾏展⽰。
参照链接:
总结⼀下这种⽅法的利弊,
优点:openoffice有各种版本,⽀持跨平台,转换速度快;
缺点:转换的样式会有缺损,Excel和openoffice完美不兼容 =  . = ,转换的时候会出现折⾏,切分等情况,效果很不理想;FlexPaper这个是⽤Flash插件显⽰的,展⽰的效果优点low。
第三种
利⽤poi实现office在线预览
public static void PoiWord07ToHtml (HttpServletRequest request) throws IOException{
String path= "C:\\Users\\Administrator\\Desktop\\";
String file = "C:\\Users\\Administrator\\Desktop\\word07.docx";
String file2 = "C:\\Users\\Administrator\\Desktop\\word07.html";
File f = new File(file);
if (!f.exists()) {
System.out.println( "Sorry File does not Exists!");
} else {
if (f.getName().endsWith( ".docx") || f.getName().endsWith( ".DOCX")) {
//读取⽂档内容
InputStream in = new FileInputStream(f);
XWPFDocument document = new XWPFDocument(in);
File imageFolderFile = new File(path);
//加载html页⾯时图⽚路径
XHTMLOptions options = ate().URIResolver( new BasicURIResolver( "./"));
//图⽚保存⽂件夹路径
options.setExtractor( new FileImageExtractor(imageFolderFile));
OutputStream out = new FileOutputStream( new File(file2));
out.close();
} else {
System.out.println( "Enter only MS Office 2007+ files");
}
}
}
总结⼀下这种⽅法的利弊
优点:纯java代码不需要第三⽅软件,poi对于Excel的解析⽐较好,可以完美转换
缺点:jar包真的好难啊,各种版本不兼容问题,⽐如word03和word07⽣成的分别是.doc和docx,poi对于.doc不识别,然后各种报错,由于⽣成的是Html所以它会把Word中的图⽚单独存放在⼀个⽂件下很占空间。
第四种
使⽤jacob实现office转换pdf达到预览功能
pom⽂件中引⽤
<dependency>
<groupId>net.sf.jacob-project</groupId>
<artifactId>jacob</artifactId>
<version>1.14.3</version>
</dependency>
getsavefilename<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14-beta1</version>
</dependency>
⽹上查jacob对应版本包把jacob-1.14.3-x64.dll复制到需要在Java\jdk1.8.0\jre\bin⽬录下,
经过多次测试发现jacob对于Excel的转换有些问题,所以Excel的转换我⽤的是poi
⾃定义⼀个⼯具类Word2Pdf
import com.jacob.activeX.ActiveXComponent;
import com.jacob.Dispatch;
import com.jacob.Variant;
import java.io.*;
public class Word2Pdf {
static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。
static final int wdFormatPDF = 17;// word转PDF 格式
static final int ppSaveAsPDF = 32;// ppt 转PDF 格式
public static void main(String[] args) throws IOException {
}
public void word2pdf(String wordPath,String target,String wordName,String suffix){
System.out.println("启动Word");
long start = System.currentTimeMillis();
String source = wordPath + wordName + suffix;
target = target + wordName ;
ActiveXComponent app = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
app.setProperty("DisplayAlerts", new Variant(false));
Dispatch docs = Property("Documents").toDispatch();
System.out.println("打开⽂档" + source);
Dispatch doc = Dispatch.call(docs,//
"Open", //
source,// FileName
false,// ConfirmConversions
true // ReadOnly
).toDispatch();
System.out.println("转换⽂档到PDF " + target);
File tofile = new File(target);
//验证⽬标路径是否存在
if (ists()) {
System.out.println("存在");
}
Dispatch.call(doc,//
"SaveAs", //
target, // FileName
wdFormatPDF);
Dispatch.call(doc, "Close", false);
long end = System.currentTimeMillis();
System.out.println("转换完成..⽤时:" + (end - start) + "ms.");
//            Cut.cutfile(str_s,str_d);
} catch (Exception e) {
System.out.println("========Error:⽂档转换失败:" + e.getMessage());
} finally {
if (app != null)
app.invoke("Quit", wdDoNotSaveChanges);
}
}
public void ppt2pdf(String wordPath,String target,String wordName,String suffix){        System.out.println("启动PPT");
String source = wordPath + wordName + suffix;
target = target + wordName ;
long start = System.currentTimeMillis();
ActiveXComponent app = null;
try {
app = new ActiveXComponent("Powerpoint.Application");
Dispatch presentations = Property("Presentations").toDispatch();
System.out.println("打开⽂档" + source);
Dispatch presentation = Dispatch.call(presentations,//
"Open",
source,// FileName
true,// ReadOnly
true,// Untitled 指定⽂件是否有标题。
false // WithWindow 指定⽂件是否可见。
).toDispatch();
System.out.println("转换⽂档到PDF " + target);
File tofile = new File(target);
if (ists()) {
if (ists()) {
tofile.delete();
}
Dispatch.call(presentation,//
"SaveAs", //
target, // FileName
ppSaveAsPDF);
Dispatch.call(presentation, "Close");
long end = System.currentTimeMillis();
System.out.println("转换完成..⽤时:" + (end - start) + "ms.");
} catch (Exception e) {
System.out.println("========Error:⽂档转换失败:" + e.getMessage());
} finally {
if (app != null) app.invoke("Quit");
}
}
}
再定义⼀个poi转换Html的⼀个类ExcelToHtml
import com.jacob.activeX.ActiveXComponent;
import com.jacob.ComThread;
import com.jacob.Dispatch;
import com.jacob.Variant;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ExcelToHtml {
private final static ExcelToHtml oOfficeToXML = new ExcelToHtml();
public static ExcelToHtml getInstance() {
return oOfficeToXML;
}
public ExcelToHtml() {
}
/**
* 因为poi转换的Html页⾯在浏览器中显⽰时会出现乱码问题,这⾥强制转换⼀下
* @param filePath
*/
public void html2utf(String filePath) {
try {
String content = "charset=utf-8";
String templateContent = "";
FileInputStream fileinputstream = new FileInputStream(filePath);// 读取模板⽂件
// 下⾯四⾏:获得输⼊流的长度,然后建⼀个该长度的数组,然后把输⼊流中的数据以字节的形式读⼊到数组中,然后关闭流int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.close();
// 通过使⽤默认字符集解码指定的 byte 数组,构造⼀个新的
//因为原来的html⽂件是gb2312格式,所以转为string时也要以GBK格式读取,不然依旧是乱码
templateContent = new String(bytes, "GBK");
templateContent = placeFirst("charset=gb2312", content);
// 因为已经替换字符串了,所以使⽤UTF-8字符集将此 String 编码为 byte 序列,并将结果存储到⼀个新的 byte 数组中。
byte tag_bytes[] = Bytes("UTF-8");
FileOutputStream fileoutputstream = new FileOutputStream(filePath);// 建⽴⽂件输出流
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
} catch (Exception e) {
System.out.String());
}
}
}
public boolean ExceltoHtml(String wordPath,String original_name,String target,String wordName,String suffix) {        ComThread.InitSTA();
ActiveXComponent activexcomponent = new
ActiveXComponent("Excel.Application");
String source = wordPath + original_name + suffix;
target = target + wordName;
boolean flag = false;
try
{
activexcomponent.setProperty("Visible", new Variant(false));
Dispatch dispatch =
Dispatch dispatch1 = Dispatch.invoke(dispatch, "Open", 1, new
Object[] {
source, new Variant(false), new Variant(true)
}, new int[1]).toDispatch();
Dispatch.call(dispatch1, "SaveAs", target, new Variant(44));
Variant variant = new Variant(false);
Dispatch.call(dispatch1, "Close", variant);
flag = true;
}
catch(Exception exception)
{
System.out.println("|||" + String());
}
finally
{
activexcomponent.invoke("Quit", new Variant[0]);
ComThread.Release();
ComThread.quitMainSTA();
}
return flag;
}
}
主要的两个类已完成,因为这只是⼀个⼩demo所以代码可能有些不太规范
controller类
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import pojo.UpFile;
import tools.ExcelToHtml;
import tools.Word2Pdf;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/sys")
public class controller {
Word2Pdf word2Pdf = new Word2Pdf();

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。