office文件转pdf在线预览

一、工具类

java 复制代码
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包在我的资源里面下载

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

java 复制代码
 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>
相关推荐
希忘auto11 分钟前
详解MySQL安装
java·mysql
冰淇淋烤布蕾22 分钟前
EasyExcel使用
java·开发语言·excel
拾荒的小海螺28 分钟前
JAVA:探索 EasyExcel 的技术指南
java·开发语言
Jakarta EE1 小时前
正确使用primefaces的process和update
java·primefaces·jakarta ee
马剑威(威哥爱编程)1 小时前
哇喔!20种单例模式的实现与变异总结
java·开发语言·单例模式
网络安全指导员1 小时前
恶意PDF文档分析记录
网络·安全·web安全·pdf
java—大象1 小时前
基于java+springboot+layui的流浪动物交流信息平台设计实现
java·开发语言·spring boot·layui·课程设计
杨哥带你写代码2 小时前
网上商城系统:Spring Boot框架的实现
java·spring boot·后端
camellias_2 小时前
SpringBoot(二十一)SpringBoot自定义CURL请求类
java·spring boot·后端
布川ku子2 小时前
[2024最新] java八股文实用版(附带原理)---Mysql篇
java·mysql·面试