• 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中添加如下依赖

      1.  <dependency>
      2.        <groupId>com.artofsolvinggroupId>
      3.        <artifactId>jodconverterartifactId>
      4.        <version>2.2.1version>
      5.    dependency>

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

      1. import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
      2. import com.artofsolving.jodconverter.DocumentConverter;
      3. import com.artofsolving.jodconverter.DocumentFormat;
      4. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
      5. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
      6. import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
      7. import java.io.*;
      8. import java.net.HttpURLConnection;
      9. import java.net.URL;
      10. import java.net.URLConnection;
      11. /**
      12. * 文件格式转换工具类
      13. *
      14. * @version 1.0
      15. * @since JDK1.8
      16. */
      17. public class FileConvertUtil {
      18.    /** 默认转换后文件后缀 */
      19.    private static final String DEFAULT_SUFFIX = "pdf";
      20.    /** openoffice_port */
      21.    private static final Integer OPENOFFICE_PORT = 8100;
      22.    /**
      23.     * 方法描述 office文档转换为PDF(处理本地文件)
      24.     *
      25.     * @param sourcePath 源文件路径
      26.     * @param suffix     源文件后缀
      27.     * @return InputStream 转换后文件输入流
      28.     * @author tarzan
      29.     */
      30.    public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
      31.        File inputFile = new File(sourcePath);
      32.        InputStream inputStream = new FileInputStream(inputFile);
      33.        return covertCommonByStream(inputStream, suffix);
      34.   }
      35.    /**
      36.     * 方法描述 office文档转换为PDF(处理网络文件)
      37.     *
      38.     * @param netFileUrl 网络文件路径
      39.     * @param suffix     文件后缀
      40.     * @return InputStream 转换后文件输入流
      41.     * @author tarzan
      42.     */
      43.    public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
      44.        // 创建URL
      45.        URL url = new URL(netFileUrl);
      46.        // 试图连接并取得返回状态码
      47.        URLConnection urlconn = url.openConnection();
      48.        urlconn.connect();
      49.        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
      50.        int httpResult = httpconn.getResponseCode();
      51.        if (httpResult == HttpURLConnection.HTTP_OK) {
      52.            InputStream inputStream = urlconn.getInputStream();
      53.            return covertCommonByStream(inputStream, suffix);
      54.       }
      55.        return null;
      56.   }
      57.    /**
      58.     * 方法描述 将文件以流的形式转换
      59.     *
      60.     * @param inputStream 源文件输入流
      61.     * @param suffix     源文件后缀
      62.     * @return InputStream 转换后文件输入流
      63.     * @author tarzan
      64.     */
      65.    public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
      66.        ByteArrayOutputStream out = new ByteArrayOutputStream();
      67.        OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
      68.        connection.connect();
      69.        DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
      70.        DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
      71.        DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
      72.        DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
      73.        converter.convert(inputStream, sourceFormat, out, targetFormat);
      74.        connection.disconnect();
      75.        return outputStreamConvertInputStream(out);
      76.   }
      77.    /**
      78.     * 方法描述 outputStream转inputStream
      79.     *
      80.     * @author tarzan
      81.     */
      82.    public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
      83.        ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
      84.        return new ByteArrayInputStream(baos.toByteArray());
      85.   }
      86.    public static void main(String[] args) throws IOException {
      87.        //convertNetFile("http://172.16.10.21/files/home/upload/department/base/201912090541573c6abdf2394d4ae3b7049dcee456d4f7.doc", ".pdf");
      88.        //convert("c:/Users/admin/Desktop/2.pdf", "c:/Users/admin/Desktop/3.pdf");
      89.   }
      90. }

    • serve层在线预览方法代码

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

    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

      1. "1.0" encoding="UTF-8" ?>
      2. <License>
      3.    <Data>
      4.        <Products>
      5.            <Product>Aspose.Total for JavaProduct>
      6.            <Product>Aspose.Words for JavaProduct>
      7.        Products>
      8.        <EditionType>EnterpriseEditionType>
      9.        <SubscriptionExpiry>20991231SubscriptionExpiry>
      10.        <LicenseExpiry>20991231LicenseExpiry>
      11.        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7SerialNumber>
      12.    Data>
      13.    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=Signature>
      14. License>

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

      1. package com.weemambo.util;
      2. import java.io.File;
      3. import java.io.FileOutputStream;
      4. import java.io.IOException;
      5. import java.io.InputStream;
      6. import org.springframework.core.io.ClassPathResource;
      7. import org.springframework.core.io.Resource;
      8. import com.aspose.words.Document;
      9. import com.aspose.words.License;
      10. import com.aspose.words.SaveFormat;
      11. public class Word2PdfAsposeUtil {
      12.    public static boolean getLicense() {
      13.        boolean result = false;
      14.        InputStream is = null;
      15.        try {
      16.            Resource resource = new ClassPathResource("license.xml");
      17.            is = resource.getInputStream();
      18.            //InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
      19.            License aposeLic = new License();
      20.            aposeLic.setLicense(is);
      21.            result = true;
      22.       } catch (Exception e) {
      23.            e.printStackTrace();
      24.       }finally {
      25.            if (is != null) {
      26.                try {
      27.                    is.close();
      28.               } catch (IOException e) {
      29.                    e.printStackTrace();
      30.               }
      31.           }
      32.       }
      33.        return result;
      34.   }
      35.    public static boolean doc2pdf(String inPath, String outPath) {
      36.        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
      37.            return false;
      38.       }
      39.        FileOutputStream os = null;
      40.        try {
      41.            long old = System.currentTimeMillis();
      42.            File file = new File(outPath); // 新建一个空白pdf文档
      43.            os = new FileOutputStream(file);
      44.            Document doc = new Document(inPath); // Address是将要被转化的word文档
      45.            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
      46.            // EPUB, XPS, SWF 相互转换
      47.            long now = System.currentTimeMillis();
      48.            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
      49.       } catch (Exception e) {
      50.            e.printStackTrace();
      51.            return false;
      52.       }finally {
      53.            if (os != null) {
      54.                try {
      55.                    os.flush();
      56.                    os.close();
      57.               } catch (IOException e) {
      58.                    e.printStackTrace();
      59.               }
      60.           }
      61.       }
      62.        return true;
      63.   }
      64. }

    总结

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

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

  • 相关阅读:
    SQL LIKE 运算符
    域名解析DNS:如何查询txt类型的解析记录
    STM32 使用内部晶振导致 Can 通讯异常
    (高阶)Redis 7 第12讲 数据双写一致性 经验篇
    liunx:进程概念
    Spring Boot项目中使用 TrueLicense 生成和验证License(附源码)
    【Python深度学习】Python全栈体系(二十九)
    【刷题(12)】图论
    力扣(LeetCode)323. 无向图中连通分量的数目(2022.11.20)
    数据结构基础==数据结构与算法2
  • 原文地址:https://blog.csdn.net/Andrew_Chenwq/article/details/126757105