Aspose实现word、excel、ppt转pdf

2023-11-07

1. 工具类 AsposeUtil

@Component
@Slf4j
public class AsposeUtil {

    private static final String[] WORD = {"doc", "docx", "wps", "wpt", "txt"};
    private static final String[] EXCEL = {"xls", "xlsx", "et", "xlsm"};
    private static final String[] PPT = {"ppt", "pptx"};
    private static final String[] PDF = {"pdf"};
    private static final String[] IMG = {"bmp", "jpg", "png", "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp", "avif", "apng"};

    private static final String TYPE_UNSUPPORT = "不支持的格式";
    private static final String TYPE_WORD = "TYPE_WORD";
    private static final String TYPE_EXCEL = "TYPE_EXCEL";
    private static final String TYPE_PPT = "TYPE_PPT";
    private static final String TYPE_PDF = "TYPE_PDF";
    private static final String TYPE_IMG = "TYPE_IMG";

    @Autowired
    OssUtil ossUtil;

    private boolean judgeLicense() {
        boolean result = false;
        try {
//			InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            String license =
                    "<License>\n" +
                            "  <Data>\n" +
                            "    <Products>\n" +
                            "      <Product>Aspose.Total for Java</Product>\n" +
                            "      <Product>Aspose.Words for Java</Product>\n" +
                            "    </Products>\n" +
                            "    <EditionType>Enterprise</EditionType>\n" +
                            "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                            "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
                            "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                            "  </Data>\n" +
                            "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                            "</License>";
            InputStream is = new ByteArrayInputStream(license.getBytes("UTF-8"));
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error("Aspose License Error,error:{}",e);
        }
        return result;
    }

    /**
     * 根据文件名判断文件类型
     *
     * @return
     */
    private String getType(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); // 后缀
        if (CollUtil.contains(Arrays.asList(WORD), suffix)) {
            return TYPE_WORD;
        } else if (CollUtil.contains(Arrays.asList(EXCEL), suffix)) {
            return TYPE_EXCEL;
        } else if (CollUtil.contains(Arrays.asList(PPT), suffix)) {
            return TYPE_PPT;
        } else if (CollUtil.contains(Arrays.asList(PDF), suffix)) {
            return TYPE_PDF;
        } else if (CollUtil.contains(Arrays.asList(IMG), suffix)) {
            return TYPE_IMG;
        } else {
            return TYPE_UNSUPPORT;
        }
    }

    /**
     * 文件转化pdf
     *
     * @param fileName 传入的文件名称
     * @param addr     传入的文件地址
     * @return 转换后的pdf地址 或 格式不支持预览
     */
    public String toPdf(String fileName, String addr) throws Exception {
        if (!judgeLicense()) {
            throw new BizException(BuErrorEnum.ASPOSE_LISENSE_PROBLEM.getErrCode(), BuErrorEnum.ASPOSE_LISENSE_PROBLEM.getErrMsg());
        }

        String type = getType(fileName);
        switch (type) {
            case TYPE_UNSUPPORT:
                return TYPE_UNSUPPORT;
            case TYPE_PDF:
                return addr;
            case TYPE_IMG:
                return addr;
            default:
                break;
        }

        InputStream in = URLUtil.getStream(URLUtil.url(addr)); // 下载文件
        ByteArrayOutputStream tmp = new ByteArrayOutputStream();
        switch (type) {
            case TYPE_WORD:
                tmp = wordToPdfStream(in);
                break;
            case TYPE_EXCEL:
                tmp = excelToPdfStream(in);
                break;
            case TYPE_PPT:
                tmp = pptToPdfStream(in);
                break;
            default:
                break;
        }
        PdfMultipartFile pdfMultipartFile = new PdfMultipartFile(fileName, new ByteArrayInputStream(tmp.toByteArray()));
        return ossUtil.uploadFile(pdfMultipartFile);
    }

    private ByteArrayOutputStream wordToPdfStream(InputStream in) throws Exception {
        Document doc = new Document(in);
        ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
        doc.save(dstStream, com.aspose.words.SaveFormat.PDF);
        return dstStream;
    }

    private ByteArrayOutputStream excelToPdfStream(InputStream in) throws Exception {

        Workbook excel = new Workbook (in);
        ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
        excel.save(dstStream, com.aspose.cells.SaveFormat.PDF);
        return dstStream;
    }

    private ByteArrayOutputStream pptToPdfStream(InputStream in) throws Exception {
        Presentation ppt = new Presentation (in);
        ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
        ppt.save(dstStream, SaveFormat.Pdf);
        return dstStream;
    }
}

public class PdfMultipartFile implements MultipartFile {

    private final String name;

    private final String originalFilename;

    @Nullable
    private final String contentType;

    private final byte[] content;


    public PdfMultipartFile(String name, @Nullable byte[] content) {
        this(name, "", null, content);
    }

    public PdfMultipartFile(String name, InputStream contentStream) throws IOException {
        this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));
    }

    public PdfMultipartFile(
            String name, @Nullable String originalFilename, @Nullable String contentType, @Nullable byte[] content) {

        Assert.hasLength(converName(name), "Name must not be empty");
        this.name = converName(name);
        this.originalFilename = (originalFilename != null ? originalFilename : "");
        this.contentType = contentType;
        this.content = (content != null ? content : new byte[0]);
    }


    public PdfMultipartFile(
            String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream)
            throws IOException {

        this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
    }

    private String converName(String name) {
        int index = name.lastIndexOf(".");
        if (index > 0) {
            String suffix = name.substring(index).toLowerCase();
            return name.replace(suffix, ".pdf");
        }
        return name + ".pdf";
    }


    @Override
    public String getName() {
        return this.name;
    }

    @Override
    @NonNull
    public String getOriginalFilename() {
        return this.originalFilename == null || this.originalFilename.equals("") ? this.name : this.originalFilename;
    }

    @Override
    @Nullable
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return (this.content.length == 0);
    }

    @Override
    public long getSize() {
        return this.content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return this.content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.content);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileCopyUtils.copy(this.content, dest);
    }

}

2. license文件

<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>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
    sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

3. jar包

4. 本地pom引入

<!--aspose start-->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>slides</artifactId>
            <version>15.9.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose.slides-15.9.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>aspose</groupId>
            <artifactId>cells</artifactId>
            <version>8.5.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>aspose</groupId>
            <artifactId>words</artifactId>
            <version>16.8.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-words-16.8.0-jdk16.jar</systemPath>
        </dependency>
        <!--aspose end-->

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Aspose实现word、excel、ppt转pdf 的相关文章

随机推荐

  • 【大数据】HiveQL的数据操作

    HiveQL的数据操作 因为 Hive 没有行级别的数据插入 数据更新和删除操作 那么往表中装载数据的唯一途径就是使用一种 大量 的数据装载操作 或者通过其他方式仅仅将文件写入到正确的目录下 1 向管理表中装载数据 LOAD DATA LO
  • SpringFactoriesLoader ServiceLoader区别

    内容简介 IoC 并不仅限于解决模块内类与类之间的依赖耦合问题 其同样适用于模块与模块之间 OSGi 一直致力于这方面的工作 但其实 Java 和 Spring 都提供了对 IoC 的支持 Java 本身提供了一种很简便的方式来支持 IoC
  • 报告

    来源 Prophet 2019年 战略数字化转型的重要性已经不止于IT领域 而影响着全公司的竞争力 企业的相关预算直线攀升 利益相关方所关注的颠覆性技术数量急剧增加 数字化项目开始由首席高管主导 并由相互协作的跨职能团队管理 数字化是整个企
  • 爬虫项目五:最详细的京东商品、评价爬虫、词云展示

    文章目录 前言 一 京东商品信息爬虫 1 分析URL 2 实例化chrome 3 加载完整数据 4 实现翻页 5 解析数据 二 京东商品评价爬虫 1 找到接口 2 分析url 3 解析数据 4 词云 前言 本文内容包含京东商品列表爬虫的详细
  • pycharm启动报错

    1 点击pycharm 报错 2 打开cmd 输入gpedit msc 点击 确定 3 在本地组策略编辑器 选择 Windows设置 安全设置 本地策略 安全选项 用户帐户控制 用于内置管理员帐户的管理员批准模式 4 设置 用户帐户控制 用
  • cuda历史版本和cudnn的下载地址

    cuda历史版本下载地址 https developer nvidia com cuda toolkit archive cudnn下载地址 https developer nvidia com rdp cudnn archive 欢迎大家
  • pthread_mutex_init线程互斥锁的使用

    pthread mutex init 头文件 include
  • Springboot项目中@JsonProperty不生效-如何处理呢?

    转自 Springboot项目中 JsonProperty不生效 如何处理呢 下文笔者讲述SpringBoot中 JsonProperty不生效的相关简介说明 首先笔者将讲述JsonProperty注解的功能简介说明 JsonPropert
  • googlecloud谷歌云的初学体会(1)

    googlecloud谷歌云入门 1 一 纯小白自述 二 云是个什么云 三 装一个软件 资源 服务 四 服务器 爷爷提供服务的电脑 五 PGSQL的安装 六 总结 一 纯小白自述 自己是个小白 仅仅懂得几句sql查询和编程的基础语法 云是啥
  • 第八十七题 UVa12166 Equilibrium Mobile

    A mobile is a type of kinetic sculpture constructed to take advantage of the principle of equilibrium It consists of a n
  • 傻瓜攻略(七)——MATLAB神经网络的保存和调用

    作为科研领域十分重要的计算工具 MATLAB在深度学习方面也一直与时俱进 每一个版本的更新都会引进许多新的机器学习和深度学习案例 下面介绍将训练好的网络进行保存的方法 当再次调用网络时 可以在前一次训练的基础上进一步训练或者直接处理新数据
  • NIPS 2017

    Attention is all you need Author Unit Google Brain Google Research University of Toronto Authors Ashish Vaswani Noam Sha
  • 什么副业可以月赚1万元?做什么副业可以月入上万?

    在当前经济形势下 对于一个普通上班族而言 指望工资生活 日子肯定是过得紧巴巴的 许多人想谋求一份副业收入很正常 那么 在当前社会上 有哪些副业项目 能一个月收入一万多呢 我这里给大家推荐几个 仅供用于调研参考 1 自媒体 也许很多人会说这个
  • 决策树详解(一)

    1 决策树的概念 决策树算法以树状结构表示数据分类的结果 每个决策点实现一个具有离散输出的测试函数 记为分支 决策树的元素有 根节点 非叶子节点 分支 叶节点四种元素 其代表的含义如下图所示 决策树的工作分为两个阶段 1 训练阶段 给定训练
  • 生成以太坊系地址

    代码解析 要首先生成一个新的钱包地址 我们需要导入go ethereum crypto包 该包提供用于生成随机私钥的GenerateKey方法 privateKey err crypto GenerateKey if err nil log
  • 再论KVM超量使用

    转载自 http www sohu com a 111248295 251444 KVM超量使用一直是热门话题 前段时间发的文章 群讨论 虚拟机能否使用32个CPU 又引去了群友的激烈讨论 本文为群友根据自己的经验总结投稿 感谢这位热心的群
  • 华为 ospf 报文及邻居状态有限机

    华为 IP 路由基础 ospf 报文及邻居状态有限机 ospf协议邻居建立 一 ospf的工作机制 建立邻居 发送数据库信息 计算出最短路径 hello报文 用来建立邻居和维护邻居 邻居发现 是自动发现邻居路由器 使用的组播的地址224 0
  • docker 安装

    前提 开发环境为虚拟机Ubuntu 16 04 更换国内镜像 虚拟机是刚刚安装的 需要先更换成国内镜像源 1 首先备份原始源文件 sudo cp etc apt sources list etc apt sources list bak 2
  • RS推荐系统-LSH最近邻查找+MiniHash

    什么是最近邻查找 在推荐系统中 主要分为召回跟排序两个阶段 召回阶段 基于用户画像及场景数据从海量的视频库 百万级别 中将相关度最高的资源检索出来 作为候选集 召回阶段可以通过 粗糙 的方式召回候选item 排序阶段 基于更加精细的特征对候
  • Aspose实现word、excel、ppt转pdf

    1 工具类 AsposeUtil Component Slf4j public class AsposeUtil private static final String WORD doc docx wps wpt txt private s