文档转PDF方式踩坑记录

335 阅读2分钟

背景说明

移动端项目中有一个附件查看的功能,主要是查看PC端使用wps生成的doc文档和手动上传的xlsx文件等,最初设想的是直接附件下载到手机端,使用手机阅读器打开文档查看。
但是客户方提出要求,这些附件有保密要求,不能下载,避免私自传播,泄露文件内容。so,只能另外再想办法
最终决定在移动端使用PDF预览的方式查看附件,于是,后端迎来了一项比较艰巨的任务——文档格式转换。

方案选型

通过网上查看各种资料,找到了一下几种文档转PDF的方案

jacob方式

由于不支持Linux系统,直接pass

aspose方式

这种方式支持跨平台,不要安装插件、文件转换的速度比较快,实现方式比较简单,但是需要收费。
网上可以找到一些破解的liscense,如果不做商业使用的话,也能尝试使用一下。

openOffice+jodConverter方式

这种方式支持跨平台,但是需要安装OpenOffice,调用转化方法前必须要启动OpenOffice,转化速度相对来说有些慢,好处是这种转化方法是完全免费的。
而且在我测试的过程中发现,openOffice支持的转换格式不如Aspose多。
最初,我希望能够支持尽可能多的文档转换格式,而且OpenOffice的方式需要运维去配合帮忙装插件,有些麻烦,这个项目使用的服务器跟主流的服务器又不太一样,也担心服务器不支持,就先采用了Aspose转换的方式。

Aspose使用

添加maven依赖

    <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose.slides</artifactId>
            <version>15.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>16.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.6</version>
        </dependency>

文档转换工具类


import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import com.aspose.words.Document;
import com.aspose.words.License;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class AsposeUtil {

    private static final Set<String> fileTypeSet = new HashSet<>();

    static {
        fileTypeSet.add("doc");
        fileTypeSet.add("docx");
        fileTypeSet.add("xls");
        fileTypeSet.add(("xlsx"));
        fileTypeSet.add("pptx");
    }

    //校验license
    private static boolean judgeLicense() {
        boolean result = false;
        try {
            InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static boolean judgeFiletype(String fileType) {
        if (fileTypeSet.contains(fileType))
            return true;
        return false;
    }

    // 转换
    public static void trans(String filePath, String pdfPath, String type) {
        if (!judgeFiletype(type)) {
            log.error("文件格式不支持:{}", type);
            return;
        }
        if (!judgeLicense()) {
            log.error("license校验失败!");
            return;
        }
        try {
            log.debug("转换开始:{}", filePath);
            long start = System.currentTimeMillis();
            File file = new File(pdfPath);
            toPdf(file, filePath, type);
            long end = System.currentTimeMillis();
            log.debug("PDF转换完成:{}", pdfPath);
            log.debug("共耗时:{}s", ((end - start) / 1000.0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void toPdf(File file, String filePath, String type) {
        if (StringUtils.equalsAnyIgnoreCase(type, "doc", "docx")) {
            wordofpdf(file, filePath);
        } else if (StringUtils.equalsAnyIgnoreCase(type, "xls", "xlsx")) {
            exceOfPdf(file, filePath);
        } else if (StringUtils.equalsAnyIgnoreCase(type, "pptx")) {
            pptofpdf(file, filePath);
        }
    }

    private static void wordofpdf(File file, String filePath) {
        FileOutputStream os = null;
        Document doc;
        try {
            os = new FileOutputStream(file);
            doc = new Document(filePath);
            doc.save(os, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void exceOfPdf(File file, String filePath) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            Workbook wb = new Workbook(filePath);
            wb.save(os, com.aspose.cells.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void pptofpdf(File file, String filePath) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            Presentation pres = new Presentation(filePath);// 输入pdf路径
            pres.save(os, SaveFormat.Pdf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

测试类

@Slf4j
public class Test {

    public static void main(String[] args) throws IOException {
        String word = "C:\\Users\\Administrator\\Desktop\\上海银行OA\\aa.xlsx";
        String wpdf = "C:\\Users\\Administrator\\Desktop\\上海银行OA\\aa.pdf";
        String fileType = FileTypeUtil.getTypeByPath(word);
        AsposeUtil.trans(word, wpdf, fileType);
    }
}

liscense文件

 我只在网上找到了一个word文件转换的liscense文件,Excel和ppt的暂时没找到
 
<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>

暂时先写到这里,后面再补充。。。。。。。。。。。。