office轉pdf和圖片實現線上預覽

linjiaqingggg發表於2017-01-19

jar包和openoffice的下載

最好都到官網下載或者sourceforge下載,不要在csdn或者其他的地方下載,因為很多都被人重新打包過導致各種問題。
- pdfbox的下載地址
只需要pdfbox-1.8.13.jar,fontbox-1.8.13.jar,用來pdf轉圖片
- openoffice的下載地址
- commons-loging.jar的下載(你如果下載過poi,你會發現裡面也有)
- JODConverter的下載地址
用來連線openoffice

開啟openoffice

2.啟動OpenOffice的服務

安裝完openoffice,安裝服務

cd C:\Program Files (x86)\OpenOffice 4\program

執行

soffice -headless -accept=”socket,host=127.0.0.1,port=8100;urp;” -nofirststartwizard

檢視是否安裝成功,檢視埠對應的pid

netstat -ano|findstr "8100"

檢視pid對應的服務程式名

tasklist|findstr "pid值"

若有對於值,說明服務啟動成功

程式碼

(我的程式碼都是針對於專案的doc資料夾下面的檔案,如果要直接用,需要新建一個doc資料夾,並把檔案放在下面,若要換成其他路徑,需要修改tmpDir)
附該程式碼專案的下載地址

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.io.FilenameUtils;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.rendering.PDFRenderer;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.sun.star.io.ConnectException;

public class MyOfficeImage {
     //臨時儲存目錄
     public static final String tmpDir = "doc/";
     //pdf轉圖片
     public static void pdf2Img(String pdfPath)  
     {  

        File file = new File(pdfPath);
        if ( !file.exists() )
        {
            return;
        }

        String imgName = pdfPath.substring(pdfPath.lastIndexOf("/"), pdfPath.lastIndexOf(".")) + ".png";

        PDDocument doc = null;
        List<BufferedImage> list = new ArrayList<BufferedImage>();
        int heights = 0;
        try {
            doc = PDDocument.load(file);
            PDFRenderer render = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for(int i = 0; i < pageCount; i++)
            {
                BufferedImage image = render.renderImage(i);
                list.add(image);
                heights += image.getHeight();
                //下面這一句可以轉成多張圖片
                //ImageIO.write(image, "PNG", new File("doc/"+dir[0]+"/"+i+".png"));
            }

            imgs2img(list, tmpDir + imgName, heights);

        } catch (InvalidPasswordException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        finally
        {
            if (doc != null) 
            {
                try {
                    doc.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
     }  

     /*
      * 不建議這樣子的寫法,因為用了太多臨時變數,沒必要
      */
     @Deprecated
     public static void imgs2imgold(List<BufferedImage> list, String imgpath)
     {
         int imgCount = list.size();
         List<int[]> imgRgb = new ArrayList<int[]>();  //總資料
         int[] tmpImgRgb;
         int height = 0;   //總高度
         int width = 0;
         int tmpHeight = 0;  //當前偏移高度
         int[] heightArray = new int[imgCount];
         BufferedImage buffer = null;
         for(int i = 0; i < imgCount; i++)
         {
             buffer = list.get(i);
             heightArray[i] = buffer.getHeight();

             if (i == 0) width = buffer.getWidth();
             height += heightArray[i];   

             tmpImgRgb = new int[width * heightArray[i]];
             tmpImgRgb = buffer.getRGB(0, 0, width, heightArray[i], tmpImgRgb, 0, width);
             imgRgb.add(tmpImgRgb);
         }

         BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
         for (int i = 0; i < imgCount; i++)
         {
             if (i != 0) tmpHeight += heightArray[i];
             imageResult.setRGB(0, tmpHeight, width, heightArray[i], imgRgb.get(i), 0, width);
         }
         try {
            ImageIO.write(imageResult, "PNG", new File(imgpath));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }

     //多張圖合成一張
     public static void imgs2img(List<BufferedImage> list, String imgpath, int heights)
     {
         //heights;//總高度
         int imgCount = list.size();                   //總圖片數
         int[] tmpImgRgb;                              //臨時儲存圖片的臨時畫素值
         int width = list.get(0).getWidth();           //圖片的寬度,這裡預設所以圖片的寬度是一樣的
         int tmpHeight = 0;                            //當前偏移高度
         BufferedImage buffer = null;                  //用來臨時儲存圖片
         //用來儲存最後那張總的圖片
         BufferedImage imageResult = new BufferedImage(width, heights, BufferedImage.TYPE_INT_RGB);

         for(int i = 0; i < imgCount; i++)
         {
             buffer = list.get(i);
             if (i != 0) tmpHeight += buffer.getHeight();

             tmpImgRgb = new int[width * buffer.getHeight()];
             tmpImgRgb = buffer.getRGB(0, 0, width, buffer.getHeight(), tmpImgRgb, 0, width);

             imageResult.setRGB(0, tmpHeight, width, buffer.getHeight(), tmpImgRgb, 0, width);
         }

         try 
         {
            ImageIO.write(imageResult, "PNG", new File(imgpath));
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
     }
     //office轉pdf
      public static String office2Pdf(String officePath)
      {  
            File inputfile = new File(officePath);
            File outputFile = null;
            if ( !inputfile.exists() )
            {
                return null;
            }

            String outPdf = tmpDir + officePath.substring(officePath.lastIndexOf('/'), officePath.lastIndexOf('.'))
                         + ".pdf";

            try {  
                // 如果目標路徑不存在, 則新建該路徑  
                outputFile = new File(outPdf);  
                // connect to an OpenOffice.org instance running on port 8100  
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(  
                        "127.0.0.1", 8100);  
                connection.connect();  
                // convert  
                DocumentConverter converter = new OpenOfficeDocumentConverter(  
                        connection);  
                converter.convert(inputfile, outputFile);  
                // close the connection  
                connection.disconnect();  
            } catch (IOException e) {  
                e.printStackTrace(); 
                return null;  
            }  
            //return outputFile.getAbsolutePath();  
            return outPdf;

        }   


      public static void office2Imag(String docPath)
      {  
               String pdfPath = office2Pdf(docPath);
               pdf2Img(pdfPath);   
      }  

      public static void main(String[] args)
      {
            // pdf2Img("doc/a.pdf");
            // pdf2Img("doc/基於交通視訊的運動目標檢測和跟蹤.pdf");
             //office2Imags("doc/自動化畢業論文開題報告範文.docx");
             office2Imag("doc/決算收支.xls");
      }

}

相關文章