当前位置: 首页 > article >正文

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>

http://www.kler.cn/a/231768.html

相关文章:

  • 【windows】校园网AP隔离解决方案笔记-解决校内设备之间无法互相通信的臭毛病-附破解程序
  • SystemVerilog学习笔记(十一):接口
  • 储能技术中锂离子电池的优势和劣势
  • 基于Springboot+Vue的中国蛇类识别系统 (含源码数据库)
  • async 和 await的使用
  • 游戏引擎学习第八天
  • Redis面试题41
  • Ubuntu 命令与脚本
  • Redis核心技术与实战【学习笔记】 - 29.Redis的未来猜想,基于 NVM内存
  • GO语言笔记4-标识符、关键字与运算符
  • MySQL的DML语言
  • LeetCode Python - 1.两数之和
  • C# OMRON PLC FINS TCP协议简单测试
  • mysql入门到精通005-基础篇-约束
  • 【前端素材】bootstrap4实现绿色植物Lukani平台
  • vite项目配置根据不同的打包环境使用不同的请求路径VITE_BASE_URL,包括报错解决
  • 挑战杯 opencv 图像识别 指纹识别 - python
  • C语言:函数递归
  • 尝试gtp2go3.8解析
  • mac电脑flutter环境配置,解决疑难问题
  • 分享86个行业PPT,总有一款适合您
  • 从零开始手写mmo游戏从框架到爆炸(六)— 消息处理工厂
  • Redis核心技术与实战【学习笔记】 - 21.Redis实现分布式锁
  • 职业发展 - 一个专注于嵌入式物联网架构设计的攻城狮(转载)
  • npm 上传一个自己的应用(4) 更新自己上传到NPM中的工具版本 并进行内容修改
  • Spring IoC容器(四)容器、环境配置及附加功能