java实现文档转换为pdf预览

1.在项目中有这样的需求就是,对一些word、excel、ppt文档进行预览,但是这个无法直接预览,这边可以实现这么个思路,就是先将这些文件转换为pdf然后就可以预览了

2.基于以上思路这边将工具类的逻辑梳理一下:首先maven需要导入的依赖如下:由于这个jar包导不进来就本地导进去了,有兴趣的朋友可以讨论下,我这个包就是导不进去,去maven官网写对应的版本也没用,暂时这样写大佬勿喷;

lib包在这里下载

链接:https://pan.baidu.com/s/1m2LcUWO5lNDrG2-2Uq_UGQ
提取码:6gxr

      <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>18.6</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-words-18.6-jdk16.jar</systemPath>
        </dependency>
        <!-- ppt转pdf -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-slides</artifactId>
            <version>15.9.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-slides-15.9.0.jar</systemPath>
        </dependency>
        <!-- excel转pdf -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
        </dependency>

 

本地的jar放再跟src同一级别下:

 

 

 然后就是工具类的梳理了:就不多说直接上代码可以自己测试看看:

package file;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

class FileTransForUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileTransForUtils.class);
    //word转PDF
    public synchronized static boolean word3Pdf(String wordPath, String pdfPath) {
        if (!getLicense("word")) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(pdfPath);  //新建一个pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(wordPath);  //Address是将要被转化的word文档

            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,

            // XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            os.close();
            logger.info("word共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }
    }
    //excel转PDF
    public synchronized static boolean excel3pdf(String excelPath, String pdfPath) {
        if (!getLicense("excel")) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        try {
            long old = System.currentTimeMillis();
            File pdfFile = new File(pdfPath);  //新建一个pdf文档
            FileOutputStream os = new FileOutputStream(pdfFile);
            Workbook wb = new Workbook(excelPath);// 原始excel路径
            wb.save(os,com.aspose.cells.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            os.close();
            logger.info("excel共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }
    }
    //ppt转PDF
    public synchronized static boolean ppt3pdf(String pptPath, String pdfPath) {
        // 验证License
        if (!getLicense("ppt")) {
            return false;
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            File pdfFile = new File(pdfPath);  //新建一个pdf文档
            os = new FileOutputStream(pdfFile);
            Presentation pres = new Presentation(pptPath);//输入ppt路径
            //IFontsManager fontsManager = pres.getFontsManager();
            pres.save(os,com.aspose.slides.SaveFormat.Pdf);
            long now = System.currentTimeMillis();
            logger.info("ppt共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //剔除水印
    private static boolean getLicense(String type) {
        boolean result = false;
        try {
            // 凭证
            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"));
            if(type.equals("word")){
                License asposeLic = new License();
                asposeLic.setLicense(is);
            }else if (type.equals("excel")){
                com.aspose.cells.License asposeLic = new com.aspose.cells.License();
                asposeLic.setLicense(is);
            }else if (type.equals("ppt")){
                com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                aposeLic.setLicense(is);
            }
            result = true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }
        return result;
    }
    /**
     * 判断资源类型文档类
     */
    private static String getResourceTypesDocument(String suffix) {
        String type = null;
        switch (suffix) {
            //文档类型
            case ".doc":
            case ".docx":
            case ".txt":
                type = "word";
                break;
            case ".xls":
            case ".xlsx":
                type = "excel";
                break;
            case ".ppt":
            case ".pptx":
                type = "ppt";
                break;
        }
        return type;
    }

    public static void main(String[] args) {
        String inputPath = "E:/test/测试.xlsx";
        String outputPath = "E:/test/11.pdf";
        String suffix = inputPath.substring(inputPath.lastIndexOf("."));
        String type = getResourceTypesDocument(suffix);
        if("word".equals(type)){
            word3Pdf(inputPath,outputPath);
        }else if("excel".equals(type)){
            excel3pdf(inputPath,outputPath);
        }else if("ppt".equals(type)){
            ppt3pdf(inputPath,outputPath);
        }
    }
}

 

 

 目前支持doc、docx、txt、xls、xlsx、ppt以及pptx转换为pdf其他格式可能需要调整下有深入研究的大佬欢迎骚扰:以上功能自测是完全没有问题的,目前研究应该都是皮毛很多深入的还待研究

下一篇文章将介绍音频的转换为MP4格式,便于前端能预览视频

posted @ 2021-09-27 17:43  执着的你  阅读(3537)  评论(1编辑  收藏  举报