在线预览(核心思想文档转成pdf,实现在线预览)

导入aspose的jar,放入到与src平级的lib包下

下载jar:

链接:https://pan.baidu.com/s/1VMI5cK36uNQeXEDhIr7hvw 
提取码:sm8z

pom文件引入jar

<dependency>
	<groupId>com.aspose</groupId>
	<artifactId>aspose-words</artifactId>
	<version>18.8</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspose-words-21.1.0-jdk17.jar</systemPath></dependency>
<dependency>
    <groupId>com.aspose</groupId>
	<artifactId>aspose-slides</artifactId>
	<version>15.9.0</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspose-slides-19.2-jdk16-crack.jar</systemPath>
</dependency>
<dependency>
	<groupId>com.aspose</groupId>
	<artifactId>aspose-cells</artifactId>
	<version>8.5.2</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspose-cells-18.9.jar</systemPath>
</dependency>
<dependency>
	<groupId>com.aspose</groupId>
	<artifactId>aspose-jweaver</artifactId>
	<version>1.8.9</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspectjweaver-1.8.9.jar</systemPath>
</dependency>
<dependency>
    <groupId>com.aspose</groupId>
	<artifactId>aspose-html</artifactId>
	<version>19.5-crack</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspose-html-19.5-crack.jar</systemPath>
</dependency>
<dependency>
	<groupId>com.aspose</groupId>
	<artifactId>aspose-gridweb</artifactId>
	<version>18.8</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspose-gridweb-18.8.jar</systemPath>
</dependency>

工具类FileUtilsPDF 调用工具类的converFile方法

public class FileUtilsPDF {
    private static Logger logger = LoggerFactory.getLogger(FileUtilsPDF.class);

    /**
     * 可用于转换的文件类型
     * xls和xlsx文件转成html,word和ppt转成pdf
     */
    private static List<String> fileType = Arrays.asList("xls", "xlsx", "doc", "docx", "ppt", "pptx");

    /**
     * 需要被Gzip压缩的Mime类型.
     */
    public static final String[] GZIP_MIME_TYPES = {"text/html", "application/xhtml+xml", "text/plain", "text/css",
            "text/javascript", "application/x-javascript", "application/json"};

    /**
     * 需要被Gzip压缩的最小文件大小.
     */
    public static final int GZIP_MINI_LENGTH = 512;

    public static MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    /**
     * 检查浏览器客户端是否支持gzip编码.
     */
    public static boolean checkAccetptGzip(HttpServletRequest request) {
        // Http1.1 header
        String acceptEncoding = request.getHeader("Accept-Encoding");

        return StringUtils.contains(acceptEncoding, "gzip");
    }

    /**
     * 设置Gzip Header并返回GZIPOutputStream.
     */
    public static OutputStream buildGzipOutputStream(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Encoding", "gzip");
        response.setHeader("Vary", "Accept-Encoding");
        return new GZIPOutputStream(response.getOutputStream());
    }

    /**
     * 创建Content基本信息.
     */
    public static ContentInfo getContentInfo(String contentPath) {
        ContentInfo contentInfo = new ContentInfo();
        File file = new File(contentPath);

        contentInfo.file = file;
        contentInfo.contentPath = contentPath;
        contentInfo.fileName = file.getName();
        contentInfo.length = (int) file.length();

        contentInfo.lastModified = file.lastModified();
        contentInfo.etag = "W/\"" + contentInfo.lastModified + "\"";

        contentInfo.mimeType = mimetypesFileTypeMap.getContentType(contentInfo.fileName);

        if ((contentInfo.length >= GZIP_MINI_LENGTH) && ArrayUtils.contains(GZIP_MIME_TYPES, contentInfo.mimeType)) {
            contentInfo.needGzip = true;
        } else {
            contentInfo.needGzip = false;
        }

        return contentInfo;
    }

    /**
     * 定义Content的基本信息.
     */
    public static class ContentInfo {
        public String contentPath;
        public File file;
        public String fileName;
        public int length;
        public String mimeType;
        public long lastModified;
        public String etag;
        public boolean needGzip;
    }

    /**
     * 根据文件名获取文件的ContentType类型
     *
     * @param filename
     * @return
     */
    public static String getFileContentType(String filename) {
        String contentType = "";
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        if (prefix.equals("xlsx")) {
            contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        } else if (prefix.equals("pdf")) {
            contentType = "application/pdf";
        } else if (prefix.equals("doc")) {
            contentType = "application/msword";
        } else if (prefix.equals("txt")) {
            contentType = "text/plain";
        } else if (prefix.equals("xls")) {
            contentType = "application/vnd.ms-excel";
        } else if (prefix.equals("docx")) {
            contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else if (prefix.equals("ppt")) {
            contentType = "application/vnd.ms-powerpoint";
        } else if (prefix.equals("pptx")) {
            contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        } else {
            contentType = "othertype";
        }

        return contentType;
    }


    // 文件复制
    public static boolean copyFile(String source, String copy) throws Exception {
        source = source.replace("\\", "/");
        copy = copy.replace("\\", "/");

        File source_file = new File(source);
        File copy_file = new File(copy);

        // BufferedStream缓冲字节流

        if (!source_file.exists()) {
            throw new IOException("文件复制失败:源文件(" + source_file + ") 不存在");
        }
        if (copy_file.isDirectory()) {
            throw new IOException("文件复制失败:复制路径(" + copy_file + ") 错误");
        }
        File parent = copy_file.getParentFile();
        // 创建复制路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        // 创建复制文件
        if (!copy_file.exists()) {
            copy_file.createNewFile();
        }

        FileInputStream fis = new FileInputStream(source_file);
        FileOutputStream fos = new FileOutputStream(copy_file);

        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] KB = new byte[1024];
        int index;
        while ((index = bis.read(KB)) != -1) {
            bos.write(KB, 0, index);
        }

        bos.close();
        bis.close();
        fos.close();
        fis.close();

        if (!copy_file.exists()) {
            return false;
        } else if (source_file.length() != copy_file.length()) {
            return false;
        } else {
            return true;
        }

    }

    // 文件重命名
    public static boolean renameFile(String url, String new_name) throws Exception {
        String old_url = url;
        old_url = old_url.replace("\\", "/");
        File old_file = new File(old_url);
        if (!old_file.exists()) {
            throw new IOException("文件重命名失败,文件(" + old_file + ")不存在");
        }

        String old_name = old_file.getName();
        // 获得父路径
        String parent = old_file.getParent();
        // 重命名
        String new_url = parent + "/" + new_name;
        File new_file = new File(new_url);
        old_file.renameTo(new_file);

        logger.info("原文件:" + old_file.getName());
        logger.info("新文件:" + new_file.getName());
        new_name = new_file.getName();
        old_name = old_file.getName();
        if (new_name.equals(old_name)) {
            return false;
        } else {
            return true;
        }

    }

    // 文件删除
    public static boolean deleteFile(String url) throws Exception {
        url = url.replace("\\", "/");
        File file = new File(url);

        if (file.isFile()) {
            if (file.exists()) {
                file.delete();
            }
        } else {
            throw new IOException("文件删除失败:(" + file + ")错误");
        }
        if (file.exists()) {
            return false;
        } else {
            return true;
        }
    }

    // 创建文件夹
    public static boolean createPath(String fileDir) throws Exception {
        fileDir = fileDir.replace("\\", "/");
        File folder = new File(fileDir);
        if (!folder.isDirectory()) {
            throw new IOException("创建文件夹失败:(" + folder + ")不是文件夹路径");
        }

        if (!folder.isFile()) {
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }
        // 检测是否创建成功
        if (folder.isDirectory() && folder.exists()) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 获取文件后缀名
     *
     * @param filename
     * @return
     */
    public static String getFileType(String filename) {
        int pos = filename.lastIndexOf(".");
        if (pos == -1) {
            return null;
        }
        return filename.substring(pos + 1);
    }

    /**
     * 获取文件名(没有后缀)
     *
     * @param filename
     * @return
     */
    public static String getFilename(String filename) {
        int pos = filename.lastIndexOf(".");
        if (pos == -1) {
            return null;
        }
        return filename.substring(0, pos);
    }

    /**
     * 检查附件中文件是否需要转换
     *
     * @param filename
     * @return
     */
    public static boolean checkFileType(String filename) {
        String type = getFileType(filename);
        if (fileType.contains(type)) {
            logger.info(filename + "需要进行文件类型转换");
            return true;
        } else {
            logger.info(filename + "无需进行文件类型转换");
            return false;
        }
    }

    /**
     * aspose words
     * 验证word的license
     *
     * @return
     */
    public static boolean getWordLicense() {
        boolean result = false;
        try {
            InputStream is = FileUtils.class.getClassLoader().getResourceAsStream("license.xml");
            License word = new License();
            word.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

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

    /**
     * aspose gridweb
     * 验证excel gridweb的license
     *
     * @return
     */
    public static boolean getGridwebLicense() {
        boolean result = false;
        try {
            InputStream is = FileUtils.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.gridweb.License license = new com.aspose.gridweb.License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * aspose slides
     * 验证ppt的license
     *
     * @return
     */
    public static boolean getPPTLicense() {
        boolean result = false;
        try {
            InputStream is = FileUtils.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.slides.License ppt = new com.aspose.slides.License();
            ppt.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * aspose slides
     * 验证html的license
     *
     * @return
     */
    public static boolean getHTMLLicense() {
        boolean result = false;
        try {
            InputStream is = FileUtils.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.html.License html = new com.aspose.html.License();
            html.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    

    /**
     * @param
     * @param
     * @param
     * @throws Exception
     */
    public static void converFile(String sourceFile) throws Exception {
        Long l=System.currentTimeMillis();
        //随机生成的路径
        String filePath = "/*****";
        sourceFile = sourceFile.replace("\\\\", "/");
        int pos = sourceFile.lastIndexOf("/");
        if (pos == -1) {
            pos = sourceFile.lastIndexOf("\\");
            if (pos == -1) {
                throw new RuntimeException("文件路径异常");
            }
        }
        String filename = sourceFile.substring(pos + 1);
        88String fileDir = sourceFile.substring(0, pos);
        //String filename_t = getFilename(filename);
        String fileType = getFileType(filename);
        String saveFile = null;
        //按照时间戳随机生成一个文件
        String name= filePath + "/" + l + ".pdf";
        switch (fileType) {
            case "doc":
            case "docx":
            case "ppt":
            case "pptx":
                saveFile = name;
                break;
            default:
                logger.info("该文件无需转换!");
                FileUtils.downLoadFile1(sourceFile,filename);
                return;
        }
        converFile(sourceFile, saveFile,l);
    }

    /**
     * @param
     * @param
     * @param
     * @throws Exception
     */
    public static void converFile(String sourceFile, String saveFile,Long l) throws Exception {
        String sourceFileType = getFileType(sourceFile);
        logger.info(sourceFile + "转换成" + saveFile);
        long start = System.currentTimeMillis();
        switch (sourceFileType) {
            case "doc":
            case "docx":
                if (!getWordLicense()) { // 验证 若不验证则转化出的pdf文档有License水印
                    throw new Exception("com.aspose.words lic ERROR!");
                }
                Document doc = new Document(sourceFile);
                doc.save(saveFile, SaveFormat.PDF);
                break;
            case "xls":
            case "xlsx":
                if (!getExcelLicense()) { // 验证License 若不验证则转化出的pdf文档有水印
                    throw new Exception("com.aspose.words lic ERROR!");
                }
                Workbook workbook = new Workbook(sourceFile);
                workbook.save(saveFile, com.aspose.cells.SaveFormat.HTML);
                break;
            case "ppt":
            case "pptx":
                if (!getPPTLicense()) { // 验证License 若不验证则转化出的pdf文档有水印
                    throw new Exception("com.aspose.words lic ERROR!");
                }
                Presentation pres = new Presentation(sourceFile);
                pres.save(saveFile, com.aspose.slides.SaveFormat.Pdf);
                break;
        }
        long end = System.currentTimeMillis();
        logger.debug("文件转换成功,共用了" + (end - start) + "豪秒");
        FileUtils.downLoadFile1(saveFile,l + ".pdf");
    }

   
}

去除水印需要在resources中创建license.xml

<License>
  <Data>
    <Products>
      <Product>Aspose.Words for Java</Product>
      <Product>Aspose.Total for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>29991231</SubscriptionExpiry>
    <LicenseExpiry>29991231</LicenseExpiry>
    <SerialNumber>---</SerialNumber>
  </Data>
  <Signature>---</Signature>
</License>


版权声明:本文为qq_43054097原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。