aspose实现word,excel在线预览

aspose实现word,excel在线预览

一,项目中引入aspose依赖

		<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
        </dependency>

        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
        </dependency>

建议将jar包下载下来并上传到自己公司的私服里
资源文末获取!

二:把license.xml放入项目中

在x这里插入图片描述结构如上图

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for Java</Product>
      <Product>Aspose.Words for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>20991231</SubscriptionExpiry>
    <LicenseExpiry>20991231</LicenseExpiry>
    <SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>
  </Data>
  <Signature>0nRuwNEddXwLfXB7pw66G71MS93gW8mNzJ7vuh3Sf4VAEOBfpxtHLCotymv1PoeukxYe31K441Ivq0Pkvx1yZZG4O1KCv3Omdbs7uqzUB4xXHlOub4VsTODzDJ5MWHqlRCB1HHcGjlyT2sVGiovLt0Grvqw5+QXBuinoBY0suX0=</Signature>
</License>

word,excel转pdf可共用一个license.xml

三.封装工具类

import com.alibaba.excel.EasyExcel;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;



@Slf4j
@Component
public class FileUtil {
   

    /**
     * 文件下载方法
     *
     * @param filename 文件保存名
     * @param filePath 文件下载路径
     * @param res
     * @throws IOException
     */
    public static void downloadFile(String filename, String filePath, HttpServletResponse res) throws IOException {
        // 发送给客户端的数据
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取filename
        bis = new BufferedInputStream(new FileInputStream(new File(filePath + filename)));
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        outputStream.close();
    }

    public static void deleteFile(String filename, String filePath) {
        File file = new File(filePath + filename);
        if (file.exists()) {//文件是否存在
            file.delete();//删除文件
        }
    }


    

    /**
     * @Author WXK
     * @Description 返回预览pdf流
     * @Date 2021/3/11
     **/
    public static void previewFile1(String filePath, HttpServletResponse res) throws IOException {
        // 发送给客户端的数据
        OutputStream outputStream = res.getOutputStream();
        try {
            byte[] buff = new byte[1024];
            BufferedInputStream bis = null;
            // 读取filename
            bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
            int i = bis.read(buff);
            while (i != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
        }


    }

    /**
     * @Author WXK
     * @Description 删除转换生成的pdf文件
     * @Date 2021/3/11
     **/
    public static void deleteFile1(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {//文件是否存在
            file.delete();//删除文件
        }
    }


    


   

    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = Test.class.getClassLoader().getResourceAsStream("license.xml"); //  
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean getExcelLicense() {
        boolean result = false;
        try {
            InputStream is = Test.class.getClassLoader().getResourceAsStream("license.xml"); //  
            com.aspose.cells.License license = new com.aspose.cells.License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @Author WXK
     * @Description word转 pdf
     * @Date 2021/3/12
     **/
    public static String doc2pdf(String fileName, String filePath) {

        if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        try {
            String oldFile = filePath + fileName;
            String newFile = oldFile.substring(0, oldFile.lastIndexOf("."))+".pdf";

            File file = new File(newFile);  //新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(oldFile);                    //Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            log.info("转换成功");  //转化用时
            return newFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @Author WXK
     * @Description 上传文件时,word转pdf 保存在本地
     * @Date 2021/3/29  
     **/
    public static String doc2pdf(InputStream inputStream,String fileName, String filePath) {

        if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        try {
            String newFile = filePath + fileName;

            File file = new File(newFile);  //新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inputStream);                    //Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            log.info("转换成功");  //转化用时
            return newFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * @Author WXK
     * @Description excel转pdf
     * @Date 2021/3/22
     **/
    public static String excelToPdf(String fileName, String filePath) throws IOException{

        if (!getExcelLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        FileOutputStream fileOS=null;
        try {
            String oldFile = filePath + fileName;
            String newFile = oldFile.substring(0, oldFile.lastIndexOf("."))+".pdf";
            File pdfFile = new File(newFile);// 输出路径
           /* Workbook wb = new Workbook(oldFile);// 原始excel路径
             fileOS = new FileOutputStream(pdfFile);
            wb.save(fileOS, SaveFormat.PDF);
            fileOS.flush();

            log.info("转换成功");*/

            Workbook wb = new Workbook(oldFile);// 原始excel路径
            

             fileOS = new FileOutputStream(newFile);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);


            int[] autoDrawSheets={3};
            //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
            autoDraw(wb,autoDrawSheets);

            int[] showSheets={0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb,showSheets);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            log.info("完毕");
            return newFile;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            fileOS.close();
        }
        return null;
    }


    /**
     * @Author WXK
     * @Description 上传文件时 excel转pdf保存在本地
     * @Date 2021/3/29  
     **/
    public static String excelToPdf(InputStream inputStream, String fileName,String filePath) throws IOException{

        if (!getExcelLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        FileOutputStream fileOS=null;
        try {
            String newFile = filePath + fileName;
            
            Workbook wb = new Workbook(inputStream);// 原始excel路径


            fileOS = new FileOutputStream(newFile);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);


            int[] autoDrawSheets={3};
            //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
            autoDraw(wb,autoDrawSheets);

            int[] showSheets={0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb,showSheets);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            log.info("完毕");
            return newFile;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            fileOS.close();
        }
        return null;
    }

    /**
     * 设置打印的sheet 自动拉伸比例
     * @param wb
     * @param page 自动拉伸的页的sheet数组
     */
    public static void autoDraw(Workbook wb,int[] page){
        if(null!=page&&page.length>0){
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }


    /**
     * 隐藏workbook中不需要的sheet页。
     * @param wb
     * @param page 显示页的sheet数组
     */
    public static void printSheetPage(Workbook wb,int[] page){
        for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if(null==page||page.length==0){
            wb.getWorksheets().get(0).setVisible(true);
        }else{
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }







    /**
     * @Author WXK
     * @Description 查看对应的.pdf文件是否存在
     * @Date 2021/3/12
     **/
    public static boolean checkFileExist(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {//文件是否存在
            return true;
        }
        return false;
    }
}

四:controller类

import com.shuangjia.constant.Constant;
import com.shuangjia.model.PeDownloadLog;
import com.shuangjia.model.PeFile;
import com.shuangjia.model.ResultEntity;
import com.shuangjia.model.UserSession;
import com.shuangjia.util.FileUtil;
import com.shuangjia.web.pepd.feginService.PeFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
public class PeFileController {
	@Value("${upload.path}")
    private  String path;

    @Value("${upload.picture.path}")
    private  String uploadPath;


 @PostMapping("/previewFile")
    @ApiOperation("返回文件流")
    public void previewFile(@RequestBody PeFile po,HttpServletResponse response)throws IOException{
        String fileName=po.getFileName();

        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if("pdf".equalsIgnoreCase(suffix)){
            String type = new MimetypesFileTypeMap().getContentType(fileName);
            response.setHeader("Content-type",type);
            String newFileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
            // 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
            response.setHeader("Content-Disposition", "attachment;filename=" + newFileName);
            FileUtil.downloadFile(fileName,path,response);

        }

        String filePath = path + fileName.substring(0,fileName.lastIndexOf(".")) + ".pdf";
        if( FileUtil.checkFileExist(filePath)){
            FileUtil.previewFile1(filePath,response);
        }else {
            String newFilePath=null;
            if("XLSX".equalsIgnoreCase(suffix) || "XLS".equalsIgnoreCase(suffix)){
                newFilePath=FileUtil.excelToPdf(fileName,path);
            }else {
                //DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF
                newFilePath = FileUtil.doc2pdf(fileName, path);
            }

         
            if(StringUtils.isNotBlank(newFilePath)){
                FileUtil.previewFile1(newFilePath,response);
            }
        }



    }



}

返回给前端的是一个pdf文件流
五:效果图
word预览图

在这里插入图片描述
关注公众号 【川蜀程序猿】,Java面经、精品书籍、Spring全家桶、超多简历模板任你选择!
海量简历模板
在这里插入图片描述

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值