office文件转pdf在线预览

一、工具类

package com.sby.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Locale;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;



/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cqwuliu
 * @Date: 2024/02/08/11:41  will_isme@163.com
 * @Description:
 */
public class AsposeUtil {
   
    /**
     * 获取license
     *
     * @return
     */
    public static boolean getLicense(int type) {
   
        boolean result = false;
        try {
   
            InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            if (type == 1) {
   //excel
                com.aspose.cells.License aposeLic = new com.aspose.cells.License();
                aposeLic.setLicense(is);
                result = true;
            } else if (type == 2) {
   //word
                com.aspose.words.License aposeLic = new com.aspose.words.License();
                aposeLic.setLicense(is);
                result = true;
            } else {
   //ppt
                com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                aposeLic.setLicense(is);
                result = true;
            }
        } catch (Exception e) {
   
            e.printStackTrace();
        }
        return result;
    }

    public static String Excel2Pdf(String officePath,String OutPutPath,String officeName) {
   
        // 验证License
        if (!getLicense(1)) {
   
            return null;
        }
        try {
   
            File file = new File(OutPutPath);
            if (!file.exists()) {
   
                file.mkdirs();
            }
//            long old = Sysout.currentTimeMillis();
            Workbook wb = new Workbook(officePath);// 原始excel路径
            File pdfFile = new File(OutPutPath+officeName);// 输出路径
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            wb.save(fileOS, pdfSaveOptions);

            return pdfFile.getAbsolutePath();
//            long now = Sysout.currentTimeMillis();
//            Sysout.println("共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
   
            e.printStackTrace();
            System.err.println("Excel2Pdf转换pdf错误");
        }
        return null;
    }

    public static String Word2Pdf(String officePath,String OutPutPath,String officeName) {
   
        // 验证License
        if (!getLicense(2)) {
   
            return null;
        }
        try {
   
            File file = new File(OutPutPath);
            if (!file.exists()) {
   
                file.mkdirs();
            }
            Document doc = new Document(officePath);// 原始word路径
            File pdfFile = new File(OutPutPath+officeName);// 输出路径
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
             doc.save(fileOS, SaveFormat.PDF);
            return pdfFile.getAbsolutePath();

        } catch (Exception e) {
   
            e.printStackTrace();
            System.err.println("word转换pdf错误");
        }
        return null;
    }

    public static String PPT2Pdf(String officePath,String OutPutPath,String officeName) {
   
        // 验证License
        if (!getLicense(3)) {
   
            return null;
        }
        try {
   
            File PathFile = new File(OutPutPath);
            if (!PathFile.exists()) {
   
                PathFile.mkdirs();
            }
            InputStream slides = new FileInputStream(new File(officePath));// 原始ppt路径
            Presentation pres = new Presentation(slides);
            File file = new File(OutPutPath+officeName);// 输出pdf路径
            FileOutputStream fileOS = new FileOutputStream(file);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);

            return file.getAbsolutePath();
        } catch (Exception e) {
   
            e.printStackTrace();
            System.err.println("ppt转换pdf错误");
        }
        return null;
    }

    /**
     * fileTyle.equals(".DOCX") || fileTyle.equals(".DOC") || fileTyle.equals(".PPT") || fileTyle.equals(".PPTX") || fileTyle.equals(".XLS") || fileTyle.equals(".XLSX")
     * @param officePath
     * @return 返回转换以后的pdf文件路径
     */
    public static String OfficeToPdf(String officePath) {
   

        //G:/product/WebApp/fwis_develop/com/is/flywings/oa/attchfile/1000000000/i0002/101951.docx⌒101951.docx⌒feiyu.docx
        String[] split = officePath.split("⌒");
        int lastIndex = split[0].lastIndexOf(".");
        int lastNameIndex = split[0].lastIndexOf("\\");

        String officeType = split[0].substring(lastIndex+1).toLowerCase(Locale.ROOT);
        String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";
        String OutPutPath = split[0].substring(0,lastNameIndex+1)+"topdf/";

        File file = new File(split[0]);
        File pdfFile = new File(OutPutPath+officeName);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if(pdfFile.exists()){
   
            return OutPutPath+officeName;
        }

        if (file.exists()) {
   

            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);

            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String MB = df.format(megabytes);
            Double Size = Double.parseDouble(MB);
            if(Size>30){
   
                return Size+"MB";
            }
            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
            try {
   
                if(officeType.equals("doc")||officeType.equals("docx")){
   
                  return   Word2Pdf(split[0],OutPutPath,officeName);
                }else if(officeType.equals("xls")||officeType.equals("xlsx")){
   
                    return   Excel2Pdf(split[0],OutPutPath,officeName);
                }else if(officeType.equals("ppt")||officeType.equals("pptx")){
   
                    return   PPT2Pdf(split[0],OutPutPath,officeName);
                }else{
   

                    System.err.println("无法识别该文件");
                    return "Error";
                }
            } catch (Exception e) {
   
                e.printStackTrace();
            }
        } else {
   
            return "NotExists";
        }
        return OutPutPath+officeName;
    }

   // public static void main(String[] args) {
   
      //  OfficeToPdf("C:\\Users\\DELL\\Desktop\\桌面表格文件\\2020年沙坪坝维护.xlsx");

   // }

}

相关jar包在我的资源里面下载

调用方法将不同文件类型分类处理后发送到前端预览,不在分类中的直接发送文件下载。

 public void previewFile(Integer id, HttpServletResponse response) throws IOException {
   
        FileInfo files = fileMapper.getFilesById(id);
        String filePate = dir + "\\" + files.getAliasName();
        String fileName = files.getAliasName();
        String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length()).toUpperCase();

        FileInputStream fileInputStream = new FileInputStream(filePate);
        int available = fileInputStream.available();
        if (available>(1024*1024*readonline) || fileTyle.equals(".DOCX") || fileTyle.equals(".DOC") || fileTyle.equals(".PPT") || fileTyle.equals(".PPTX") || fileTyle.equals(".XLS") || fileTyle.equals(".XLSX")) {
   


           try{
   
               //将office转换成pdf "预览";
               fileInputStream = new FileInputStream(AsposeUtil.OfficeToPdf(filePate));
               IOUtils.copy(fileInputStream, response.getOutputStream());
               return;
           }catch (Exception e){
   
               log.error("officez转换pdf预览失败"+filePate);
               System.err.println("officez转换pdf预览失败");
           }
            String filename = files.getFileName();
            filename = java.net.URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } else if (!fileTyle.equals(".PNG") && !fileTyle.equals(".JPG") && !fileTyle.equals(".JPEG") && !fileTyle.equals(".PDF")) {
   
            BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
   
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write(line);
                response.getWriter().write("<br/>");
            }
        } else {
   

            IOUtils.copy(fileInputStream, response.getOutputStream());
        }
    }





























     <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose.slides</artifactId>
            <version>15.9.0</version>
            <scope>system</scope>
            <systemPath>${
   basedir}/lib/aspose.slides-15.9.0.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose.cells.java</artifactId>
            <version>18.11</version>
            <scope>system</scope>
            <systemPath>${
   basedir}/lib/aspose-cells-java-18.11.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose.words</artifactId>
            <version>15.8.0</version>
            <scope>system</scope>
            <systemPath>${
   basedir}/lib/aspose-words-15.8.0.jar</systemPath>
        </dependency>

相关推荐

  1. office文件pdf线

    2024-02-09 11:06:03       37 阅读
  2. word、excel、ppt文件office线

    2024-02-09 11:06:03       37 阅读
  3. pdf html 线和查询

    2024-02-09 11:06:03       51 阅读
  4. vue线excel、pdf、word文件

    2024-02-09 11:06:03       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-09 11:06:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-09 11:06:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-09 11:06:03       82 阅读
  4. Python语言-面向对象

    2024-02-09 11:06:03       91 阅读

热门阅读

  1. LeetCode魔塔游戏

    2024-02-09 11:06:03       48 阅读
  2. SQL面试题挑战15:sql实现分钟级的趋势图

    2024-02-09 11:06:03       54 阅读
  3. Debezium发布历史117

    2024-02-09 11:06:03       46 阅读
  4. Android studio 六大基本布局详解

    2024-02-09 11:06:03       48 阅读
  5. Acwing143最大异或对

    2024-02-09 11:06:03       48 阅读
  6. Vivado用ILA抓波形保存为CSV文件

    2024-02-09 11:06:03       48 阅读