(java office转pdf) MS Office2010、WPS2015、OpenOffice4用Java将Office文档转换为PDF,WIN7 64位系统

来源:互联网 发布:网络布线施工室分 编辑:程序博客网 时间:2024/05/17 02:09

1.前言

MS Office2010是可以的,理论上2007版本也可以,博主没试过;

Wps2015是可以的,理论上Wps2016也能用,Wps理论上还兼容MS Office的相关代码,有时间的可以试试;

Wps和Ms Office都需要导入jacob-1.18.jar包,以及将jacob-1.18-x64.dll或者jacob-1.18-x64.dll放置到jdk的bin目录(或者windows的System32/SysWoW64目录下)

而OpenOffice需要导入jodconverter-2.2.1.jar等相关包;

相关包的下载链接,包含实现代码:http://download.csdn.net/detail/huitoukest/9506740

包中的代码可能没有捕获NoClassDefFoundError异常和,建议使用者自行捕获;

2.MS Office2010

核心代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private static final int wdFormatPDF = 17;  
  2.     private static final int xlTypePDF = 0;  
  3.     private static final int ppSaveAsPDF = 32;  
  4.     //private static final int msoTrue = -1;  
  5.     //private static final int msofalse = 0;  
  6.     /** 
  7.      * @return 操作成功与否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置错误; 如果返回 0, 
  8.      *         则表示操作成功; 返回1, 则表示转换失败 
  9.      */  
  10.     @Override  
  11.     public int officeToPdf(OfficeToPDFInfo officeToPDFInfo) {  
  12.         String sourceFile=officeToPDFInfo.sourceUrl;  
  13.         String destFile=officeToPDFInfo.destUrl;  
  14.             File inputFile = new File(sourceFile);  
  15.             if (!inputFile.exists()) {  
  16.                 return -1;// 找不到源文件, 则返回-1  
  17.             }  
  18.             // 如果目标路径不存在, 则新建该路径  
  19.             File outputFile = new File(destFile);  
  20.             if (!outputFile.getParentFile().exists()) {  
  21.                 outputFile.getParentFile().mkdirs();  
  22.             }  
  23.             String extentionName=FileUtils.getFileExtension(sourceFile);  
  24.             if(extentionName.equalsIgnoreCase("ppt")||extentionName.equalsIgnoreCase("pptx"))  
  25.             {  
  26.                 ppt2pdf(officeToPDFInfo.sourceUrl,officeToPDFInfo.destUrl);  
  27.             }else if(extentionName.equalsIgnoreCase("doc")||extentionName.equalsIgnoreCase("docx")){  
  28.                 doc2pdf(officeToPDFInfo.sourceUrl,officeToPDFInfo.destUrl);  
  29.             }else if(extentionName.equalsIgnoreCase("xls")||extentionName.equalsIgnoreCase("xlsx")){  
  30.                 excel2PDF(officeToPDFInfo.sourceUrl,officeToPDFInfo.destUrl);  
  31.             }     
  32.             return 0;  
  33.     }  
  34.       
  35.     protected static boolean doc2pdf(String srcFilePath, String pdfFilePath) {    
  36.         ActiveXComponent app = null;    
  37.         Dispatch doc = null;    
  38.         try {    
  39.             ComThread.InitSTA();    
  40.             app = new ActiveXComponent("Word.Application");    
  41.             app.setProperty("Visible"false);    
  42.             Dispatch docs = app.getProperty("Documents").toDispatch();    
  43.             doc = Dispatch.invoke(docs, "Open", Dispatch.Method,    
  44.                     new Object[] { srcFilePath,     
  45.                                                  new Variant(false),     
  46.                                                  new Variant(true),//是否只读    
  47.                                                  new Variant(false),     
  48.                                                  new Variant("pwd") },    
  49.                     new int[1]).toDispatch();    
  50.             // Dispatch.put(doc, "Compatibility", false);  //兼容性检查,为特定值false不正确    
  51.             Dispatch.put(doc, "RemovePersonalInformation"false);    
  52.             Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath,wdFormatPDF); // word保存为pdf格式宏,值为17  
  53.             return true// set flag true;    
  54.         }finally {    
  55.             if (doc != null) {    
  56.                 Dispatch.call(doc, "Close"false);    
  57.             }    
  58.             if (app != null) {    
  59.                 app.invoke("Quit"0);    
  60.             }    
  61.             ComThread.Release();    
  62.         }    
  63.     }  
  64.       
  65.     protected static boolean ppt2pdf(String srcFilePath, String pdfFilePath) {    
  66.         ActiveXComponent app = null;    
  67.         Dispatch ppt = null;    
  68.             try {    
  69.                 ComThread.InitSTA();    
  70.                 app = new ActiveXComponent("PowerPoint.Application");    
  71.                 Dispatch ppts = app.getProperty("Presentations").toDispatch();    
  72.     
  73.                 // 因POWER.EXE的发布规则为同步,所以设置为同步发布    
  74.                 ppt = Dispatch.call(ppts, "Open", srcFilePath, true,// ReadOnly    
  75.                         true,// Untitled指定文件是否有标题    
  76.                         false// WithWindow指定文件是否可见    
  77.                         ).toDispatch();    
  78.                 Dispatch.call(ppt, "SaveAs", pdfFilePath, ppSaveAsPDF); //ppSaveAsPDF为特定值32      
  79.                 return true// set flag true;    
  80.             }finally {    
  81.                 if (ppt != null) {    
  82.                     Dispatch.call(ppt, "Close");    
  83.                 }    
  84.                 if (app != null) {    
  85.                     app.invoke("Quit");    
  86.                 }    
  87.                 ComThread.Release();    
  88.             }  
  89.     }   
  90.      public static boolean excel2PDF(String inputFile,String pdfFile){  
  91.          ActiveXComponent app=null;  
  92.          Dispatch excel =null;  
  93.          try{  
  94.             ComThread.InitSTA();    
  95.             app = new ActiveXComponent("Excel.Application");  
  96.             app.setProperty("Visible"false);  
  97.             Dispatch excels = app.getProperty("Workbooks").toDispatch();  
  98.             excel = Dispatch.call(excels,"Open",inputFile, false,true).toDispatch();  
  99.             Dispatch.call(excel,"ExportAsFixedFormat", xlTypePDF,pdfFile);  
  100.             return true;  
  101.         }finally{  
  102.               if (excel!= null) {  
  103.                   Dispatch.call(excel, "Close");    
  104.               }    
  105.               if (app != null) {    
  106.                   app.invoke("Quit");    
  107.               }  
  108.               ComThread.Release();    
  109.         }              
  110.         }  

2.Wps 2015

核心代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public final static String WORDSERVER_STRING="KWPS.Application";  
  2.     public final static String PPTSERVER_STRING="KWPP.Application";  
  3.     public final static String EXECLSERVER_STRING="KET.Application";  
  4.     private static final int wdFormatPDF = 17;  
  5.     private static final int xlTypePDF = 0;  
  6.     private static final int ppSaveAsPDF = 32;  
  7.       
  8.     /** 
  9.      * @return 操作成功与否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置错误; 如果返回 0, 
  10.      *         则表示操作成功; 返回1, 则表示转换失败 
  11.      */  
  12.     @Override  
  13.     public int officeToPdf(OfficeToPDFInfo officeToPDFInfo) {  
  14.         String sourceFile=officeToPDFInfo.sourceUrl;  
  15.         String destFile=officeToPDFInfo.destUrl;  
  16.             File inputFile = new File(sourceFile);  
  17.             if (!inputFile.exists()) {  
  18.                 return -1;// 找不到源文件, 则返回-1  
  19.             }  
  20.             // 如果目标路径不存在, 则新建该路径  
  21.             File outputFile = new File(destFile);  
  22.             if (!outputFile.getParentFile().exists()) {  
  23.                 outputFile.getParentFile().mkdirs();  
  24.             }  
  25.             String extentionName=FileUtils.getFileExtension(sourceFile);  
  26.             if(extentionName.equalsIgnoreCase("ppt")||extentionName.equalsIgnoreCase("pptx")||extentionName.equalsIgnoreCase("wpt"))  
  27.             {  
  28.                 ppt2pdf(officeToPDFInfo.sourceUrl,officeToPDFInfo.destUrl);  
  29.             }else if(extentionName.equalsIgnoreCase("doc")||extentionName.equalsIgnoreCase("docx")||extentionName.equalsIgnoreCase("wps")){  
  30.                 doc2pdf(officeToPDFInfo.sourceUrl,officeToPDFInfo.destUrl);  
  31.             }else if(extentionName.equalsIgnoreCase("xls")||extentionName.equalsIgnoreCase("xlsx")||extentionName.equalsIgnoreCase("et")){  
  32.                 excel2PDF(officeToPDFInfo.sourceUrl,officeToPDFInfo.destUrl);  
  33.             }     
  34.             return 0;  
  35.     }  
  36.     protected static boolean doc2pdf(String srcFilePath, String pdfFilePath) {    
  37.          ActiveXComponent pptActiveXComponent=null;   
  38.          ActiveXComponent workbook = null;   
  39.         try {  
  40.              ComThread.InitSTA();//初始化COM线程    
  41.              pptActiveXComponent = new ActiveXComponent(WORDSERVER_STRING);//初始化exe程序    
  42.              Variant[] openParams=new Variant[]{  
  43.                     new Variant(srcFilePath),//filePath  
  44.                     new Variant(true),  
  45.                     new Variant(true)//readOnley  
  46.              };  
  47.              workbook = pptActiveXComponent.invokeGetComponent("Documents").invokeGetComponent  
  48.                     ("Open",openParams);  
  49.              workbook.invoke("SaveAs",new Variant(pdfFilePath),new Variant(wdFormatPDF));                  
  50.              return true;  
  51.         }finally{  
  52.              if(workbook!=null)  
  53.              {  
  54.                  workbook.invoke("Close");   
  55.                  workbook.safeRelease();   
  56.              }  
  57.              if(pptActiveXComponent!=null)  
  58.              {            
  59.                  pptActiveXComponent.invoke("Quit");   
  60.                  pptActiveXComponent.safeRelease();  
  61.              }  
  62.              ComThread.Release();    
  63.          }  
  64.     }  
  65.       
  66.     protected static boolean ppt2pdf(String srcFilePath, String pdfFilePath) {  
  67.          ActiveXComponent pptActiveXComponent=null;   
  68.          ActiveXComponent workbook = null;    
  69.          boolean readonly = true;  
  70.         try {  
  71.              ComThread.InitSTA();//初始化COM线程    
  72.              pptActiveXComponent = new ActiveXComponent(PPTSERVER_STRING);//初始化exe程序    
  73.              workbook = pptActiveXComponent.invokeGetComponent("Presentations").invokeGetComponent  
  74.                     ("Open",new Variant(srcFilePath),new Variant(readonly));  
  75.              workbook.invoke("SaveAs",new Variant(pdfFilePath),new Variant(ppSaveAsPDF));                  
  76.              return true;  
  77.         }finally{  
  78.              if(workbook!=null)  
  79.              {  
  80.                  workbook.invoke("Close");   
  81.                  workbook.safeRelease();   
  82.              }  
  83.              if(pptActiveXComponent!=null)  
  84.              {            
  85.                  pptActiveXComponent.invoke("Quit");   
  86.                  pptActiveXComponent.safeRelease();  
  87.              }  
  88.              ComThread.Release();    
  89.          }  
  90.     }   
  91.      public static boolean excel2PDF(String srcFilePath,String pdfFilePath){  
  92.         ActiveXComponent et = null;   
  93.         Dispatch workbooks = null;    
  94.         Dispatch workbook = null;    
  95.              ComThread.InitSTA();//初始化COM线程    
  96.              //ComThread.InitSTA(true);    
  97.              try {    
  98.                  et = new ActiveXComponent(EXECLSERVER_STRING);//初始化et.exe程序    
  99.                  et.setProperty("Visible"new Variant(false));    
  100.                  workbooks = et.getProperty("Workbooks").toDispatch();    
  101.                  //workbook = Dispatch.call(workbooks, "Open", filename).toDispatch();//这一句也可以的    
  102.                  workbook = Dispatch.invoke(workbooks,"Open",Dispatch.Method,new Object[]{srcFilePath,0,true},new int[1]).toDispatch();     
  103.                  //Dispatch.invoke(workbook,"SaveAs",Dispatch.Method,new Object[]{pdfFilePath,xlTypePDF},new int[1]);  
  104.                  Dispatch.call(workbook,"ExportAsFixedFormat",new Object[]{xlTypePDF,pdfFilePath});  
  105.                  return true;  
  106.              }finally{  
  107.                  if(workbook!=null)  
  108.                  {  
  109.                      Dispatch.call(workbook,"Close");  
  110.                      workbook.safeRelease();   
  111.                  }  
  112.                  if(et!=null)  
  113.                  {            
  114.                      et.invoke("Quit");   
  115.                      et.safeRelease();  
  116.                  }  
  117.                  ComThread.Release();    
  118.              }  
  119.      }  

3.OpenOffice4.X

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public int officeToPdf(OfficeToPDFInfo officeToPDFInfo) throws IOException {  
  2.         String sourceFile=officeToPDFInfo.sourceUrl;  
  3.         String destFile=officeToPDFInfo.destUrl;  
  4.         String OpenOffice_HOME=officeToPDFInfo.openOfficeHOME;  
  5.             File inputFile = new File(sourceFile);  
  6.             if (!inputFile.exists()) {  
  7.                 return -1;// 找不到源文件, 则返回-1  
  8.             }  
  9.   
  10.             // 如果目标路径不存在, 则新建该路径  
  11.             File outputFile = new File(destFile);  
  12.             if (!outputFile.getParentFile().exists()) {  
  13.                 outputFile.getParentFile().mkdirs();  
  14.             }  
  15.   
  16.             //= "D:\\Program Files\\OpenOffice.org 3";//这里是OpenOffice的安装目录, 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是绝对没问题的  
  17.             // 如果从文件中读取的URL地址最后一个字符不是 '\',则添加'\'  
  18.             if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {  
  19.                 OpenOffice_HOME += "\\";  
  20.             }  
  21.             // 启动OpenOffice的服务  
  22.             String command = OpenOffice_HOME  
  23.                     + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;StarOffice.ServiceManager\" -nofirststartwizard";  
  24.             Process pro = Runtime.getRuntime().exec(command);  
  25.             // connect to an OpenOffice.org instance running on port 8100  
  26.             OpenOfficeConnection connection = new SocketOpenOfficeConnection(  
  27.                     "127.0.0.1"8100);  
  28.             connection.connect();  
  29.             // convert  
  30.             DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
  31.             //DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);   
  32.               
  33.             converter.convert(inputFile, outputFile);  
  34.             // close the connection  
  35.             connection.disconnect();  
  36.             // 关闭OpenOffice服务的进程  
  37.             pro.destroy();  
  38.             return 0;  
  39.     }  

0 0
原创粉丝点击