Backend Development 8 min read

Implementing Online Office Document Preview in Java Using OpenOffice and JODConverter

This article demonstrates how to enable browser-based preview of Word, Excel, and PowerPoint files in Java by converting them to PDF streams with Apache OpenOffice and JODConverter, covering installation, Maven setup, utility code, service logic, and controller exposure.

IT Xianyu
IT Xianyu
IT Xianyu
Implementing Online Office Document Preview in Java Using OpenOffice and JODConverter

Java can be used to implement online preview of office documents by converting them to PDF streams, allowing browsers to display Word, Excel, and PowerPoint files without external services.

First, download and install Apache OpenOffice, then add the JODConverter dependency to your Maven pom.xml :

com.artofsolving
jodconverter
2.2.1

Next, create a utility class FileConvertUtil that provides methods to convert local or network files to PDF streams using OpenOffice via a socket connection.

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;

/**
 * 文件格式转换工具类
 *
 * @author tarzan
 * @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 转换后文件输入流
     */
    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 转换后文件输入流
     */
    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 转换后文件输入流
     */
    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
     */
    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://example.com/file.doc", ".pdf");
        //convert("c:/Users/admin/Desktop/2.pdf", "c:/Users/admin/Desktop/3.pdf");
    }
}

The service layer provides an onlinePreview method that validates the file extension, obtains the PDF stream via FileConvertUtil.convertNetFile , and streams the result to the HTTP response.

/**
 * 系统文件在线预览接口
 */
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];
    int n;
    while ((n = in.read(buff)) != -1) {
        outputStream.write(buff, 0, n);
    }
    outputStream.flush();
    outputStream.close();
    in.close();
}

A simple Spring MVC controller exposes a POST endpoint /api/file/onlinePreview that forwards the request to the service method.

@PostMapping("/api/file/onlinePreview")
public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception {
    fileService.onlinePreview(url, response);
}

By integrating these components, developers can enable seamless, server‑side conversion of office documents to PDF and provide instant preview functionality within web applications.

backendJavapdfFile ConversionOpenOfficeJODConverterWeb Preview
IT Xianyu
Written by

IT Xianyu

We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.