Java中如何实现文件预览的功能

Java中如何实现文件预览的功能

JODConverter

  • JODConverter是一种Java OpenDocument转换器,能够转换不同格式的文档,它依赖于Apache OpenOffice或 LibreOffice ,它为OpenDocument和Microsoft Office提供了最好的免费导入/导出的过滤器。

  • JODConverter可以用在这几种地方:

    • 作为一个Java类库,嵌入到你的Java应用程序中。

    • 作为一个命令行工具,可以在你的脚本中调用。

    • 作为一个简单的web应用,上传文档,选择转换的格式并下载转换后的版本。

  • 可以用openoffice,实现原理就是:

    • 通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件流;这样就可以在浏览器上实现预览了。

    • 先去openoffice官网下载进行安装,官网地址:Apache OpenOffice - Official Download 安装完成后启动。

  • Maven中添加如下依赖

  •  <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.1</version>
        </dependency>

  • 将word、excel、ppt转换为pdf流的工具类代码

  • import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
    import com.artofsolving.jodconverter.DocumentConverter;
    import com.artofsolving.jodconverter.DocumentFormat;
    import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
    import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
    import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
     
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
     
     
    /**
     * 文件格式转换工具类
     *
     * @version 1.0
     * @since JDK1.8
     */
    public class FileConvertUtil {
        /** 默认转换后文件后缀 */
        private static final String DEFAULT_SUFFIX = "pdf";
        /** openoffice_port */
        private static final Integer OPENOFFICE_PORT = 8100;
     
        /**
         * 方法描述 office文档转换为PDF(处理本地文件)
         *
         * @param sourcePath 源文件路径
         * @param suffix     源文件后缀
         * @return InputStream 转换后文件输入流
         * @author tarzan
         */
        public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
            File inputFile = new File(sourcePath);
            InputStream inputStream = new FileInputStream(inputFile);
            return covertCommonByStream(inputStream, suffix);
        }
     
        /**
         * 方法描述  office文档转换为PDF(处理网络文件)
         *
         * @param netFileUrl 网络文件路径
         * @param suffix     文件后缀
         * @return InputStream 转换后文件输入流
         * @author tarzan
         */
        public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
            // 创建URL
            URL url = new URL(netFileUrl);
            // 试图连接并取得返回状态码
            URLConnection urlconn = url.openConnection();
            urlconn.connect();
            HttpURLConnection httpconn = (HttpURLConnection) urlconn;
            int httpResult = httpconn.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = urlconn.getInputStream();
                return covertCommonByStream(inputStream, suffix);
            }
            return null;
        }
     
        /**
         * 方法描述  将文件以流的形式转换
         *
         * @param inputStream 源文件输入流
         * @param suffix      源文件后缀
         * @return InputStream 转换后文件输入流
         * @author tarzan
         */
        public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
            connection.connect();
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
            DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
            DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
            DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
            converter.convert(inputStream, sourceFormat, out, targetFormat);
            connection.disconnect();
            return outputStreamConvertInputStream(out);
        }
     
        /**
         * 方法描述 outputStream转inputStream
         *
         * @author tarzan
         */
        public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
            ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
            return new ByteArrayInputStream(baos.toByteArray());
        }
     
     
     
        public static void main(String[] args) throws IOException {
            //convertNetFile("http://172.16.10.21/files/home/upload/department/base/201912090541573c6abdf2394d4ae3b7049dcee456d4f7.doc", ".pdf");
            //convert("c:/Users/admin/Desktop/2.pdf", "c:/Users/admin/Desktop/3.pdf");
        }
    }

  • serve层在线预览方法代码

  •  /**
         * @Description:系统文件在线预览接口
         */
        public void onlinePreview(String url, HttpServletResponse response) throws Exception {
            //获取文件类型
            String[] str = SmartStringUtil.split(url,"\\.");
     
            if(str.length==0){
                throw new Exception("文件格式不正确");
            }
            String suffix = str[str.length-1];
            if(!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
                    && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")){
                throw new Exception("文件格式不支持预览");
            }
            InputStream in=FileConvertUtil.convertNetFile(url,suffix);
            OutputStream outputStream = response.getOutputStream();
            //创建存放文件内容的数组
            byte[] buff =new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while((n=in.read(buff))!=-1){
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff,0,n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
            //关流
            outputStream.close();
            in.close();
        }

Aspose

  • Aspose.Words是一款先进的类库,通过它可以直接在各个应用程序中执行各种文档处理任务。Aspose.Words支持DOC,OOXML,RTF,HTML,OpenDocument, PDF, XPS, EPUB和其他格式。使用Aspose.Words,可以生成,更改,转换,渲染和打印文档而不使用Microsoft Word。

  • 实现原理也是通过Aspose把文件转换成pdf然后在预览,实现步骤如下: 添加jar包,下载地址:https://download.csdn.net/download/xinghui_liu/85931977

  • <?xml version="1.0" encoding="UTF-8" ?>
    <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>

  • 添加如下工具类,程序中调用doc2pdf即可实现文件转pdf

  • package com.weemambo.util;
    ​
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    ​
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    ​
    import com.aspose.words.Document;
    import com.aspose.words.License;
    import com.aspose.words.SaveFormat;
    ​
    public class Word2PdfAsposeUtil {
    ​
    ​
        public static boolean getLicense() {
            boolean result = false;
            InputStream is = null;
            try {
                Resource resource = new ClassPathResource("license.xml");
                is = resource.getInputStream();
                //InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
                License aposeLic = new License();
                aposeLic.setLicense(is);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
    ​
        public static boolean doc2pdf(String inPath, String outPath) {
            if (!getLicense()) { // 验证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, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
                // EPUB, XPS, SWF 相互转换
                long now = System.currentTimeMillis();
                System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }finally {
                if (os != null) {
                    try {
                        os.flush();
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return true;
        }
    }

总结

  • JODConverter 依赖于openoffice,需要在服务器单独安装openoffice

  • Aspose使用的是破解版的,如果商用使用需要考虑版权问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jayues_lies

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值