java实现文件预览(Office转PDF)

  • Post author:
  • Post category:java


一、首先下载安装openOffice软件,下载地址:

http://www.openoffice.org/download/index.html

当然,下载速度特别慢,下面是百度网盘地址。

链接:https://pan.baidu.com/s/1FfQa14WYXuJU2CTQf34gew

提取码:4q08

下载完一步一步下一步安装好,就行了。没什么特别的。

二、引入jar包

  <dependency>
      <groupId>org.jodconverter</groupId>
      <artifactId>jodconverter-core</artifactId>
      <version>4.0.0-RELEASE</version>
  </dependency>

三、上代码,注释都很详细,应该能看懂,主要原理呢就是讲office文件转换为PDF,页面可以直接打开PDF,相当于预览

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;


import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.DefaultOfficeManagerBuilder;
import org.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/filePreview")
public class FilePreview {

    private static final Logger logger = LoggerFactory.getLogger(FilePreview.class);


    //这个是为了将uri转为File对象的一个临时路径
    private String tempPath = System.getProperty("java.io.tmpdir");

    /**
     * 预览文件
     *
     * @param response 响应对象
     * @throws Exception
     */
    @RequestMapping("/readFile")
    public void readFile(HttpServletResponse response) throws Exception {
        try {

            File file = null;
            //文件路径
            String uri = "http://xxx.xxx.xxx.xxx/group1/M00/00/02/wKgAuV5NSPyAK7-ZAAA8pSZux3M89.docx";
            String fileName = uri.substring(uri.lastIndexOf("/") + 1);
            //通过FileUtils将服务器文件下载的本地临时文件夹
            URL url = new URL(uri);
            FileUtils.copyURLToFile(url, new File(tempPath + File.separator + fileName));
            //创建文件对象
            file = new File(tempPath + File.separator + fileName);
            InputStream inputStream = null;
            OutputStream outputStream = null;
            //截取文件后缀,判断是pdf还是word还是excel,若是pdf直接读否则转pdf再读
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
            if (!fileSuffix.equals("pdf")) {
                file = openOfficeToPDF(fileName, file);
            }
            //创建文件输入流
            if (file != null) {
                inputStream = new FileInputStream(file);
            }
            response.setContentType("application/pdf");
            outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(b)) != -1) {
                outputStream.write(b);
            }
            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }

    }

    /**
     * 将office文档转换为pdf文档
     *
     * @return
     */
    public static File openOfficeToPDF(String fileName, File file) {
        try {
            //截取源文件文件名
            String sourceFileName = fileName.substring(0, fileName.lastIndexOf("."));
            //启动openOffice
            DefaultOfficeManagerBuilder builder = new DefaultOfficeManagerBuilder();
            //文件转换为pdf后会在电脑临时存储,重新预览时,清空之前之前的文件夹
            File tempfile = new File("C:/pdfFile/");
            //这个方法是我用的工具类,大家可以自己写下,jar包我就没有放了
            FileUtil.del(tempfile);
            //然后重新将创建file文件对象,用来存储转换完成的PDF文件
            String after_convert_file_path = "C:/pdfFile/" + sourceFileName + ".pdf";
            File outputFile = new File(after_convert_file_path);
            if (!outputFile.getParentFile().exists()) {
                //如果上级目录不存在则创建一个
                outputFile.getParentFile().mkdirs();
            }
            //指定openOffice4安装路径,并开启
            String openOffice4path = "C:/Program Files (x86)/OpenOffice 4";
            builder.setOfficeHome(openOffice4path);
            OfficeManager officeManager = builder.build();
            officeManager.start();
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
            //文件转换PDF
            converter.convert(file, outputFile);
            officeManager.stop();
            return outputFile;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return null;
    }


}

注意:因为我用的FastDfs文件服务器,所以我的文件路径是http格式的uri,如果是本地文件就更简单了,看下面

            File file = null;
            //文件路径
            String uri = "http://xxx.xxx.xxx.xxx/group1/M00/00/02/wKgAuV5NSPyAK7-ZAAA8pSZux3M89.docx";
            String fileName = uri.substring(uri.lastIndexOf("/") + 1);
            //通过FileUtils将服务器文件下载的本地临时文件夹
            URL url = new URL(uri);
            FileUtils.copyURLToFile(url, new File(tempPath + File.separator + fileName));
            //创建文件对象
            file = new File(tempPath + File.separator + fileName);

            上面这段直接改成
            File file = new File("文件路径") 就好了



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