使用aspose方式使excel,ppt,word进行在线预览。(无水印)

使用aspose方式使excel,ppt,word进行在线预览。(无水印)


1.首先,页面需要用jquery中window.open();打开一个新页面。

 window.open(../fileManage/preview?id=1);

2.请求后台代码(Jfinal框架)

2.1获取文件绝对路径,拼接pdf生成的路径

   public void preview() {
        HttpServletResponse response = this.getResponse();
        Integer id = this.getParaToInt("id");
        FileInfo fileInfo = FileInfo.dao.getFileInfoById(id);
        String uploaddir = fileInfo.getStr("uploaddir");
        HttpServletRequest request = this.getRequest();
        String contextPath = request.getContextPath();
        // 获取webApp中的upload
        String basePath = request.getSession().getServletContext().getRealPath("/" + uploaddir + "");
        String path = request.getContextPath();
        //传给quurl方法,获取最后生成的文件地址
        String url = pdfUrl(basePath, fileInfo);
        //在线预览,浏览器支持的文件类型都能打开
        String fileName = fileInfo.getStr("name");
        URL u = null;
        try {
            u = new URL("file:///" + url);
            response.reset();
            response.setContentType(u.openConnection().getContentType());
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" +fileName );
            BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(url)));
            byte[] buf = new byte[1024];
            int len = 0;
            OutputStream out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            br.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        renderNull();
    }

2.2获取生成pdf路径。

    public String pdfUrl(String basePath, FileInfo fileInfo) {
        //获取文件名
        String filename = fileInfo.getStr("name");
        //获取后缀
        String type = fileInfo.getStr("type");
        int dot = basePath.lastIndexOf(".");
        //获取配置文件中的保存转换后文件的路径
        String path = basePath.substring(0, dot) + ".pdf";
        AsposePdfUtil.convertToPdfAsAspose(basePath, path, type);
        return path;
    }

2.3aspose工具类

package com.wom.utils;

import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;

import java.io.*;

/**
 *工具类
 * @author ycs
 */
public class AsposePdfUtil {
    /**
     * 使用aspose转换成pdf文件
     * @param inputFile
     * @param pdfFile
     * @return
     */
    public static boolean convertToPdfAsAspose(String inputFile, String pdfFile,String suffix) {
        File file = new File(inputFile) ;
        if(!file.exists()) {
            return false ;
        }
        if("pdf".equalsIgnoreCase(suffix)) {
            return false ;
        }

        //根据不同的文件转换成pdf文件
        if("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix) || "txt".equalsIgnoreCase(suffix)) {
            return doc2pdf(inputFile,pdfFile) ;
        } else if("xls".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix)) {
            return excel2Pdf(inputFile, pdfFile);
        } else if("ppt".equalsIgnoreCase(suffix) || "pptx".equalsIgnoreCase(suffix)) {
            return  ppt2pdf(inputFile, pdfFile);
        } else if (suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpg")
                || suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("gif")) {
            return img2PDF(inputFile, pdfFile);
        } else {
            return false;
        }
    }

    /**
     * aspose.word包获取配置
     * @return
     */
    public static boolean getWordLicense() {
        boolean result = false;
        InputStream is = null ;
        try {
            is = AsposePdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);
            result = true;
            is.close();
        } catch (Exception e) {
            if(is != null) {
                try {
                    is.close() ;
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
        return result;
    }

    /**
     * word文档转pdf
     * @param inPath
     * @param outPath
     */
    public static boolean doc2pdf(String inPath, String outPath) {
        if (!getWordLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        FileOutputStream os = null ;
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, com.aspose.words.SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
            os.close();
        } catch (Exception e) {
            if(os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
            return false ;
        }
        return true ;
    }

    public static boolean getExcelLicense() {
        boolean result = false;
        InputStream is = null ;
        try {
            is = AsposePdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
            is.close();
        } catch (Exception e) {
            if(is != null) {
                try {
                    is.close() ;
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
        return result;
    }

    /**
     * asponse:excel转pdf
     * @param excelPath
     * @param pdfPath
     */
    public static boolean excel2Pdf(String excelPath, String pdfPath) {
        long old = System.currentTimeMillis();
        // 验证License
        if (!getExcelLicense()) {
            return false;
        }
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            File excelFile = new File(excelPath);
            if (excelFile.exists()) {
                fileInputStream = new FileInputStream(excelFile);
                Workbook workbook = new Workbook(fileInputStream);
                File pdfFile = new File(pdfPath);
                fileOutputStream = new FileOutputStream(pdfFile);
                workbook.save(fileOutputStream, com.aspose.cells.SaveFormat.PDF);
                long now = System.currentTimeMillis();
                System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + pdfFile.getPath());
                return true ;
            } else {
                System.out.println("文件不存在");
                return false ;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false ;
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static boolean getPptLicense() {
        boolean result = false;
        InputStream is = null ;
        try {
            is = AsposePdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            com.aspose.slides.License aposeLic = new com.aspose.slides.License();
            aposeLic.setLicense(is);
            result = true;
            is.close();
        } catch (Exception e) {
            if(is != null) {
                try {
                    is.close() ;
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
        return result;
    }
    /**
     * aspose:ppt转pdf
     * @param inPath
     * @param outPath
     */
    public static boolean ppt2pdf(String inPath,String outPath) {

        // 验证License
        if (!getPptLicense()) {
            return false;
        }
        FileOutputStream fileOS = null ;
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath);// 输出pdf路径
            Presentation pres = new Presentation(inPath);//输入pdf路径
            fileOS = new FileOutputStream(file);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
            fileOS.close();

            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + file.getPath()); //转化过程耗时
       return  true;
        } catch (Exception e) {
            if(fileOS != null) {
                try {
                    fileOS.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
            return  false;
        }
    }

    //img转pdf
    public static boolean img2PDF(String imgFilePath, String pdfFilePath){
        File file = new File(imgFilePath);
        if (file.exists()) {
            com.lowagie.text.Document document = new com.lowagie.text.Document();
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(pdfFilePath);
                PdfWriter.getInstance(document, fos);

                // 添加PDF文档的某些信息,比如作者,主题等等
                document.addAuthor("newprint");
                document.addSubject("test pdf.");
                // 设置文档的大小
                document.setPageSize(PageSize.A4);
                // 打开文档
                document.open();
                // 写入一段文字
                // document.add(new Paragraph("JUST TEST ..."));
                // 读取一个图片
                Image image = Image.getInstance(imgFilePath);
                float imageHeight = image.getScaledHeight();
                float imageWidth = image.getScaledWidth();
                int i = 0;
                while (imageHeight > 500 || imageWidth > 500) {
                    image.scalePercent(100 - i);
                    i++;
                    imageHeight = image.getScaledHeight();
                    imageWidth = image.getScaledWidth();
                }

                image.setAlignment(Image.ALIGN_CENTER);
                // //设置图片的绝对位置
                // image.setAbsolutePosition(0, 0);
                // image.scaleAbsolute(500, 400);
                // 插入一个图片
                document.add(image);
            } catch (DocumentException de) {
                System.out.println(de.getMessage());
            } catch (IOException ioe) {
                System.out.println(ioe.getMessage());
            }
            document.close();
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return true;
        } else {
            return false;
        }
    }



}

所需jar包下载:

aspose下载

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值