因为要做文件在线预览 . 网上找了方法是需要调用公网微软地址传入我的文件路径
<iframe src='https://view.officeapps.live.com/op/view.aspx?src=http://storage.xuetangx.com/public_assets/xuetangx/PDF/1.xls' width='100%' height='100%' frameborder='1'> </iframe>
但是, 我们项目是内网项目, 无法实现
PDF在页面预览已经实现 , 因此想着可否将Excel 与 Word文件首次预览的时候 , 转为PDF在页面显示 , 第二次预览直接调用就行
下面这个方法只支持Windows系统
首先需要在电脑安装 SaveAsPDFandXPS
需要下载 jacob-1.19 (jar包放入项目 , 两个dll文件放入你本地的jre下的bin目录)
下面是代码(亲测)
private static final int wdFormatPDF = 17;// PDF 格式
/**
* 将word转为pdf
* @param wordPath
* @param pdfPath
*/
public String wordToPDF(String wordPath, String pdfPath){
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" , wordPath).toDispatch();
File tofile = new File(pdfPath);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,"SaveAs", pdfPath, wdFormatPDF);
if(app != null){
app.invoke("Quit",new Variant[]{});
app = null;
}
ComThread.Release();
return "";
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
/**
* 将excel转为pdf
* @param wordPath
* @param pdfPath
*/
public String excelToPdf(String excelPath, String pdfPath){
ComThread.InitSTA(true);
ActiveXComponent ax=new ActiveXComponent("Excel.Application");
try{
ax.setProperty("Visible", new Variant(false));
ax.setProperty("AutomationSecurity", new Variant(3)); //禁用宏
Dispatch excels=ax.getProperty("Workbooks").toDispatch();
// 读取Excel
Dispatch excel=Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[]{
excelPath,
new Variant(false),
new Variant(false)
},
new int[9]).toDispatch();
// 转换格式
Dispatch.invoke(excel,"ExportAsFixedFormat",Dispatch.Method,new Object[]{
new Variant(0), // PDF 格式 = 0
pdfPath,
new Variant(0) // 0 = 标准 (生成的PDF图片不会变模糊) 1 = 最小文件 (生成的PDF图片糊的一塌糊涂)
},new int[1]);
Dispatch.call(excel, "Close",new Variant(false));
if(ax!=null){
ax.invoke("Quit",new Variant[]{});
ax=null;
}
ComThread.Release();
return "";
}catch(Exception es){
es.printStackTrace();
return es.toString();
}
}