web浏览office java LiberOffice

安装插件

  • 1、解压: tar -xvf LibreOffice_7.5.2_Linux_x86-64_rpm.tar.gz
  • 2、安装:cd LibreOffice_7.5.2_Linux_x86-64_rpm/RPMS
  • 3、执行 yum localinstall *.rpm
  • 4、which libreoffice7.5 看到路径为
  • 5.、默认目录 opt/libreoffice7.5
  • 6、运行 /opt/libreoffice7.5/program/soffice --headless --accept="socket, host=127.0.0.1, port=8102; urp;" --nofirststartwizard &
注:

如果报错:
/opt/libreoffice5.3/program/oosplash: error while loading shared libraries: libXinerama.so.1: cannot open shared object file: No such file or directory

安装依赖:yum install -y libXinerama

报错:
/opt/libreoffice5.3/program/soffice.bin: error while loading shared libraries: libcairo.so.2: cannot open shared object file: No such file or directory

安装依赖:yum install -y ibus

注:linux 环境下 docx 转pdf会出现乱码,解决方法 安装拓展字体

java实现

1、maven依赖
 		 <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-spring-boot-starter</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.libreoffice</groupId>
            <artifactId>ridl</artifactId>
            <version>5.4.2</version>
        </dependency>

2、yml配置信息

application.yml

spring:
  profiles:
    active: linux
server:
  port: 86

application-linux.yml

jodconverter:
  local:
    enabled: true
    # 设置LibreOffice主目录
    office-home: /opt/libreoffice7.5
    # 开启多个LibreOffice进程,每个端口对应一个进程
    port-numbers: 8102
    # LibreOffice进程重启前的最大进程数
    max-tasks-per-process: 100

application-win.yml

jodconverter:
  local:
    enabled: true
    # 设置LibreOffice主目录
    office-home: C:\Program Files\LibreOffice
    # 开启多个LibreOffice进程,每个端口对应一个进程
    port-numbers: 8102
    # LibreOffice进程重启前的最大进程数
    max-tasks-per-process: 100
package com.dfsoft.libreoffice;

import lombok.extern.slf4j.Slf4j;
import org.jodconverter.DocumentConverter;
import org.jodconverter.document.DefaultDocumentFormatRegistry;
import org.jodconverter.document.DocumentFormat;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;


@Slf4j
@Service
public class OfficeConvertToPdfService {
    
    
    @Resource
    private DocumentConverter documentConverter;

    /**
     * @param inputStream  源文件输入流
     * @param outputStream pdf目标输出流
     */
    public void convert(InputStream inputStream, OutputStream outputStream, String suffix) throws Exception {
    
    
        final DocumentFormatEnum documentFormatEnum = DocumentFormatEnum.valueOf(suffix.toUpperCase());
        try (final InputStream is = documentFormatEnum.getInputStream(inputStream))
        {
    
    
            final DocumentFormat format = documentFormatEnum.getFormFormat();
            log.info(">>> 待转换的文档类型:{}", format);
            final DocumentFormat targetFormat = documentFormatEnum.getTargetFormat();
            log.info(">>> 转换的目标文档类型:{}", targetFormat);
            documentConverter.convert(is).as(format).to(outputStream).as(targetFormat).execute();
        }
        log.info(">>> 文件转换结束");
    }

    public enum DocumentFormatEnum {
    
    
        DOC {
    
    
            @Override
            public DocumentFormat getFormFormat() {
    
    
                return DefaultDocumentFormatRegistry.DOC;
            }
        },
        DOCX {
    
    
            @Override
            public DocumentFormat getFormFormat() {
    
    
                return DefaultDocumentFormatRegistry.DOCX;
            }
        },
        PPT {
    
    
            @Override
            public DocumentFormat getFormFormat() {
    
    
                return DefaultDocumentFormatRegistry.PPT;
            }
        },
        PPTX {
    
    
            @Override
            public DocumentFormat getFormFormat() {
    
    
                return DefaultDocumentFormatRegistry.PPTX;
            }
        },
        XLS {
    
    
            @Override
            public DocumentFormat getFormFormat() {
    
    
                return DefaultDocumentFormatRegistry.XLS;
            }

            @Override
            public DocumentFormat getTargetFormat() {
    
    
                return DefaultDocumentFormatRegistry.HTML;
            }
        },
        XLSX {
    
    
            @Override
            public DocumentFormat getFormFormat() {
    
    
                return DefaultDocumentFormatRegistry.XLSX;
            }

            @Override
            public DocumentFormat getTargetFormat() {
    
    
                return DefaultDocumentFormatRegistry.HTML;
            }
        },
        TXT {
    
    
            @Override
            public DocumentFormat getFormFormat() {
    
    
                return DefaultDocumentFormatRegistry.TXT;
            }

            @Override
            public InputStream getInputStream(InputStream inputStream) throws IOException {
    
    
                //因为会出现中文乱码问题,所以先通过字符流进行编码转换,再转换成字节流
                try (final BufferedReader bis = new BufferedReader(new InputStreamReader(inputStream, "GBK")))
                {
    
    
                    StringBuffer buf = new StringBuffer();
                    String temp;
                    while ((temp = bis.readLine()) != null)
                    {
    
    
                        buf.append(temp).append(System.getProperty("line.separator"));
                    }
                    return new ByteArrayInputStream(buf.toString().getBytes());
                }
            }
        };

        public InputStream getInputStream(InputStream inputStream) throws IOException {
    
    
            return inputStream;
        }

        public abstract DocumentFormat getFormFormat();

        public DocumentFormat getTargetFormat() {
    
    
            return DefaultDocumentFormatRegistry.PDF;
        }
    }
}

 @PostMapping("/upload")
    public void upload(MultipartFile file, HttpServletResponse response) throws Exception {
    
    
        final String fileSuffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream())
        {
    
    
            try
            {
    
    
                // 文件扩展名匹配了转换服务内的扩展名,则调用转换服务进行转换pdf
                final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum = OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                if (!Objects.isNull(documentFormatEnum))
                {
    
    
                    officeConvertToPdfService.convert(file.getInputStream(), bos, fileSuffix);
                }
            } catch (IllegalArgumentException e)
            {
    
    
                bos.reset();
                try (InputStream inputStream = file.getInputStream())
                {
    
    
                    bos.write(file.getBytes(), 0, file.getBytes().length);
                }
            }
            bos.close();
            final byte[] bytes = bos.toByteArray();
            response.setCharacterEncoding("UTF-8");
            // response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getOriginalFilename().getBytes("UTF-8"), "ISO-8859-1")); //
            response.setHeader("Content-Length", String.valueOf(bytes.length));
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_42456784/article/details/130408167