aspose实现文件转换pdf实现WEB文件预览

项目需求

上传文件需要实现下载、浏览器直接预览。主要预览文件为图片格式、word、excel

处理思路

  1. 浏览器本身支持图片格式,这里几乎不需要处理
  2. 处理word、excel比较麻烦,浏览器不支持,那么只能转化成浏览器支持格式,如:图片、pdf、html

实现

辗转各种搜索博客,最后选择aspose实现转换pdf。

引入aspose-words、aspose-cell包

我是加入的本地仓库,进入到jar目录命令如下

mvn install:install-file -Dfile=aspose-words-16.8.0.jar -DgroupId=com.aspose -DartifactId=aspose-words -Dversion=16.8.0 -Dpackaging=jar
mvn install:install-file -Dfile=aspose-cells-18.9.jar -DgroupId=com.aspose -DartifactId=aspose-cells -Dversion=18.9 -Dpackaging=jar

引入jar包

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>16.8.0</version>
</dependency>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-cells</artifactId>
    <version>18.9</version>
</dependency>

添加license.xml到resources下,这里因为使用的两个,license.xml为word的,licenseCell.xml为cell的,看工具类代码

编写工具类PdfUtil.java

package com.tianque.util;


import com.aspose.cells.Workbook;
import com.aspose.cells.WorksheetCollection;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * pdf工具
 *
 * @author LiRui
 * @version 1.0
 */
public class PdfUtils {
    private PdfUtils() {
    }

    private static final List<String> DOC_LIST = new ArrayList<>();
    private static final List<String> CELL_LIST = new ArrayList<>();

    static {
        DOC_LIST.add(".doc");
        DOC_LIST.add(".docx");
        DOC_LIST.add(".pdf");
        CELL_LIST.add(".xlsx");
        CELL_LIST.add(".xls");
    }

    private static final boolean DOC_LICENCE = getDocLicense();
    private static final boolean CELL_LICENCE = getCellLicense();

    public static boolean getDocLicense() {
        boolean result = false;
        try {
            // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = PdfUtils.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            assert is != null;
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean getCellLicense() {
        boolean result = false;
        try {
            // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = PdfUtils.class.getClassLoader().getResourceAsStream("licenseCell.xml");
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            assert is != null;
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * doc转pdf
     *
     * @param inPath
     * @param os
     */
    public static void toPdf(String inPath, OutputStream os) {
        final String type = inPath.substring(inPath.lastIndexOf(".")).toLowerCase();
        if (DOC_LIST.contains(type)) {
            docToPdf(inPath, os);
        }
        if (CELL_LIST.contains(type)) {
            excelToPdf(inPath, os);
        }
    }

    /**
     * doc转pdf
     *
     * @param inPath
     * @param os
     */
    public static void docToPdf(String inPath, OutputStream os) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!DOC_LICENCE) {
            return;
        }
        try {
            Document doc = new Document(inPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * excel转pdf
     *
     * @param inPath
     * @param os
     */
    public static void excelToPdf(String inPath, OutputStream os) {
        if (!CELL_LICENCE) {
            return;
        }
        try {
            //注意这里使用的包为cell的包
            Workbook wb = new Workbook(inPath);
            com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            wb.save(os, com.aspose.cells.SaveFormat.PDF);
            wb.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

注意里面使用了两个aspose包,一个是转word一个是转excel的,所以excelToPdf的方法加了全名

Controller调用

/***
     * 附件预览
     *
     * @param id
     */
    @RequestMapping(value = "/preview", method = {RequestMethod.GET})
    public void preview(@RequestParam Long id, HttpServletResponse response) throws IOException {
       //获取附件信息(根据自己实际情况编写吧)
        KpiAttachment attachment = kpiObjectResultDubboService.findFileListById(id);
        if (null == attachment) {
            throw new BusinessValidationException("附件不存在,下载失败");
        }
        if (attachment.getPreview().equals((short)0)) {
            throw new BusinessValidationException("附件不支持预览");
        }
        //获取文件根路径
        String path = FileUtil.getWebRoot() + attachment.getFileActualUrl();
        String lowerCase = attachment.getFileName().toLowerCase();
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            //判断文件是pdf直接输出
            if ("pdf".equalsIgnoreCase(attachment.getExtFileName())){
                outputStream.write(FileUtils.readFileToByteArray(new File(path)));
                response.setContentType("application/pdf");
            }
            //判断是否支持转换
            if (PdfUtils.canToPdf(attachment.getFileActualUrl())) {
                PdfUtils.toPdf(path, outputStream);
                response.setContentType("application/pdf");
                return;
            }
            outputStream.write(FileUtils.readFileToByteArray(new File(path)));
            response.setContentType("image/" + lowerCase.substring(1));
        }
    }

前端代码

<a class="media" href="/kpi/kpiObjectResult/preview?id=1" target="_blank">预览</a>

由于这个是一个老项目,为jsp的这里是直接输出流进行处理。其中注意ContentType的设置,如果不是很了解http协议这个东西建议去官方看一下,查一下资料。这其实就是告诉浏览器我给你的是个啥,然后浏览器做相应的解析。

结束

实现思路还有很多,比如先把文档中的内容拿出来组装成html输出到页面成为预览。aspose转pdf主要是简单方便。

遗留问题

表格转化为pdf时没有表格线,贼难看!!!找各种博客,都是去设置源文件,感觉不好使~也不想搞了!老版本包表格转码还会乱码!我也是搞了几个版本 和产品商量了表格就不预览了!后期再处理,如哪位兄弟找到了解决方案请Call我 Thanks!

分离项目一般做法

分离项目(我这个项目老项目jsp吐槽一下)常规操作是Rest风格返回预览地址 只需要将上面的工具类调整为生成pdf到目标目录下,然后将目标目录返回给前端,前端做打开预览即可.添加以下工具代码(没测试,大概思路就这个)。生成预览临时文件记得及时清理哦

    /**
     * 转换输出文件
     *
     * @param inPath  文件目录
     * @param outPath 输出目录
     * @throws FileNotFoundException
     */
    public static void docToPdf(String inPath, String outPath) throws FileNotFoundException {
        OutputStream os = new FileOutputStream(outPath);
        docToPdf(inPath, os);
    }

aspose包

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

niubility锐

觉得有用的话鼓励鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值