预览Word、PPT、Excel

我之前发过一篇文章,是介绍office预览和编辑的但是大部门插件都是收费的,我这次提供的是免费的一个将Word、PPT、Excel转换为PDF然后在浏览器进行预览,之前也看过很多网上的一些预览方案,比如openoffice、jacob、libreoffice等等,但是相对于速度以及bug容错来讲,用aspose是最简单最方便,直接jar包,然后代码抄走就行了。

jar包,跟相关xml我都放到我主页的下载资源中了,放到我服务器上的话,未来某一天服务器不用了,我这个文章岂不作废了,大家可以去我的主页下载资源,就是叫 使用aspose将office转换为PDF。

以下代码是我自己实际业务环境,大家可以自行修改,如有问题大家评论区讨论。

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.is.flywings.frame.util.Sysout;

public class AsposeUtil {
    /**
     * 获取license
     *
     * @return
     */
    public static boolean getLicense(int type) {
        boolean result = false;
        try {
            InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            if (type == 1) {//excel
                com.aspose.cells.License aposeLic = new com.aspose.cells.License();
                aposeLic.setLicense(is);
                result = true;
            } else if (type == 2) {//word
                com.aspose.words.License aposeLic = new com.aspose.words.License();
                aposeLic.setLicense(is);
                result = true;
            } else {//ppt
                com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                aposeLic.setLicense(is);
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void Excel2Pdf(String officePath,String OutPutPath,String officeName) {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
//            long old = Sysout.currentTimeMillis();
            Workbook wb = new Workbook(officePath);// 原始excel路径
            File pdfFile = new File(OutPutPath+officeName);// 输出路径
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            wb.save(fileOS, pdfSaveOptions);
//            long now = Sysout.currentTimeMillis();
//            Sysout.println("共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Word2Pdf(String officePath,String OutPutPath,String officeName) {
        // 验证License
        if (!getLicense(2)) {
            return;
        }
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Document doc = new Document(officePath);// 原始word路径
            File pdfFile = new File(OutPutPath+officeName);// 输出路径
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void PPT2Pdf(String officePath,String OutPutPath,String officeName) {
        // 验证License
        if (!getLicense(3)) {
            return;
        }
        try {
            File PathFile = new File(OutPutPath);
            if (!PathFile.exists()) {
                PathFile.mkdirs();
            }
            InputStream slides = new FileInputStream(new File(officePath));// 原始ppt路径
            Presentation pres = new Presentation(slides);
            File file = new File(OutPutPath+officeName);// 输出pdf路径
            FileOutputStream fileOS = new FileOutputStream(file);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String OfficeToPdf(String officePath) {

        //G:/product/WebApp/fwis_develop/com/is/flywings/oa/attchfile/1000000000/i0002/101951.docx⌒101951.docx⌒feiyu.docx
        String[] split = officePath.split("⌒");
        int lastIndex = split[0].lastIndexOf(".");
        int lastNameIndex = split[0].lastIndexOf("/");

        String officeType = split[0].substring(lastIndex+1);
        String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";
        String OutPutPath = split[0].substring(0,lastNameIndex+1)+"office/";

        File file = new File(split[0]);
        File pdfFile = new File(OutPutPath+officeName);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if(pdfFile.exists()){
            return OutPutPath+officeName;
        }

        if (file.exists()) {

            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);

            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String MB = df.format(megabytes);
            Double Size = Double.parseDouble(MB);
            if(Size>10){
                return Size+"MB";
            }
            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
            try {
                if(officeType.equals("doc")||officeType.equals("docx")){
                    Word2Pdf(split[0],OutPutPath,officeName);
                }else if(officeType.equals("xls")||officeType.equals("xlsx")){
                    Excel2Pdf(split[0],OutPutPath,officeName);
                }else if(officeType.equals("ppt")||officeType.equals("pptx")){
                    PPT2Pdf(split[0],OutPutPath,officeName);
                }else{
                    Sysout.println("无法识别该文件!");
                    return "Error";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "NotExists";
        }
        return OutPutPath+officeName;
    }

}

优点

使用aspose的优点就是转换快,可以跨平台,需要注意的就是中英文乱码,如果出现乱码,大家直接百度搜索aspose转换中文乱码即可,教程简单无脑,直接替换字体就行,无伤大雅。

如果是可以网上编辑的话

免费方案:
①采用dsoframer。dsoframer是微软提供一款开源的用于在线编辑、调用Word、 Excel 、PowerPoint等的ActiveX控件。缺点:只支持IE浏览器,由于dsoframer是早些年发布的,一直都没有更新,可能ie10、ie11下运行会有问题;调用起来比较复杂,功能少;客户端插件安装不方便,比如会遇到浏览器阻拦不能成功安装,甚至不提示安装等问题。
②利用Office Online 实现文档在线预览
利用office online 平台进行office 文档的在线查看,主旨在于获取文档的具体地址,通过Office 平台提供的链接地址指向需要预览的文档地址即可,例:http://view.officeapps.live.com/op/view.aspx?src=http%3a%2f%2fvideo.ch9.ms%2fbuild%2f2011%2fslides%2fTOOL-532T_Sutter.pptx
这个链接分为了两部分,一部分是 http://view.officeapps.live.com/op/view.aspx?src=,后面那个是具体的文档地址,用URLEncode进行处理的链接地址

通过拼接的地址即可实现office 的在线预览
需要注意的是:office 在线预览限制

文档访问地址不能直接使用 ip,需要通过域名访问,并且端口必须是 80 端口
文档的格式(必须为以下格式之一):
Word:docx、docm、dotm、dotx
Excel:xlsx、xlsb、xls、xlsm
PowerPoint:pptx、ppsx、ppt、pps、pptm、potm、ppam、potx、ppsm
文档的大小:Word 和 PowerPoint 文档必须小于 10 兆字节;Excel 必须小于五兆字节(通过office web app 部署的本地服务器可以设置文档大小)