近日在项目中需要将word文档嵌入到jsp页面中,遇到这个问题,首先想到的解决方法便是将word内容读取,然后放入jsp中,可是这样做有一个难点,就是读取word的格式,图片以及表格等内容,由于在前几日用过jacob将word转换为pdf文件,所以试想,能不能将word转换为htm文件,直接展示就容易很多,经过研究,果然可以做到,步骤如下: 第一步 下载jacob 下载地址:/download/ide/4107.html 第二步 解压下载的文件,将其中dll文件放入tomcat bin目录和jdk的bin目录下,将jacob.jar 放入项目的lib库中。 第三步 复制以下方法到任意类中。 public boolean transWord2Htm(String docFile) { String HtmlFile = docFile.substring(0, (docFile.length() - 4)) + ".htm"; ActiveXComponent app = new ActiveXComponent("Word.Application"); try { app.setProperty("Visible", new Variant(false)); Dispatch docs = app.getProperty("Documents").toDispatch(); Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { docFile, new Variant(false),new Variant(true) }, new int[1]).toDispatch(); //打开word文件 Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {HtmlFile, new Variant(8)}, new int[1]); //作为htm格式保存文件 Dispatch.call(doc, "Close", new Variant(false)); } catch (Exception e) { e.printStackTrace(); return false; } finally { app.invoke("Quit", new Variant[] {}); } return true; } 第四部 调用以上方法即可。其中参数String docFile为word文件的绝对路径,例如:C:\\a.doc,如果是在servlet中或者action中,调用 request.getSession().getServletContext().getRealPath("/")即可获得项目的绝对路径。 运行以后,会在doc目录下生成同名的htm文件和一个htm文件夹,存放图片等资源,直接调用即可。 |
|