项目需要对上传的word及pdf进行在线预览,因基于jquery的pdf插件,很方面实现在线预览,而word实现在线预览费劲不少,于是想到在进行上传处理时,直接将word转成pdf,在预览时直接预览pdf实现在线预览。而项目环境为win server,于是决定使用jacob进行word转pdf。
研究再三,发现jacob从2005年开始,共有19个版本,根据现有jdk版本及服务器版本,最终选中jacob1.15进行搭配。
下载地址:http://sourceforge.net/projects/jacob-project/?source=typ_redirect
处理如下:
1.将下载的jacob.jar放入项目lib目录。
2.将dll放入jre/bin目录。
3.java代码如下(转):
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class Word2Pdf {
static final int wdFormatPDF = 17;// PDF 格式
public void wordToPDF(String docFileName,String toFileName){
ComThread.InitSTA();
System.out.println("启动Word...");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.call(docs, "Open" , docFileName).toDispatch();
System.out.println("打开文档..." + docFileName);
System.out.println("转换文档到PDF..." + toFileName);
File tofile = new File(toFileName);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,
"SaveAs",
toFileName, // FileName
wdFormatPDF);
long end = System.currentTimeMillis();
System.out.println("转换完成..用时:" + (end - start) + "ms.");
} catch (Exception e) {
System.out.println("========Error:文档转换失败:" + e.getMessage());
} finally {
Dispatch.call(doc,"Close",false);
System.out.println("关闭文档");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//如果没有这句话,winword.exe进程将不会关闭
ComThread.Release();
}
public static void main(String[] args) {
Word2Pdf d2p = new Word2Pdf();
d2p.wordToPDF("C:/Users/SIR/Desktop/1228.doc","C:/Users/SIR/Desktop/1228.pdf");
}
}
4.html代码实现
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<script type="text/javascript" src="avascript/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery.media.js"></script>
<style type="text/css">
body{ text-align:center;padding:0px;margin:0px;}
div{ margin:0 auto; width:800px; height:100%; }
ul{
font-size:14px;
line-height:30px;
text-align: left;
}
</style>
<script type="text/javascript">
$(function() {
$('a.media').media({width:800, height:600});
});
</script>
</head>
<body>
<div>
<a class="media" href="${ctx}/upload/${fileid}.pdf"></a>
</div>
<div>
<p>说明:如未正确显示预览文件,由以下情况导致!
<ul>
<li>本地未安装PDF阅读器,请下载并Adobe Reader或福昕PDF阅读器!</li>
<li>如本地已安装PDF阅读器,请按如下操作步骤进行设定。<br/>
1.如本地已有Adobe Reader,请点击》编辑》首选项》英特网》在浏览器中显示PDF》勾选》保存<br/>
2.如本地已有福昕PDF阅读器,请点击》工具》偏好设置》文件关联》在浏览器内显示PDF》勾选》保存<br/></li>
</ul>
</div>
</body>
</html>