java利用第三方jar實現excel,word,ppt,txt轉pdf格式

最近項目有文件模塊的上傳預覽功能,好比把word文檔上傳,之後點擊能夠預覽。採用的思路爲:文件上傳到服務器,而後獲取轉換成對應的新的PDF文件,而後讀取PDF文件。本文着重實現文檔上傳而後轉爲PDF。所需jar:   https://pan.baidu.com/s/1AKBQuD4GPxQsxFomIi-sEQ 提取碼: rzju java

文件上傳代碼:web

    public String fileUpload(HttpServletRequest request, HttpServletResponse response) {

        String saveDirectory = request.getServletContext().getRealPath("/upload");//上傳路徑
        // 將當前上下文初始化給 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());

        if (multipartResolver.isMultipart(request)) {
            // 將request變成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 獲取multiRequest 中全部的文件名
            Iterator iter = multiRequest.getFileNames();
            String extName = "";// 擴展名
            while (iter.hasNext()) {
                // 一次遍歷全部文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    try {
                        InputStream is = file.getInputStream();
               //獲取文件md5值判斷是否有重複,若是有文件就不上傳,直接讀取 String fileHashCode
= MD5Util.md5HashCode32(is); String originalFileName = file.getOriginalFilename();
               //獲取擴展名 extName
= originalFileName.substring(originalFileName.lastIndexOf(".")); //源文件上傳地址
               String sourceFilePath = saveDirectory + File.separator + fileHashCode + extName;
               //生成的目標文件地址
String destinatFilePath = request.getServletContext.getRealPath("/convert")+File.separator+fileHashCode + ".pdf";
              // 表示文件已存在不須要上傳
               if (new File(sourceFilePath).exists()) { 
                  continue;//跳出本次循環

                        } else {
                            file.transferTo(new File(path));// 生成新的文件
                            file.getInputStream().close();//流關最好在finally裏關閉 // 文件轉換工具用於轉換文件,最好新開線程,對文件較大的須要等待時間。參數(源文件路徑,目標文件路徑)
                            FileConvertUtils.convert(sourceFilePath, destinatFilePath);
                        }

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
            return "請選擇文件上傳!";
        }
        return "文件上傳請求配置錯誤!";

    }

定義函數用於判斷調用哪一個轉換函數:api

public class FileConvertUtils {
    public static final Logger log = LoggerFactory.getLogger(FileConvertUtils.class);

    public static void convert(final String sourceFilePath ,final String destFilePath){
        String fileType = sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
        ExecutorService executor = Executors.newCachedThreadPool() ;
        executor.submit(() -> {
            try {
                //要執行的業務代碼,
                  if(!"".equals(fileType)&&fileType!=null){
                      if(".doc".equals(fileType)||".docx".equals(fileType)||".wps".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".txt".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".xls".equals(fileType)||".xlsx".equals(fileType)){
                          OfficeToPdfUtils.excel2Pdf(sourceFilePath,destFilePath);
                      }else if(".ppt".equals(fileType)||".pptx".equals(fileType)){
                          OfficeToPdfUtils.ppt2Pdf(sourceFilePath,destFilePath);
                      }else if(".pdf".equals(fileType)){
                          FileUtils.copyFile(sourceFilePath, destFilePath);
                      }
                  }
            }catch(Exception e) {
                e.printStackTrace();
                throw new RuntimeException("報錯啦!!");
            }

        });

    }

   
}

 

文件轉換核心代碼:服務器

package com.hhwy.fileview.convert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aspose.cells.Workbook;
import com.aspose.pdf.SaveFormat;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.hhwy.fweb.framework.api.utils.IoTools;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.*;

public class OfficeToPdfUtils {

    /**
     * The constant LOG.
     *
     */
    private static final Logger LOG = LoggerFactory.getLogger(OfficeToPdfUtils.class);

    /**
     * 獲取license
     *
     * @return
     */
    public static boolean getWordLicense() {
        boolean result = false;
        try {
            InputStream license = new FileInputStream(new File(IoTools.getABSPATH() + "WEB-INF/license.xml"));// license路徑,這裏我引用的是公司的包獲取路徑,這邊本身能夠定義指定路徑
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static boolean getPPTLicense() {
        boolean result = false;
        try {
            InputStream license = new FileInputStream(new File(IoTools.getABSPATH() + "WEB-INF/license.xml"));// license路徑
            com.aspose.slides.License aposeLic = new com.aspose.slides.License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static boolean getExcelLicense() {
        boolean result = false;
        try {
            InputStream license = new FileInputStream(new File(IoTools.getABSPATH() + "WEB-INF/license.xml"));// license路徑
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void word2Pdf(String resourceFilePath, String destFilePath) {
        InputStream wordIn = null;
        try {
             wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        // 驗證License
        if (!getWordLicense()) {
            LOG.error("驗證License失敗!");
            return;
        }
        try {
            Document doc = new Document(wordIn);
            fileOS = new FileOutputStream(new File(destFilePath));
            // 保存轉換的pdf文件
            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }
    public static void ppt2Pdf(String resourceFilePath, String destFilePath){
        InputStream wordIn = null;
        try {
            wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        // 驗證License
        if (!getPPTLicense()) {
            LOG.error("驗證License失敗!");
            return;
        }
        try {
            fileOS = new FileOutputStream(new File(destFilePath));
            Presentation ppt = new Presentation(wordIn);
       //此處不可寫SaveFormat.Pdf,這樣轉換能生成文件,可是轉換的文件沒法打開 ppt.save(fileOS, com.aspose.slides.SaveFormat.Pdf); }
catch (Exception e) { LOG.error("error:", e); } finally { try { if(fileOS != null){ fileOS.close(); } } catch (IOException e) { LOG.error("error:", e); } } }
  
public static void word2Html(String resourceFilePath, String destFilePath) { InputStream wordIn = null; try { wordIn = new FileInputStream(new File(resourceFilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } FileOutputStream fileOS = null; // 驗證License if (!getWordLicense()) { LOG.error("驗證License失敗!"); return; } try { Document doc = new Document(wordIn); fileOS = new FileOutputStream(new File(destFilePath)); // 保存轉換的pdf文件 doc.save(fileOS, com.aspose.words.SaveFormat.HTML); } catch (Exception e) { LOG.error("error:", e); } finally { try { if(fileOS != null){ fileOS.close(); } } catch (IOException e) { LOG.error("error:", e); } } } public static void excel2Pdf(String resourceFilePath, String destFilePath){ InputStream in = null; try { in = new FileInputStream(new File(resourceFilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } FileOutputStream fileOS = null; // 驗證License if (!getExcelLicense()) { LOG.error("驗證License失敗!"); return; } try { fileOS = new FileOutputStream(new File(destFilePath)); Workbook excel = new Workbook(in); excel.save(destFilePath,com.aspose.cells.SaveFormat.PDF); } catch (Exception e) { LOG.error("error:", e); } finally { try { if(fileOS != null){ fileOS.close(); System.out.println("轉換已完成!"); } } catch (IOException e) { LOG.error("error:", e); } } }
public static void main(String[] args) { word2Pdf("/Users/workspace/docs/test.docx","/Users/workspace/docs/test.pdf"); /* InputStream pptIn = new FileInputStream(new File("/Users/workspace/docs/test.pptx")); ppt2Pdf(pptIn,"/Users/workspace/docs/test-ppt.pdf"); InputStream excelIn = new FileInputStream(new File("/Users/workspace/docs/test.xlsx")); excel2Pdf(excelIn,"D:\\aspose\\test-excel.pdf"); InputStream txtIn = new FileInputStream(new File("/Users/workspace/docs/test.txt")); word2Pdf(txtIn,"/Users/workspace/docs/test-txt.pdf");*/ } }

本在實現上還有許多須要優化的地方,好比如何得知某文件什麼時候轉換成功,文件夾,文件不存在時候的判斷等。後續優化後再更新。ide

針對沒法獲取文件什麼時候轉換成功,修改了FileConvertUtils 使其實現Callable接口,定義線程池在上傳文件外部調用該類,代碼:函數

public class FileConvertUtils implements Callable<Integer>{

    private String sourceFilePath;
    private String destFilePath;
    
    FileConvertUtils(String sourceFilePath,String destFilePath){
        this.sourceFilePath = sourceFilePath;
        this.destFilePath = destFilePath;
    }
    
    public void convert(String sourceFilePath,String destFilePath){
        String fileType = sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
            try {
                //要執行的業務代碼,
                  if(!"".equals(fileType)&&fileType!=null){
                      if(".doc".equals(fileType)||".docx".equals(fileType)||".wps".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".txt".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".xls".equals(fileType)||".xlsx".equals(fileType)){
                          OfficeToPdfUtils.excel2Pdf(sourceFilePath,destFilePath);
                      }else if(".ppt".equals(fileType)||".pptx".equals(fileType)){
                          OfficeToPdfUtils.ppt2Pdf(sourceFilePath,destFilePath);
                      }else if(".pdf".equals(fileType)){
                          FileUtils.copyFile(sourceFilePath, destFilePath);
                      }
                  }
            }catch(Exception e) {
                e.printStackTrace();
                throw new RuntimeException("報錯啦!!");
            }      

    }

    @Override
    public Integer call() throws Exception {
        this.convert(sourceFilePath, destFilePath);
        return 1;//經過future.get能夠獲取改返回值,表示執行完成
    }

調用處代碼:工具

                            ExecutorService executor = Executors.newCachedThreadPool();
                            Future<Integer> future = executor.submit(new FileConvertUtils(sourceFilePath,destinatFilePath));
                            System.out.println("=================="+future.get());//若是返回1,則調用成功,不然get方法會一直阻塞。

 

增長ppt轉圖片操做方法:優化

    /**
     * pptToImage
     * @param resourceFilePath
     * @param destFilePath
     */
    
    public static void ppt2Image(String resourceFilePath,String destFilePath){
        InputStream wordIn = null;
        try {
            wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        //驗證license
        if(!getPPTLicense()){
            LOG.error("驗證License失敗!");
            return;
        }
        try {
            Presentation ppt = new Presentation(wordIn);
            int i=0;
            for(;i<ppt.getSlides().size();i++){
                ISlide slide = ppt.getSlides().get_Item(i);
                int hight = (int) (ppt.getSlideSize().getSize().getHeight()-150);
                int width = (int) (ppt.getSlideSize().getSize().getWidth()-150);
                BufferedImage image = slide.getThumbnail(new Dimension(width,hight));
                //每頁輸出一張圖片
                File outImage = new File(destFilePath.replace(".pdf","")+i+".JPG");
                ImageIO.write(image, "JPG", outImage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
destinatFilePath 
相關文章
相關標籤/搜索