A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 郝永亮 于 2018-8-13 21:16 编辑

使用OFFICE把office文档转换为pdf文档
一、所需要的资源
1. jar包 (iText-2.1.5.jar,jacob.jar)
2. dll文件(jacob-1.17-M2-x64.dll,jacob-1.17-M2-x86.dll)
二、使用前准备


  • 把dll文件放在%JAVA_HOME%\bin下(注意系统是32位还是64位),也可以放在C:\Windows\System32下,如果是64位应该放在C:\Windows\SysWOW64 下。建议放在项目使用的jdk的bin目录下
  • 如果是在eclipse下开发,需要重新引入jdk(Preference/Java/Installed JREs)
  • 开发时将jacab.jar包放在项目lib下并add到liabraries中即可。
  • 当前电脑获取服务器必须安装office软件,否则无法进行文档转换操作。

三、编写office转换的工具类
  /**
* 这是一个工具类,主要是为了使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx)
* 转化为pdf文件<br>
* @date 2017-02-21
*
*/
public class Office2PDFUtil {
        
   /*********************************************** 调用服务器office安装来转换*******************************************************/
   
    private staticfinal int wdFormatPDF = 17;
     private staticfinal int xlTypePDF = 0;
     private staticfinal int ppSaveAsPDF = 32;
     private staticfinal int msoTrue = -1;
     private staticfinal int msofalse = 0;
    //直接调用这个方法即可
        publicstatic boolean convert2PDF(String inputFile, String pdfFile) {
            Stringsuffix =  getFileSufix(inputFile);
            Filefile = new File(inputFile);
           if(!file.exists()){
               System.out.println("文件不存在!");
               return false;
            }
           if(suffix.equals("pdf")){
               System.out.println("PDF not need to convert!");
               return false;
            }
           if(suffix.equals("doc")||suffix.equals("docx")||suffix.equals("txt")){
               return word2PDF(inputFile,pdfFile);
            }elseif(suffix.equals("ppt")||suffix.equals("pptx")){
               return ppt2PDF(inputFile,pdfFile);
            }elseif(suffix.equals("xls")||suffix.equals("xlsx")){
               return excel2PDF(inputFile,pdfFile);
            }elseif(suffix.equals("png") || suffix.equals("jpg") ||suffix.equals("jpeg") || suffix.equals("gif")){
               return img2PDF(inputFile,pdfFile);
            }else{
               System.out.println("文件格式不支持转换!");
               return false;
            }
        }
        publicstatic String getFileSufix(String fileName){
            intsplitIndex = fileName.lastIndexOf(".");
           return fileName.substring(splitIndex + 1);
        }
        publicstatic boolean word2PDF(String inputFile,String pdfFile){
            try{
            //打开word应用程序
           ActiveXComponent app = new ActiveXComponent("Word.Application");
            //设置word不可见
           app.setProperty("Visible", false);
            //获得word中所有打开的文档,返回Documents对象
           Dispatch docs = app.getProperty("Documents").toDispatch();
            //调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
           Dispatch doc = Dispatch.call(docs,
                                       "Open",
                                       inputFile,
                                        false,
                                        true
                                        ).toDispatch();
            //调用Document对象的SaveAs方法,将文档保存为pdf格式
            /*
           Dispatch.call(doc,
                       "SaveAs",
                       pdfFile,
                       wdFormatPDF     //word保存为pdf格式宏,值为17
                       );
                       */
           Dispatch.call(doc,
                   "ExportAsFixedFormat",
                   pdfFile,
                   wdFormatPDF     //word保存为pdf格式宏,值为17
                   );
            //关闭文档
           Dispatch.call(doc, "Close",false);
            //关闭word应用程序
           app.invoke("Quit", 0);
            returntrue;
       }catch(Exception e){
            returnfalse;
        }
        }
       /**
       *excel转换的时候如果有多个工作簿或者数据量太大的时候转换还是存在问题的
       *
       */
        publicstatic boolean excel2PDF(String inputFile,String pdfFile){
            try{
               ActiveXComponent app = newActiveXComponent("Excel.Application");
           app.setProperty("Visible", false);
           Dispatch excels = app.getProperty("Workbooks").toDispatch();
           Dispatch excel = Dispatch.call(excels,
                                       "Open",
                                       inputFile,
                                        false,
                                        true
                                       ).toDispatch();
           Dispatch.call(excel,
                       "ExportAsFixedFormat",
                       xlTypePDF,      
                       pdfFile
                       );
           Dispatch.call(excel, "Close",false);
           app.invoke("Quit");
            returntrue;
       }catch(Exception e){
            returnfalse;
        }
            
        }
        public static boolean ppt2PDF(StringinputFile,String pdfFile){
            try{
           ActiveXComponent app = newActiveXComponent("PowerPoint.Application");
           //app.setProperty("Visible", msofalse);
           Dispatch ppts = app.getProperty("Presentations").toDispatch();
            
           Dispatch ppt = Dispatch.call(ppts,
                                       "Open",
                                       inputFile,
                                       true,//ReadOnly
                                       true,//Untitled指定文件是否有标题
                                       false//WithWindow指定文件是否可见
                                       ).toDispatch();
            
           Dispatch.call(ppt,
                       "SaveAs",
                       pdfFile,
                       ppSaveAsPDF
                       );
                  
           Dispatch.call(ppt, "Close");
            
           app.invoke("Quit");
            returntrue;
            }catch(Exceptione){
               return false;
            }
        }
        
   
       /******************************************* 图片转pdf *****************************************/
        privatestatic void handleText(PdfWriter writer, String content, String color,
               float x, float y, float z) {
           PdfContentByte canvas = writer.getDirectContent();
           Phrase phrase = new Phrase(content);
           if (color != null) {
               phrase = new Phrase(content, FontFactory.getFont(
                       FontFactory.COURIER, 12,Font.NORMAL, new Color(255, 0, 0)));
           }
           ColumnText.showTextAligned(canvas, Element.ALIGN_UNDEFINED,phrase, x,
                   y, z);
        }
       public static Boolean img2PDF(String imagePath, StringmOutputPdfFileName) {
           Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
           try {
               PdfWriter writer = PdfWriter.getInstance(doc, newFileOutputStream(
                       mOutputPdfFileName));
               doc.open();
               doc.newPage();
               Image png1 = Image.getInstance(imagePath);
               float heigth = png1.getHeight();
               float width = png1.getWidth();
                intpercent = getPercent2(heigth, width);
               png1.setAlignment(Image.MIDDLE);
               png1.setAlignment(Image.TEXTWRAP);
               png1.scalePercent(percent + 3);
               doc.add(png1);
               handleText(writer, "This is a test","red", 400, 725, 0);
               doc.close();
           } catch (FileNotFoundException e){
               e.printStackTrace();
           } catch (DocumentException e) {
               e.printStackTrace();
            } catch (IOException e) {
               e.printStackTrace();
           }
           File mOutputPdfFile = new File(mOutputPdfFileName);
           if (!mOutputPdfFile.exists()) {
               mOutputPdfFile.deleteOnExit();
               return false;
           }
           return true;
        }
       public int getPercent1(float h, float w) {
           int p = 0;
           float p2 = 0.0f;
           if (h > w) {
               p2 = 297 / h * 100;
           } else {
               p2 = 210 / w * 100;
           }
           p = Math.round(p2);
           return p;
        }
       private static int getPercent2(float h, float w) {
           int p = 0;
           float p2 = 0.0f;
           p2 = 530 / w * 100;
           p = Math.round(p2);
           return p;
        }
      /**
      * 测试方法
      */
        publicstatic void main(String[] args) {
           Office2PDFUtil office2pdf = new Office2PDFUtil();
           office2pdf.convert2PDF("C:/Users/cheryl/Desktop/视屏/g.txt", "C:/Users/cheryl/Desktop/视屏/g_" + new Date().getTime() + ".pdf" );
        }
        
}

四、在普通的action中的使用
  
//注意srcfilePath,与destFilePath 都是文件在硬盘中的绝对位置
  
convertResult = Office2PDFUtil.convert2PDF(srcfilePath,  destFilePath);
  
  

五、使用到的相关知识

  • 使用jacob处理office文档
  • 使用iText处理     转换之后的pdf文件

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马