使用jacob + SWFTool + flexpaper进行office的页面预览
来源:互联网 发布:c语言pow函数源代码 编辑:程序博客网 时间:2024/06/05 23:44
实现思路是现将office文件统一转换成pdf文件,再讲pdf文件转换成swf文件,最后使用flexpaper插件将swf文件预览在页面上
先搭jacob的环境吧
- 导入所用到的jar包
- 将jacob.dll文件放入jdk的bin中,system32文件夹下,tomcat的bin下
接下来就可以测试office文件是否能转成pdf文件
代码如下
public class File2PDF { static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。 static final int wdFormatPDF = 17;// word转PDF 格式 static final int ppSaveAsPDF = 32;// ppt 转PDF 格式 private static Logger logger = Logger.getLogger(File2PDF.class); public static void main(String[] args) { String source = "C:\\Users\\Administrator\\Desktop\\开心开心真开心.docx"; String target = "C:\\Users\\Administrator\\Desktop\\test.pdf"; File2PDF.word2pdf(source, target); } public static void word2pdf(String source,String target){ logger.info("启动word"); long start = System.currentTimeMillis(); ActiveXComponent app = null; try { app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", false); Dispatch docs = app.getProperty("Documents").toDispatch(); logger.info("启动word"); Dispatch doc = Dispatch.call(docs,// "Open", // source,// FileName false,// ConfirmConversions true // ReadOnly ).toDispatch(); logger.info("转换文档到PDF " + target); File tofile = new File(target); if (tofile.exists()) { tofile.delete(); } Dispatch.call(doc,// "SaveAs", // target, // FileName wdFormatPDF); Dispatch.call(doc, "Close", false); long end = System.currentTimeMillis(); logger.info("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) { logger.error("========Error:文档转换失败:" + e.getMessage()); } finally { if (app != null) app.invoke("Quit", wdDoNotSaveChanges); } } public static void ppt2pdf(String source,String target){ logger.info("启动PPT"); long start = System.currentTimeMillis(); ActiveXComponent app = null; try { app = new ActiveXComponent("Powerpoint.Application"); Dispatch presentations = app.getProperty("Presentations").toDispatch(); logger.info("打开文档" + source); Dispatch presentation = Dispatch.call(presentations,// "Open", source,// FileName true,// ReadOnly true,// Untitled 指定文件是否有标题。 false // WithWindow 指定文件是否可见。 ).toDispatch(); logger.info("转换文档到PDF " + target); File tofile = new File(target); if (tofile.exists()) { tofile.delete(); } Dispatch.call(presentation,// "SaveAs", // target, // FileName ppSaveAsPDF); Dispatch.call(presentation, "Close"); long end = System.currentTimeMillis(); logger.info("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) { logger.error("========Error:文档转换失败:" + e.getMessage()); } finally { if (app != null) app.invoke("Quit"); } } public static void excel2pdf(String source, String target) { logger.info("启动Excel"); long start = System.currentTimeMillis(); ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动excel(Excel.Application) try { app.setProperty("Visible", false); Dispatch workbooks = app.getProperty("Workbooks").toDispatch(); logger.info("打开文档" + source); Dispatch workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method, new Object[]{source, new Variant(false),new Variant(false)}, new int[3]).toDispatch(); Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] { target, new Variant(57), new Variant(false), new Variant(57), new Variant(57), new Variant(false), new Variant(true), new Variant(57), new Variant(true), new Variant(true), new Variant(true) }, new int[1]); Variant f = new Variant(false); logger.info("转换文档到PDF " + target); Dispatch.call(workbook, "Close", f); long end = System.currentTimeMillis(); logger.info("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) { logger.info("========Error:文档转换失败:" + e.getMessage()); }finally { if (app != null){ app.invoke("Quit", new Variant[] {}); } } } public static boolean imgToPdf(String imgFilePath, String pdfFilePath)throws IOException { File file=new File(imgFilePath); if(file.exists()){ Document document = new Document(); FileOutputStream fos = null; try { fos = new FileOutputStream(pdfFilePath); PdfWriter.getInstance(document, fos); // 添加PDF文档的某些信息,比如作者,主题等等 document.addAuthor("arui"); document.addSubject("test pdf."); // 设置文档的大小 document.setPageSize(PageSize.A4); // 打开文档 document.open(); // 写入一段文字 //document.add(new Paragraph("JUST TEST ...")); // 读取一个图片 Image image = Image.getInstance(imgFilePath); float imageHeight=image.getScaledHeight(); float imageWidth=image.getScaledWidth(); int i=0; while(imageHeight>500||imageWidth>500){ image.scalePercent(100-i); i++; imageHeight=image.getScaledHeight(); imageWidth=image.getScaledWidth(); System.out.println("imageHeight->"+imageHeight); System.out.println("imageWidth->"+imageWidth); } image.setAlignment(Image.ALIGN_CENTER); //设置图片的绝对位置 // image.setAbsolutePosition(0, 0); // image.scaleAbsolute(500, 400); // 插入一个图片 document.add(image); } catch (DocumentException de) { System.out.println(de.getMessage()); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } document.close(); fos.flush(); fos.close(); return true; }else{ return false; } }}
再安装swftool文件
安装好后记录安装目录下pdf2swf.exe文件的路径,需要cmd命令操作该软件将pdf转换为swf,因为jacob只能在windows下使用,如果需要在linux下运行,就得换工具了,代码如下:
public class DocConverter { private static Logger logger = Logger.getLogger(DocConverter.class); private static int environment;//环境1:windows 2:linux(涉及pdf2swf路径问题) private String fileName; private File pdfFile; private File swfFile; private File docFile; static{ if(isWindowsSys()){ environment = 1; }else{ environment = 2; } } public DocConverter(String fileString){ ini(fileString); } /* * 重新设置 file * @param fileString */ public void setFile(String fileString){ ini(fileString); } /** * @param fileString * 初始化 */ private void ini(String fileString){ fileName=fileString.substring(0,fileString.lastIndexOf(".")); docFile=new File(fileString); pdfFile=new File(fileName+".pdf"); String s = fileName.substring(0,fileName.lastIndexOf(File.separator)); String e = fileName.substring(fileName.lastIndexOf(File.separator)+1); String utf8name = ChineToUTFUtils.getUtf8(e); utf8name = s+File.separator+utf8name; swfFile=new File(utf8name+".swf");//转换后输出的swf文件 } /** * 判断是否是windows操作系统 * @author Liubf * @return true false */ private static boolean isWindowsSys() { String p = System.getProperty("os.name"); return p.toLowerCase().indexOf("windows") >= 0 ? true : false; } /** * 转swf文件 */ private void pdf2swf(String exePath){//exePath参数是swftools执行文件的路径 logger.info("2222222222222222222"); Runtime r=Runtime.getRuntime(); if(!swfFile.exists()){ if(pdfFile.exists()){ if(environment==1){//windows环境处理 try { logger.info("3333333333333333"); String cmd = exePath + " -o " + swfFile.getPath() + " -s flashversion=9 " + pdfFile.getPath(); logger.info("执行命令" + cmd); Process p=r.exec(cmd); loadStream(p.getInputStream()); logger.info("****swf转换成功,文件输出:"+swfFile.getPath()+"****"); if(pdfFile.exists()) { logger.info("4444444444444"); //pdfFile.delete(); } }catch (Exception e){ logger.info("报错" + e.getMessage()); e.printStackTrace(); } }else if(environment==2){//linux环境处理 try { Process p=r.exec(exePath+" "+pdfFile.getPath()+" -o "+swfFile.getPath()+" -T 9 -t -s storeallcharacters"); loadStream(p.getInputStream()); if(pdfFile.exists()){ //pdfFile.delete(); } }catch(Exception e){ e.printStackTrace(); } } }else{ logger.error("****pdf不存在,无法转换****"); } }else{ logger.info("****swf已存在不需要转换****"); } } static String loadStream(InputStream in){ int ptr=0; in=new BufferedInputStream(in); StringBuffer buffer=new StringBuffer(); try { while((ptr=in.read())!=-1) { buffer.append((char)ptr); } } catch (IOException e) { logger.error("加载数据流异常",e); } return buffer.toString(); } /** * @param fileName 文件名(含后缀) * @return true false * 转换主方法 */ public String conver(String fileName,String openIp,String exePath){ String fileTypes = fileName.substring(fileName.lastIndexOf(".") + 1); MagicMatch match; try { match = Magic.getMagicMatch(new File(fileName), false); //String fileTypes = match.getExtension(); String contentTypes = match.getMimeType(); if (StringUtils.isBlank(contentTypes)) { logger.error("当前文件类型不支持预览: "+ fileName ); return null; }else{ if(swfFile.exists()) { //System.out.println("****swf转换器开始工作,该文件已经转换为swf****"); return swfFile.getPath(); } try { if(CommonFunction.isWORD(fileTypes)) { File2PDF.word2pdf(docFile.getPath(), pdfFile.getPath()); } logger.info("111111111111111111111111"); if(CommonFunction.isPPT(fileTypes)) { File2PDF.ppt2pdf(docFile.getPath(), pdfFile.getPath()); } if(CommonFunction.isEXCEL(fileTypes)) { File2PDF.excel2pdf(docFile.getPath(), pdfFile.getPath()); } if(CommonFunction.isPDF(fileTypes)) { //FileUtils.moveFile(docFile, pdfFile); pdfFile = docFile; } pdf2swf(exePath); } catch (Exception e) { e.printStackTrace(); return null; } if(swfFile.exists()) { return swfFile.getPath(); } else { return null; } } } catch (Exception e) { e.printStackTrace(); return null; } }}
最后一步,使用flexpaper将swf文件显示在页面上
先得将js和swf文件导入到项目中来,贴张图:
flexpaper.js中设置有swf文件的路径,根据自己的需要进行修改,主要改这两个地方吧
再贴上jsp代码:
<div id="viewerPlaceHolder" class="flexpaper_viewer" style="width:1084px;height:560px;"></div> <script type="text/javascript"> var swfpath = "${ swfpath }"; $('#viewerPlaceHolder').FlexPaperViewer( { config : { SWFFile : escape(swfpath +''), Scale : 1, ZoomTransition : 'easeOut', ZoomTime : 0.5, ZoomInterval : 0.2, FitPageOnLoad : false, FitWidthOnLoad : true, FullScreenAsMaxWindow : false, ProgressiveLoading : false, MinZoomSize : 0.5, MaxZoomSize : 2, SearchMatchAll : true, InitViewMode : 'Portrait', ReaderingOrder :'false', StartAtPage :'', ViewModeToolsVisible : true, ZoomToolsVisible : true, NavToolsVisible : true, CursorToolsVisible : true, SearchToolsVisible : true, localeChain: 'zh_CN' }}); </script>
好了,这就差不多大功告成了,中间也是遇到了不少问题,总结一下:
- jacob的jar包和dll文件得找对,第一次找的就用不了..
- 再自己机子上可以运行,但是在服务器上excel转pdf失败,百度了很久,是因为服务器上的excel启动方式不对,解决方法
开始 ->运行 输入dcomcnfg.exe启动组件服务 ->DCOM配置 ->Microsoft EXCEL ->右击点属性 ->标示->选择交互式用户(如果没找到,可能是因为EXCEL是32位组件,在运行 输入comexp.msc -32剩下步骤一样) - swftool的命令问题
举个例子吧
D:\SWFTools\pdf2swf.exe -o SWfFile.swf -s flashversion=9 PDFFile.pdf
还有其他的一些小问题就不一一列举了,中间引用了好些篇文章,感谢。
以上。(第一篇博文,好激动。。)
阅读全文
0 0
- 使用jacob + SWFTool + flexpaper进行office的页面预览
- FlexPaper+SWFTool+操作类=在线预览PDF
- centos6.5下安装openoffice+jodconverter+swftool+flexpaper工具实现在线预览文档功能
- 使用jacob操作office
- 在线文档查阅-OpenOffice+SWFTool+FlexPaper
- 在线预览文档openoffice+swfTool
- 使用FlexPaper实现PDF文件在线预览
- 使用FlexPaper实现PDF文件在线预览
- flexpaper实现文档的在线预览
- Java + FlexPaper 实现 pdf 的预览功能
- 文档在线预览(四)- 使用FlexPaper预览文档
- 使用Jacob操作Office(一)
- 使用java jacob转换office到pdf
- 使用java jacob转换office到pdf
- swftool pdf2swf使用
- flexpaper的使用
- 关于FlexPaper的使用
- 使用flexpaper实现在线预览功能时 ,遇到的flash缓存问题的解放方案
- 农村女孩高中才接触电脑,却成为程序媛的心路历程
- CAN 帧ID 与J1939 PGN 转换例子
- Spring基础学习教程(Spring之核心容器bean)-06
- 关于绝对路径和相对路径
- 关于mysql分区表主键的选择
- 使用jacob + SWFTool + flexpaper进行office的页面预览
- Vware安装centos7找不到网卡
- C 字符串与数字的转换
- Linux 终端颜色,界面着色
- opencv(28)---GrabCut & FloodFill图像分割
- 电容的分类及作用
- 汇编语言: 从键盘上输入一串字符(用回车键结束,使用 10 号功能调用。)放在 STRING 中,试 编制一个程序测试字符串中是否存在数字。如有,则把 CL 的第 5 位置 1,否则将该位置置 0。
- iOS-矩阵与线性代数的关系____仿射变换
- 关于matlab计算定积分