Java程序实现Word文档转为pdf以及出现的问题解决

来源:互联网 发布:马苏德阿兹哈尔 知乎 编辑:程序博客网 时间:2024/06/18 00:05

做兽医项目需要用到这种需求,很多程序员都遇到过,有些word文档希望直接在浏览器中打开进行预览,但是浏览器往往不是很配合,直接就提示下载,不像pdf文档,浏览器可以直接进行预览。
1. Word文档转为pdf直接上代码:
import java.io.File;import org.apache.poi.POIXMLDocument;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.SAXReader;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 int wordToPDF(String sfileName,String toFileName) throws Exception{                        System.out.println("启动Word...");              long start = System.currentTimeMillis();              ActiveXComponent app = null;          Dispatch doc = null;          try {                  app = new ActiveXComponent("Word.Application");             // 设置word不可见            app.setProperty("Visible", new Variant(false));              // 打开word文件            Dispatch docs = app.getProperty("Documents").toDispatch();   //          doc = Dispatch.call(docs,  "Open" , sourceFile).toDispatch();               doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] {                                   sfileName, new Variant(false),new Variant(true) }, new int[1]).toDispatch();            System.out.println("打开文档..." + sfileName);              System.out.println("转换文档到PDF..." + toFileName);                  File tofile = new File(toFileName);               // System.err.println(getDocPageSize(new File(sfileName)));            if (tofile.exists()) {                      tofile.delete();                  }        //          Dispatch.call(doc, "SaveAs",  destFile,  17);            // 作为html格式保存到临时文件::参数 new Variant(8)其中8表示word转html;7表示word转txt;44表示Excel转html;17表示word转成pdf。。            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {                                toFileName, new Variant(17) }, new int[1]);                long end = System.currentTimeMillis();                  System.out.println("转换完成..用时:" + (end - start) + "ms.");                        } catch (Exception e) {              e.printStackTrace();              System.out.println("========Error:文档转换失败:" + e.getMessage());              }catch(Throwable t){        t.printStackTrace();        } finally {          // 关闭word            Dispatch.call(doc,"Close",false);              System.out.println("关闭文档");              if (app != null)                      app.invoke("Quit", new Variant[] {});                  }            //如果没有这句话,winword.exe进程将不会关闭             ComThread.Release();             return 1;           }      private static Document read(File xmlFile) throws DocumentException {        SAXReader saxReader = new SAXReader();        return saxReader.read(xmlFile);    }//    public String getDocPageSize(File file){//        String pages = null;//        try{//            Document doc = read(file);//            List<Node> nodes = doc.selectNodes("//o:Pages");//            if(nodes != null && nodes.size() > 0){//                pages = nodes.get(0).getText();//                System.out.println("/////////////////");//                System.out.println("该word文档的页数为:"+Integer.parseInt(pages));//                System.out.println("/////////////////");//            }else{//                System.out.println("*********");//                System.out.println("页面转换错误");//                System.out.println("*********");//            }//        }catch(Exception ex){//            ex.printStackTrace(); //        }//        return pages;//    }    public  int getDocPageSize(String filePath)  throws Exception {        XWPFDocument docx = new XWPFDocument(POIXMLDocument.openPackage(filePath));        int pages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//总页数        int wordCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格的总字符数 另外还有getCharactersWithSpaces()方法获取带空格的总字数。                System.out.println ("pages=" + pages + " wordCount=" + wordCount);        return pages;    }         public static void main(String[] args) throws Exception {      Word2pdf d = new Word2pdf();      System.err.println(d.getDocPageSize("d:\\exportWord.docx"));        d.wordToPDF("d:\\exportWord.docx", "d:\\law.pdf");      }    }  

可是能够完全运行的应该不可能,还要准备工作,

出错总结:

1.没引入jar包,,这个错误我就不说了,,基本上所有人都可以避免.jacob.jar

2.

出现这个错误是因为缺少了jacob-1.17-x64.dll这个东西,,把jacob.dll(不同版本的jacob的dll文件名有所不同)复制到C:\Program Files\Java\jdk1.6.0_17\jre\bin(项目中用到的jre)目录下即可。

注意:名字一定要改成和报错的时候一样的名字,差一点也不行。

3.由于出错没有截图,所以现在错误也不好去演示了,,简单的就是下面的错误

com.jacob.com.ComFailException: Invoke of: SaveAs 

Source: Microsoft Word 

Description: 命令失败

出现这种错误网上也有很多解决办法:如下

Office版本使用2007,因为2007提供了一个加载项:Microsoft Save as PDF 或 XPS,可将文档另存为PDF格式。下载地址:http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=4D951911-3E7E-4AE6-B059-A2E79ED87041,安装即可使用。 

4.最后一步,

d.wordToPDF("d:\\exportWord.docx", "d:\\law.pdf");
这个目录一定要写正确,如果你写成d:\\pdf\\law.pdf,而d盘中又没有pdf文件夹,则会报如下错误
<img src="http://img.blog.csdn.net/20161027104907109?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

避免上面4种错误,则能够万无一失了,,还有jar和dll文件版本要对应。。由于我没出现这个错误,不过网上有人出过,,注意下就可以了。


0 0
原创粉丝点击