基于java 和 LibreOffice实现文件预览

相关链接

工具库-基于LibreOffice实现文档操作_liumapp的博客-CSDN博客

LibreOffice 安装_头发浓密的程序员的博客-CSDN博客

1 安装 LibreOffice

        请参考链接 

LibreOffice 安装_头发浓密的程序员的博客-CSDN博客

需要记住 LibreOffice 安装主目录

2  pom 依赖


<dependency>
  <groupId>com.liumapp.workable.converter</groupId>
  <artifactId>workable-converter</artifactId>
  <version>v1.2.0</version>
</dependency>

3 配置文件 application.yml

com:
  liumapp:
    workable-converter:
      libreofficePath: "/Applications/LibreOffice.app/Contents" # LibreofficePath 安装主目录

4 controller 代码

@Controller
@RequestMapping("/viewfile")
public class ViewPdfController {
    @Autowired
    private AttachmentsService attachmentsService;

    @RequestMapping(value = "/pdf", method = RequestMethod.GET)
    @ResponseBody
    @Validated
    public void downloadFile(@RequestParam(value = "address") String address, HttpServletResponse response) throws IOException, ConvertFailedException {
        attachmentsService.libreOfficeOnlinePreview(address, response);
    }
}

 5 attachementService 代码


    public void libreOfficeOnlinePreview(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("文件格式不支持预览");
        }
        PdfUtils.wordToPdf(url, response);
    }

6 PdfUtils 代码

package com.ieslab.pdfview.service.fileservice;

import com.liumapp.workable.converter.WorkableConverter;
import com.liumapp.workable.converter.core.ConvertPattern;
import com.liumapp.workable.converter.exceptions.ConvertFailedException;
import com.liumapp.workable.converter.factory.CommonConverterManager;
import com.liumapp.workable.converter.factory.ConvertPatternManager;
import org.jodconverter.document.DefaultDocumentFormatRegistry;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @version V1.0
 * @Title:
 * @Package com.ieslab.pdfview.service.fileservice
 * @Description: TODO
 * @author: zongmoumou
 * @date 2020/10/13
 */
public class PdfUtils {
    public static void wordToPdf(String address, HttpServletResponse response) throws IOException, ConvertFailedException {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFilePath = "temp-" + uuid + ".pdf";
        WorkableConverter converter = new WorkableConverter();
        ConvertPattern pattern = ConvertPatternManager.getInstance();
        // 处理本地文件
        // pattern.streamToStream(new FileInputStream(address), new     FileOutputStream(tempFilePath));
        // 处理网络文件
        pattern.streamToStream(FileConvertUtil.getInputStream(address), new FileOutputStream(tempFilePath));
        pattern.setSrcFilePrefix(DefaultDocumentFormatRegistry.DOCX);
        pattern.setDestFilePrefix(DefaultDocumentFormatRegistry.PDF);
        converter.setConverterType(CommonConverterManager.getInstance());
        boolean result = converter.convert(pattern.getParameter());
        if (result) {
            outputPdf(tempFilePath, response);
            File file = new File(tempFilePath);
            if (file != null) {
                file.delete();
            }
        }
    }

    private static void outputPdf(String filePath, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
            String[] dir = filePath.split("/");
            String fileName = dir[dir.length - 1];
            // 设置响应类型为html,编码为utf-8,处理相应页面文本显示的乱码
            response.setContentType("application/octet-stream");
            // 设置文件头:最后一个参数是设置下载文件名
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {

        } finally {
            response.flushBuffer();
            try {
                out.close();
                in.close();
            } catch (NullPointerException e) {

            } catch (Exception e) {

            }
        }

    }
}

7 FileConvertUtil 代码

    public static InputStream getInputStream(String filePath) throws IOException {
        // 创建URL
        filePath = getEncodeUrl(filePath).replaceAll("\\+", "%20");
        InputStream inputStream = null;
        // 创建URL
        URL url = new URL(filePath);
        // 试图连接并取得返回状态码
        URLConnection urlconn = url.openConnection();
        urlconn.connect();
        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
        int httpResult = httpconn.getResponseCode();
        if (httpResult == HttpURLConnection.HTTP_OK) {
            inputStream = urlconn.getInputStream();
        }
        return inputStream;
    }

可以使用LibreOfficeJava API来实现LibreOffice文档转换为PDF文档。以下是实现的步骤: 1. 首先需要确保LibreOffice已经安装在系统中,并且已经配置好了环境变量。同时需要下载并安装LibreOfficeJava API。 2. 在Java程序中引入LibreOfficeJava API所在的jar包。 3. 使用以下代码将文档转换为PDF文档: ``` import com.sun.star.beans.PropertyValue; import com.sun.star.frame.XComponentLoader; import com.sun.star.lang.XComponent; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; public class ConvertToPDF { public static void main(String[] args) { XComponentContext xContext = null; try { //获取LibreOffice的上下文 xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); XComponentLoader xLoader = UnoRuntime.queryInterface(XComponentLoader.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xContext)); //设置待转换文档的路径和文件名 String fileToConvert = "file:///C:/example.docx"; //设置转换后的PDF文档的路径和文件名 String pdfFile = "file:///C:/example.pdf"; //设置转换参数 PropertyValue[] conversionProperties = new PropertyValue[2]; conversionProperties[0] = new PropertyValue(); conversionProperties[0].Name = "Hidden"; conversionProperties[0].Value = Boolean.TRUE; conversionProperties[1] = new PropertyValue(); conversionProperties[1].Name = "FilterName"; conversionProperties[1].Value = "writer_pdf_Export"; //打开待转换文档 XComponent xComponent = xLoader.loadComponentFromURL(fileToConvert, "_blank", 0, conversionProperties); //将文档转换为PDF格式 PropertyValue[] storeProperties = new PropertyValue[3]; storeProperties[0] = new PropertyValue(); storeProperties[0].Name = "FilterName"; storeProperties[0].Value = "writer_pdf_Export"; storeProperties[1] = new PropertyValue(); storeProperties[1].Name = "Overwrite"; storeProperties[1].Value = Boolean.TRUE; storeProperties[2] = new PropertyValue(); storeProperties[2].Name = "Hidden"; storeProperties[2].Value = Boolean.TRUE; UnoRuntime.queryInterface(XStorable.class, xComponent).storeToURL(pdfFile, storeProperties); //关闭文档 UnoRuntime.queryInterface(XCloseable.class, xComponent).close(Boolean.TRUE); } catch (Exception e) { e.printStackTrace(); } finally { if (xContext != null) { com.sun.star.uno.Runtime.getRuntime(xContext).freeUnusedLibraries(); } } } } ``` 4. 运行程序即可将LibreOffice文档转换为PDF文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值