Java implements the online preview function of office files such as word, excel, ppt, txt, etc.!

How to use Java to implement the online preview function of office files such as word, excel, ppt, txt, etc.? This article tells you the answer!

Implementing the online preview function of office files in java is a need that everyone may encounter at work. Some online companies specialize in providing such services, but they require a fee.

If you want it for free, you can use openoffice. The implementation principle is:
Use the third-party tool openoffice to convert word, excel, ppt, txt and other files into PDF file streams; of course, if Adobe Reader XI is installed, drag the PDF directly to the browser page to open the preview directly, provided that the browser supports it PDF file browsing.

I will introduce here how to convert word, excel, ppt to pdf stream through poi, so that you can preview it on the browser.

  1. Go to the official website to download Apache OpenOffice: https://www.openoffice.org/download/ installation package, install and run. (For the installation methods of different systems, please refer to Baidu yourself. I won’t explain too much here)

Picture

  1. Introduce dependencies into the project’s pom file

<!--openoffice-->
<dependency>
    <groupId>com.artofsolving</groupId>
    <artifactId>jodconverter</artifactId>
    <version>2.2.1</version>
</dependency>
  1. Tool code to convert word, excel, ppt to pdf stream

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

/** * File format conversion tool class */
public class FileConvertUtil {
    /** Default converted file suffix */
    private static final String DEFAULT_SUFFIX = "pdf";
    /** openoffice_port */
    private static final Integer OPENOFFICE_PORT = 8100;

    /** * Method description Convert office documents to PDF (process local files) * * @param sourcePath source file path * @param suffix source file suffix * @return InputStream converted file input stream */
    public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
        File inputFile = new File(sourcePath);
        InputStream inputStream = new FileInputStream(inputFile);
        return covertCommonByStream(inputStream, suffix);
    }

    /** * Method description Convert office documents to PDF (processing network files) * * @param netFileUrl network file path * @param suffix file suffix * @return InputStream converted file input stream */
    public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
        //Create URL
        URL url = new URL(netFileUrl);
        //Try to connect and get the return status code
        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;
    }

    /** * Method description Convert files into streams * * @param inputStream source file input stream * @param suffix source file suffix * @return InputStream converted file input stream */
    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);
    }

    /** * Method description outputStream to inputStream */
    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");
    }
}
  1. serve layer online preview method code

/** * @Description: System file online preview interface * @Author: tarzan */
public void onlinePreview(String url, HttpServletResponse response) throws Exception {
    //Get file type
    String[] str = SmartStringUtil.split(url,"\.");

    if(str.length==0){
        throw new Exception("The file format is incorrect");
    }
    String suffix = str[str.length-1];
    if(!suffix.equals("txt") & amp; & amp; !suffix.equals("doc") & amp; & amp; !suffix.equals("docx") & amp; & amp; !suffix.equals("xls")
             & amp; & amp; !suffix.equals("xlsx") & amp; & amp; !suffix.equals("ppt") & amp; & amp; !suffix.equals("pptx" )){
        throw new Exception("The file format does not support preview");
    }
    InputStream in=FileConvertUtil.convertNetFile(url,suffix);
    OutputStream outputStream = response.getOutputStream();
    //Create an array to store the file contents
    byte[] buff =new byte[1024];
    //The read content is received using n
    int n;
    //When the reading is not finished, continue reading and loop
    while((n=in.read(buff))!=-1){
        //Write all the data of the byte array into the output stream
        outputStream.write(buff,0,n);
    }
    //Force the data in the cache area to be output
    outputStream.flush();
    //Turn off the flow
    outputStream.close();
    in.close();
}
  1. controller layer code

@ApiOperation(value = "System file online preview interface")
@PostMapping("/api/file/onlinePreview")
public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
    fileService.onlinePreview(url,response);
}

Show results:

Picture

Preview execl online

Picture

Preview word

Reference address: https://blog.csdn.net/weixin_40986713/article/details/109527294