springboot+openoffice+jodconverter实现文档在线预览

  1. 引入依赖
<dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    <dependency>
        <groupId>org.jodconverter</groupId>
        <artifactId>jodconverter-spring-boot-starter</artifactId>
        <version>4.2.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <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>
  1. application.properties配置
jodconverter.local.enabled=true
jodconverter.local.port-numbers=8100
  1. controller代码
@Controller
public class 	MyController {
    // 第一步:转换器直接注入
    @Autowired
    private DocumentConverter converter;
    @Autowired
    private HttpServletResponse response;
    @RequestMapping("toPdfFile")
    public String toPdfFile() {
    //该编码方式只适用于window10本地安装openoffice,不适用docker镜像的openoffice,因为镜像基于linux系统,你的操作文件/目录在window,和镜像不在一台机器,所以就会报404,url错误
		File file = new File("D:/aa.doc");//需要转换的文件
	try {
	    File newFile = new File("D:/obj-pdf");//转换之后文件生成的地址
	    if (!newFile.exists()) {
		newFile.mkdirs();
	    }
	    //文件转化
	    converter.convert(file).to(new File("D:/obj-pdf/hello.pdf")).execute();
	    //使用response,将pdf文件以流的方式发送的前段
	    ServletOutputStream outputStream = response.getOutputStream();
	    InputStream in = new FileInputStream(new File("D:/obj-pdf/hello.pdf"));// 读取文件
	    // copy文件
	    int i = IOUtils.copy(in, outputStream);
	    System.out.println(i);
	    in.close();
	    outputStream.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return "This is to pdf";
    }
}
  1. 下载openoffice
    4.1 window10版openoffice(该方式可用上述的controller代码测试)
    http://www.openoffice.org/download/
    下载可自定义安装目录,也可使用默认的路径在:
    在这里插入图片描述
    执行如下命令启动:
    soffice -headless -accept=“socket,host=0.0.0.0,port=8100;urp;” -nofirststartwizard

    4.2 如果基于docker的openoffice镜像

    version: "3.3"
    services:
    	openoffice:
       		image: "rafaeltuelho/openoffice3-daemon"
       		ports:
       			- 8100:8100
       		command: /opt/openoffice.org3/program/soffice -headless -nofirststartwizard  -accept="socket,host=0.0.0.0,port=8100;urp;"
    

    代码如下

public void preview(Long fileId, HttpServletResponse response) {
        FileEntity fileData = fileMapper.selectOne(new QueryWrapper<FileEntity>().eq("file_id", fileId));
        String fileName = fileData.getFileName();
        byte[] fileByte=FastDFSClient.getFileByte(fileData);
            //获得文件名后缀
            String suffix = "";
            if (StringUtils.isNotBlank(fileName) && fileName.contains(".")) {
                suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
            }

            if (StringUtils.isBlank(suffix)) {
                throw new OutOfBusinessException("文件预览失败");
            }

            String[] suffixs = new String[]{"DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX", "TXT"};


            if (Arrays.asList(suffixs).contains(suffix)) {
                File tempFile = null;
                try {
                    tempFile = File.createTempFile(UUID.randomUUID().toString(), "." + suffix);
                    FileOutputStream fos = new FileOutputStream(tempFile);
                    fos.write(fileByte, 0, fileByte.length);
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }


                String filePath = tempFile.getPath();

                //转换之后的文件
                File pdfFile = new File(filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf");

                //打开OpenOffice连接
                OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1",8100);
                try {
                    connection.connect();
                    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
                    converter.convert(tempFile, pdfFile);
                    connection.disconnect();

                    filePath = pdfFile.getPath();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new OutOfBusinessException("文件转换失败");
                } finally {
                    try {
                        //发生exception时, connection不会自动切断, 程序会一直挂着
                        if (connection != null) {
                            connection.disconnect();
                            connection = null;
                        }
                    } catch (Exception e) {
                    }
                }
                response.setContentType("application/pdf");
                //将文件写入输出流,显示在界面上,实现预览效果
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(filePath);

                    byte[] byt = new byte[fis.available()];
                    fis.read(byt);
                    writeBytesToOut(response.getOutputStream(), byt, 4096);
                    tempFile.delete();
                    pdfFile.delete();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //预览
                response.setContentType(fileData.getFileType());
                try {
                    writeBytesToOut(response.getOutputStream(), fileByte, 4096);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值