Use Openoffice or LibreOffice to realize online preview of World, Excel, PPTX

preview plan

use of third-party services

There are third-party services that provide the function of previewing documents online. You can upload files to these services, and then embed the preview components provided by them into your web pages. Commonly used services include Google Docs, Microsoft Office Online, and Adobe Document Cloud.

1. Call Microsoft's online preview function to achieve

<iframe src='https://view.officeapps.live.com/op/view.aspx?src='+fileurl width='100%' height='100%' frameborder='1'></iframe>

2. Call Google's document online preview implementation

<iframe :src="https://docs.google.com/viewer?url="+fileurl></iframe>

3. Call the XDOC document preview service

XDOC document preview service:https://view.xdocin.com/

XDOC can also realize online preview of text, text with parameters, html text, json text, official documents, etc. For the specific implementation method, please refer to the official document

Notice:预览资源必须是公共可访问的

Use the front-end library

Use some front-end libraries to achieve online preview of documents. For example, for Word documents and Excel files, you can use the mammoth.js or xlsx.js libraries to parse and render the file content. For PDF files, you can use the pdf.js library to render and display PDF content.

world:https://github.com/mwilliamson/mammoth.js

excel:https://github.com/qax-os/excelizehttps://github.com/tealeg/xlsx

pdf:https://github.com/mozilla/pdf.js

convert format

Convert documents to a specific format and display them on a web page. For example: Convert Word, Excel, and PDF to PDF, HTML, and images for preview.

You can use jodconverter, which is a powerful document conversion tool for applications that need to convert Office documents to other formats.

jodconverter

jodconverter overview

jodconverter is an open source project for converting Office documents (such as Word, Excel, PowerPoint, etc.) to other formats, such as PDF, HTML, images, etc. It is based on the Java platform and uses LibreOffice/OpenOffice as the conversion engine.

jodconverter provides an easy-to-use API that enables developers to integrate document conversion functionality in their own applications. It can be used with Java applications, or can be called remotely through the REST API.

Github:https://github.com/jodconverter/jodconverter

main features

文档转换:jodconverter 可以将各种 Office 文档格式(如 DOCX、XLSX、PPTX 等)转换为其他格式,如 PDF、HTML、图像(PNG、JPEG 等)等。

批量转换:你可以使用 jodconverter 批量转换多个文档,提高转换效率。

异步转换:jodconverter 支持异步转换,可以在后台进行文档转换,不会阻塞主线程。

自定义配置:你可以根据需要配置转换过程中的参数,如输出格式、图像质量、页面大小等。

监听器支持:jodconverter 提供了监听器接口,可以在转换过程中监听转换状态和进度。

多平台支持:jodconverter 可以在多个平台上运行,包括 Windows、Linux 和 macOS。

OpenOffice

jodconverter depends on Apache OpenOffice or LibreOffice, you need to install one of them before using jodconverter

Apache OpenOffice is a free open source office software suite that includes text editors, spreadsheets, presentations, graphics processing, and database management. It is developed and maintained by the Apache Software Foundation, supports cross-platform, and can run on operating systems such as Windows, Mac, and Linux. Apache OpenOffice is similar to Microsoft Office and can be used to create, edit and share various documents, reports and emails.

openoffice download:http://www.openoffice.org/download/index.html
insert image description here
insert image description here

LibreOffice

jodconverter depends on Apache OpenOffice or LibreOffice, you need to install one of them before using jodconverter

LibreOffice is a free open source office suite, which includes multiple components such as text editors, spreadsheets, presentations, drawing and database management tools, which can be used to handle various common office tasks. LibreOffice is developed by The Document Foundation and is a branch of OpenOffice.org. Its source code is completely open and it provides support for a variety of operating systems, including Windows, Mac OS X, and Linux.

libreoffice:https://www.libreoffice.org/download/download-libreoffice/

insert image description here
insert image description here

Basic use of jodconverter

add dependencies

        <!-- 核心包 -->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>4.4.6</version>
        </dependency>
        <!-- 本地支持包 -->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.4.6</version>
        </dependency>

configuration

jodconverter:
  local:
    # libreOffice根目录
#    office-home: D:\LibreOffice
    # OpenOffice安装地址
    office-home: D:\OpenOffice 4
    # 同时执行任务的个数,最大进程数
    max-tasks-per-process: 2
    # 开启多个进程,每个端口对应一个进程;设置端口号(任意设置)
    port-numbers: 3000,3001
    # 一个进程的超时时间
    process-timeout: 120000

Create a DocumentConverter instance

import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.office.InstalledOfficeManagerHolder;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.core.office.OfficeUtils;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Arrays;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ConverterConfiguration {
    
    

    private LocalOfficeManager officeManager;
    @Value("${jodconverter.local.office-home}")
    private String officeHome;

    @Value("${jodconverter.local.port-numbers}")
    private String portNumber;

    @Value("${jodconverter.local.max-tasks-per-process}")
    private Integer maxTaskPerProcess;

    @Value("${jodconverter.local.process-timeout}")
    private Long processTimeout;

    /**
     * 启动Office组件进程
     *
     * @return
     */
    @PostConstruct
    public OfficeManager officeManager() {
    
    
        // 多个端口处理
        String[] portsString = portNumber.split(",");
        int[] ports = Arrays.stream(portsString).mapToInt(Integer::parseInt).toArray();
        // 系统判断
        String os = System.getProperty("os.name").toLowerCase();

        officeManager = LocalOfficeManager.builder()
                .officeHome(os.contains("windows") ? officeHome : "linuxHome")
                .portNumbers(ports)
                .processTimeout(processTimeout)
                .maxTasksPerProcess(maxTaskPerProcess)
                .install()
                .build();
        try {
    
    
            officeManager.start();
            InstalledOfficeManagerHolder.setInstance(officeManager);
            log.info("office进程启动成功");
        } catch (OfficeException e) {
    
    
            log.error("启动office组件失败");
            throw new RuntimeException(e);
        }
        return officeManager;
    }

    /**
     * 创建DocumentConverter实例
     *
     * @return
     */
    @Bean
    public DocumentConverter documentConverter() {
    
    
        log.info("创建DocumentConverter实例");
        LocalConverter converter = LocalConverter.builder()
                .officeManager(officeManager)
                .build();
        return converter;
    }

    @PreDestroy
    public void destroyOfficeManager() {
    
    
        if (null != officeManager && officeManager.isRunning()) {
    
    
            log.info("终止office进程");
            OfficeUtils.stopQuietly(officeManager);
        }
    }

}

Upload and Convert


import org.jodconverter.DocumentConverter;
import org.jodconverter.document.DefaultDocumentFormatRegistry;
import org.jodconverter.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@RestController
public class FileController {
    
    

    /**
     * 上传与预览的测试目录
     */
    public static String PATH = "D://test//";

	/**
     *  转换器
     */
    @Autowired
    private DocumentConverter documentConverter;


    @GetMapping("/test")
    public String test() {
    
    
        return "OK";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws OfficeException {
    
    
        if (file.isEmpty()) {
    
    
            return "请选择上传文件";
        }

        // 保存上传文件
        File localFile = new File(PATH + file.getOriginalFilename());
        try (OutputStream os = new FileOutputStream(localFile)) {
    
    
            os.write(file.getBytes());
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        // 转换成pdf的名称
        String pdfName = UUID.randomUUID().toString().replace("-", "");
        // 转换成pdf存放路径
        File pdfFile = new File(PATH + pdfName + ".pdf");
        // 开始转换
        documentConverter.convert(localFile)
                .as("doc".equals(DefaultDocumentFormatRegistry.DOC.getExtension()) ? DefaultDocumentFormatRegistry.DOC : DefaultDocumentFormatRegistry.DOCX)
                .to(pdfFile).as(DefaultDocumentFormatRegistry.PDF)
                .execute();

        // 返回转换后的pdf文件的URL
        String previewUrl = "http://localhost:8888/preview/" + pdfName;
        return "<a href='" + previewUrl + "' target='_blank'>Preview</a>";
    }
}

preview

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@RestController
public class PreviewController {
    
    

    @GetMapping("/preview/{fileName}")
    public void showPreview(@PathVariable String fileName, HttpServletResponse response) throws IOException {
    
    
        File file = new File(FileController.PATH + fileName + ".pdf");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=" + fileName);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        Files.copy(file.toPath(), response.getOutputStream());
    }
}

start up

OpenOffice startup log:

INFO 25076 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8888 (http)
INFO 25076 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
INFO 25076 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
INFO 25076 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : Loaded Apache Tomcat Native library [1.2.31] using APR version [1.7.0].
INFO 25076 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
INFO 25076 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
INFO 25076 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1l  24 Aug 2021]
INFO 25076 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
INFO 25076 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2235 ms
INFO 25076 --- [  restartedMain] c.y.demo.config.ConverterConfiguration   : office进程启动成功
INFO 25076 --- [er-offprocmng-0] o.j.local.office.OfficeDescriptor        : soffice info (from exec path): Product: OpenOffice - Version: ??? - useLongOptionNameGnuStyle: false
INFO 25076 --- [er-offprocmng-1] o.j.local.office.OfficeDescriptor        : soffice info (from exec path): Product: OpenOffice - Version: ??? - useLongOptionNameGnuStyle: false
INFO 25076 --- [  restartedMain] c.y.demo.config.ConverterConfiguration   : 创建DocumentConverter实例
INFO 25076 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
INFO 25076 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
INFO 25076 --- [er-offprocmng-0] o.j.l.office.LocalOfficeProcessManager   : Starting process with --accept 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1;urp;StarOffice.ServiceManager' and profileDir 'C:\Users\Admin\AppData\Local\Temp\.jodconverter_socket_host-127.0.0.1_port-3000_tcpNoDelay-1'
INFO 25076 --- [er-offprocmng-1] o.j.l.office.LocalOfficeProcessManager   : Starting process with --accept 'socket,host=127.0.0.1,port=3001,tcpNoDelay=1;urp;StarOffice.ServiceManager' and profileDir 'C:\Users\Admin\AppData\Local\Temp\.jodconverter_socket_host-127.0.0.1_port-3001_tcpNoDelay-1'
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
INFO 25076 --- [er-offprocmng-0] o.j.local.office.OfficeConnection        : Connected: 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1'
INFO 25076 --- [er-offprocmng-0] o.j.l.office.LocalOfficeProcessManager   : Started process; pid: 27528
INFO 25076 --- [er-offprocmng-1] o.j.local.office.OfficeConnection        : Connected: 'socket,host=127.0.0.1,port=3001,tcpNoDelay=1'
INFO 25076 --- [er-offprocmng-1] o.j.l.office.LocalOfficeProcessManager   : Started process; pid: 20444
INFO 25076 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
INFO 25076 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
INFO 25076 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8888 (http) with context path ''
INFO 25076 --- [  restartedMain] cn.ybzy.demo.Application                 : Started Application in 6.576 seconds (JVM running for 8.362)
INFO 25076 --- [1)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
WARN 25076 --- [1)-192.168.56.1] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
INFO 25076 --- [1)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
INFO 25076 --- [3)-192.168.56.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 25076 --- [3)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
INFO 25076 --- [3)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms
INFO 25076 --- [ter-poolentry-2] o.j.local.task.LocalConversionTask       : Executing local conversion task [doc -> pdf]...

LibreOffice startup log:

5728 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8888 (http)
25728 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
5728 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
NFO 5728 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : Loaded Apache Tomcat Native library [1.2.31] using APR version [1.7.0].INFO 5728 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].INFO 5728 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]INFO 5728 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1l  24 Aug 2021]INFO 5728 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContextINFO 5728 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2260 msINFO 5728 --- [  restartedMain] c.y.demo.config.ConverterConfiguration   : office进程启动成功INFO 5728 --- [er-offprocmng-0] o.j.local.office.OfficeDescriptor        : soffice info (from exec path): Product: LibreOffice - Version: ??? - useLongOptionNameGnuStyle: true
INFO 5728 --- [er-offprocmng-1] o.j.local.office.OfficeDescriptor        : soffice info (from exec path): Product: LibreOffice - Version: ??? - useLongOptionNameGnuStyle: true
INFO 5728 --- [  restartedMain] c.y.demo.config.ConverterConfiguration   : 创建DocumentConverter实例
INFO 5728 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
INFO 5728 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
INFO 5728 --- [er-offprocmng-1] o.j.l.office.LocalOfficeProcessManager   : Starting process with --accept 'socket,host=127.0.0.1,port=3001,tcpNoDelay=1;urp;StarOffice.ServiceManager' and profileDir 'C:\Users\Admin\AppData\Local\Temp\.jodconverter_socket_host-127.0.0.1_port-3001_tcpNoDelay-1'
INFO 5728 --- [er-offprocmng-0] o.j.l.office.LocalOfficeProcessManager   : Starting process with --accept 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1;urp;StarOffice.ServiceManager' and profileDir 'C:\Users\Admin\AppData\Local\Temp\.jodconverter_socket_host-127.0.0.1_port-3000_tcpNoDelay-1'
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
INFO 5728 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
INFO 5728 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
INFO 5728 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8888 (http) with context path ''
INFO 5728 --- [  restartedMain] cn.ybzy.demo.Application                 : Started Application in 6.968 seconds (JVM running for 8.97)
INFO 5728 --- [1)-192.168.56.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 5728 --- [1)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet' INFO 5728 --- [2)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
WARN 5728 --- [2)-192.168.56.1] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
INFO 5728 --- [1)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
INFO 5728 --- [2)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
INFO 5728 --- [er-offprocmng-1] o.j.local.office.OfficeConnection        : Connected: 'socket,host=127.0.0.1,port=3001,tcpNoDelay=1'
INFO 5728 --- [er-offprocmng-1] o.j.l.office.LocalOfficeProcessManager   : Started process; pid: 29060
INFO 5728 --- [er-offprocmng-0] o.j.local.office.OfficeConnection        : Connected: 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1'
INFO 5728 --- [er-offprocmng-0] o.j.l.office.LocalOfficeProcessManager   : Started process; pid: 16476
INFO 5728 --- [ter-poolentry-2] o.j.local.task.LocalConversionTask       : Executing local conversion task [doc -> pdf]...

Upload and preview World

insert image description here

insert image description here

Integration with Spring Boot

add dependencies

        <!-- 核心包 -->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>4.2.2</version>
        </dependency>
        <!-- 本地支持包 -->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.2.2</version>
        </dependency>
        <!-- springboot支持,包括自动配置类 -->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-spring-boot-starter</artifactId>
            <version>4.2.2</version>
        </dependency>

Configuring JodConverter and LibreOffice

Configure JodConverter and LibreOffice by adding the following properties to your application's configuration file:

jodconverter:
  local:
    enabled: true
    # libreOffice根目录
    office-home: D:\LibreOffice
    # OpenOffice安装地址
    # office-home: D:\OpenOffice 4
    # 同时执行任务的个数,最大进程数
    max-tasks-per-process: 2
    # 开启多个进程,每个端口对应一个进程;设置端口号(任意设置)
    port-numbers: 3000
    # 任务执行的超时时间
    taskExecutionTimeout: 120000
    # 任务队列的超时时间
    taskQueueTimeout: 30000
    # 一个进程的超时时间
    process-timeout: 120000

start comparison

Use Openoffice

INFO 17640 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8888 (http)
INFO 17640 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
INFO 17640 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
INFO 17640 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : Loaded Apache Tomcat Native library [1.2.31] using APR version [1.7.0].
INFO 17640 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
INFO 17640 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
INFO 17640 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1l  24 Aug 2021]
INFO 17640 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
INFO 17640 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 5223 ms
INFO 17640 --- [  restartedMain] o.j.office.OfficeProcessManager          : Submitting task 'Start' and waiting...
INFO 17640 --- [ProcessThread-0] o.jodconverter.office.OfficeDescriptor   : soffice info (from exec path): Product: OpenOffice - Version: ??? - useLongOptionNameGnuStyle: false
INFO 17640 --- [ProcessThread-0] org.jodconverter.office.OfficeProcess    : Starting process with acceptString 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1;urp;StarOffice.ServiceManager' and profileDir 'C:\Users\Admin\AppData\Local\Temp\.jodconverter_socket_host-127.0.0.1_port-3000_tcpNoDelay-1'
INFO 17640 --- [ProcessThread-0] org.jodconverter.office.OfficeProcess    : Started process; pid = 19960
INFO 17640 --- [ProcessThread-0] o.jodconverter.office.OfficeConnection   : Connected: 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1'
INFO 17640 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
INFO 17640 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
INFO 17640 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
INFO 17640 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
INFO 17640 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8888 (http) with context path ''
INFO 17640 --- [  restartedMain] cn.ybzy.demo.Application                 : Started Application in 12.67 seconds (JVM running for 16.446)
INFO 17640 --- [2)-192.168.56.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 17640 --- [2)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
INFO 17640 --- [1)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
WARN 17640 --- [1)-192.168.56.1] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
INFO 17640 --- [2)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 16 ms
INFO 17640 --- [1)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
INFO 17640 --- [agerPoolEntry-1] o.jodconverter.task.LocalConversionTask  : Executing local conversion task...

Using LibreOffice

INFO 13756 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8888 (http)
INFO 13756 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
INFO 13756 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
INFO 13756 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : Loaded Apache Tomcat Native library [1.2.31] using APR version [1.7.0].
INFO 13756 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
INFO 13756 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
INFO 13756 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1l  24 Aug 2021]
INFO 13756 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
INFO 13756 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2312 ms
INFO 13756 --- [  restartedMain] o.j.office.OfficeProcessManager          : Submitting task 'Start' and waiting...
INFO 13756 --- [ProcessThread-0] o.jodconverter.office.OfficeDescriptor   : soffice info (from exec path): Product: LibreOffice - Version: ??? - useLongOptionNameGnuStyle: true
INFO 13756 --- [ProcessThread-0] org.jodconverter.office.OfficeProcess    : Starting process with acceptString 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1;urp;StarOffice.ServiceManager' and profileDir 'C:\Users\Admin\AppData\Local\Temp\.jodconverter_socket_host-127.0.0.1_port-3000_tcpNoDelay-1'
INFO 13756 --- [ProcessThread-0] org.jodconverter.office.OfficeProcess    : Started process; pid = 3216
INFO 13756 --- [ProcessThread-0] o.jodconverter.office.OfficeConnection   : Connected: 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1'
INFO 13756 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
INFO 13756 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
INFO 13756 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
INFO 13756 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
INFO 13756 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8888 (http) with context path ''
INFO 13756 --- [  restartedMain] cn.ybzy.demo.Application                 : Started Application in 21.748 seconds (JVM running for 23.568)
INFO 13756 --- [1)-192.168.56.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 13756 --- [1)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
INFO 13756 --- [2)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
WARN 13756 --- [2)-192.168.56.1] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
INFO 13756 --- [1)-192.168.56.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
INFO 13756 --- [2)-192.168.56.1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
INFO 13756 --- [agerPoolEntry-1] o.jodconverter.task.LocalConversionTask  : Executing local conversion task...

After testing it was found that:使用Openoffice启动速度更快

Preview Excel

You can convert Excel to PDF or HTML format for preview. Generally speaking, it is better to convert to HTML format. Here, it is only used for debugging and converted to PDF.

@RestController
public class FileController {
    
    

    /**
     * 上传与预览的测试目录
     */
    public static String PATH = "D://test//";

    @Autowired
    private DocumentConverter documentConverter;


    @GetMapping("/test")
    public String test() {
    
    
        return "OK";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws OfficeException, IOException {
    
    
        if (file.isEmpty()) {
    
    
            return "请选择上传文件";
        }

        // 保存上传文件
        File localFile = new File(PATH + file.getOriginalFilename());
        FileUtils.writeByteArrayToFile(localFile, file.getBytes());

        // 转换成pdf的名称
        String pdfName = UUID.randomUUID().toString().replace("-", "");
        // 转换成pdf存放路径
        File pdfFile = new File(PATH + pdfName + ".pdf");

        // 开始转换
        documentConverter.convert(localFile).to(pdfFile).execute();

        // 返回转换后的pdf文件的URL
        String previewUrl = "http://localhost:8888/preview/" + pdfName;
        return "<a href='" + previewUrl + "' target='_blank'>Preview</a>";
    }
}

NFO 24048 --- [er-offprocmng-0] o.j.local.office.OfficeConnection        : Connected: 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1'
INFO 24048 --- [er-offprocmng-0] o.j.l.office.LocalOfficeProcessManager   : Started process; pid: 9896
INFO 24048 --- [ter-poolentry-1] o.j.local.task.LocalConversionTask       : Executing local conversion task [xlsx -> pdf]...

insert image description here

insert image description here

PPTX preview

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws OfficeException, IOException {
    
    
        if (file.isEmpty()) {
    
    
            return "请选择上传文件";
        }

        // 保存上传文件
        File localFile = new File(PATH + file.getOriginalFilename());
        FileUtils.writeByteArrayToFile(localFile, file.getBytes());

        // 转换成pdf的名称
        String pdfName = UUID.randomUUID().toString().replace("-", "");
        // 转换成pdf存放路径
        File pdfFile = new File(PATH + pdfName + ".pdf");

        // 开始转换
        documentConverter.convert(localFile).to(pdfFile).execute();
        
        // 返回转换后的pdf文件的URL
        String previewUrl = "http://localhost:8888/preview/" + pdfName;
        return previewUrl;
    }

insert image description here

INFO 24048 --- [er-offprocmng-0] o.j.local.office.OfficeConnection        : Connected: 'socket,host=127.0.0.1,port=3000,tcpNoDelay=1'
INFO 24048 --- [er-offprocmng-0] o.j.l.office.LocalOfficeProcessManager   : Started process; pid: 16724
INFO 24048 --- [ter-poolentry-1] o.j.local.task.LocalConversionTask       : Executing local conversion task [pptx -> pdf]...

Guess you like

Origin blog.csdn.net/qq_38628046/article/details/130683144