SpringBoot + LibreOffice + Hutool 实现附件预览简单示例

1. 简介

  在日常开发中,经常会遇到需要预览附件的需求,如果附件类型为图片、文本、PDF或者网页文件,则直接可以在浏览器预览;如果附件类型为Word、Excel、PPT等文件,则需要通过工具转换为PDF后在浏览器预览。
  本博客使用LibreOffice和Hutool实现文件预览简单示例。
  LibreOffice官网:https://zh-cn.libreoffice.org/

2. 安装Libreoffice
  • Windows安装
  • Linux安装
    • yum安装
    yum -y install libreoffice
    # 安装后的目录为:/usr/lib64/libreoffice
    • 乱码问题
    # 上传Windows的C:\Windows\Fonts目录中的字体到Linux的/usr/share/fonts/windows目录
    # 执行授权
    chmod 644 /usr/share/fonts/windows/* && fc-cache -fv
  • 官网安装手册https://zh-cn.libreoffice.org/get-help/install-howto/
3. 示例代码
  • 创建工程
  • 修改pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.c3stones</groupId>
	<artifactId>spring-boot-libreoffice-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-libreoffice-demo</name>
	<description>Spring Boot Libreoffice Demo</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath />
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-spring-boot-starter</artifactId>
			<version>4.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-local</artifactId>
			<version>4.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-core</artifactId>
			<version>4.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.libreoffice</groupId>
			<artifactId>ridl</artifactId>
			<version>7.2.0</version>
		</dependency>
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.7.13</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
  • 创建配置文件application.yml
server:
  port: 8080

spring:
  thymeleaf:
    prefix: classpath:/view/
    suffix: .html
    encoding: UTF-8
    servlet:
      content-type: text/html
    cache: false
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB

# 附件预览
jodconverter:
  local:
    enabled: true
#   # 设置LibreOffice目录
    officeHome: D:\LibreOffice
#   # CentOS 下安装 LibreOffice:
#   # 1、安装:yum -y install libreoffice
#   # 2、配置:officeHome: /usr/lib64/libreoffice
#   # Linux 中文字体乱码解决:
#   # 1、上传 C:\Windows\Fonts 下的字体到 /usr/share/fonts/windows 目录
#   # 2、执行命令: chmod 644 /usr/share/fonts/windows/* && fc-cache -fv
#   # 监听端口,开启多个LibreOffice进程,每个端口对应一个进程
#   portNumbers: 8100,8101,8102
    portNumbers: 2002
#   # LibreOffice进程重启前的最大进程数
    maxTasksPerProcess: 10
#   # 任务在转换队列中的最大生存时间,默认30s
    taskQueueTimeout: 30
  • 创建Controller
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.office.OfficeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 附件预览Controller
 * 
 * @author CL
 *
 */
@Controller
@RequestMapping(value = "/file")
public class FilePreviewController {

	private static final Logger log = LoggerFactory.getLogger(FilePreviewController.class);

	@Autowired
	private DocumentConverter documentConverter;

	/**
	 * 跳转到附件预览和下载页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "")
	public String index() {
		return "fileIndex";
	}

	/**
	 * 附件预览
	 * 
	 * @param file     附件
	 * @param response
	 */
	@RequestMapping(value = "/preview")
	@ResponseBody
	public void preview(MultipartFile file, HttpServletResponse response) {
		if (file == null) {
			return;
		}
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = file.getInputStream();
			outputStream = response.getOutputStream();
			String fileName = file.getOriginalFilename();
			if (StrUtil.endWithAnyIgnoreCase(fileName, ".doc", ".docx", ".xls", ".xlsx", ".csv", ".ppt", ".pptx")) {
				// 转为PDF
				documentConverter.convert(inputStream).to(outputStream)
						.as(documentConverter.getFormatRegistry().getFormatByExtension("pdf")).execute();
			} else if (StrUtil.endWithAnyIgnoreCase(fileName, ".pdf", ".txt", ".xml", ".md", ".json", ".html", ".htm",
					".gif", ".jpg", ".jpeg", ".png", ".ico", ".bmp")) {
				IoUtil.copy(inputStream, outputStream);
			} else {
				outputStream.write("暂不支持预览此类型附件".getBytes());
			}
		} catch (IORuntimeException e) {
			log.error("附件预览IO运行异常:{}", e.getMessage());
		} catch (IOException e) {
			log.error("附件预览IO异常:{}", e.getMessage());
		} catch (OfficeException e) {
			log.error("附件预览Office异常:{}", e.getMessage());
		} finally {
			IOUtils.closeQuietly(inputStream);
		}
		IoUtil.writeUtf8(outputStream, true);
	}

}
  • 创建附件预览示例页面
      在resources下新建目录view,在view目录下新建页面:fileIndex.html
<html>
<head>
	<title>附件预览和下载</title>
</head>
<body>
	<h5>支持附件类型为:.doc, .docx, .xls, .xlsx, .csv, .ppt, .pptx, .pdf, .txt, .xml, .md, .json, .gif, .jpg, .jpeg, .png, .ico, .bmp</h5>
	<form id="fileForm" action="" method="post" enctype="multipart/form-data">
		<i style="color: red">*</i> 上传附件:<input id="file" name="file" type="file" /><br/>
	</form>
	<button onclick="preview()">预览</button>
</body>
</html>
<script>
// 预览方法
function preview() {
	// 检查是否为空和大小限制
	var file = document.getElementById('file').files[0];
	if (!file) {
		alert("附件不能为空");
		return;
	}
	var fileSize = file.size;
	if (fileSize > 50 * 1024 * 1024) {
		alert("最大支持附件大小为 50MB");
		return;
	}
	
	// 提交表单
	var fileForm = document.getElementById('fileForm');
	fileForm.action = "[[@{/}]]file/preview";  
	fileForm.submit();
}
</script>
  • 创建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 启动类
 * 
 * @author CL
 *
 */
@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}
4. 测试
  • 启动项目
  • 浏览器访问:http://127.0.0.1:8080/file
  • 测试预览图片
  • 测试预览文本
  • 测试预览Word文件
  • 测试预览PPT文件
  • 测试预览PDF
5. 项目地址

  spring-boot-libreoffice-demo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
计算机硬件系统: 计算机硬件系统是构成计算机物理实体的所有部件的集合,包括核心组件以及外设。其主要组成部分包括: 中央处理单元 (CPU):作为计算机的大脑,负责执行指令、进行逻辑运算和数据处理。 内存:包括随机访问内存 (RAM) 和只读存储器 (ROM),用于临时或永久地存储程序和数据供CPU快速访问。 存储设备:如硬盘、固态硬盘 (SSD)、光盘驱动器等,用于长期保存大量的程序和数据。 输入/输出设备:如键盘、鼠标、显示器、打印机、扫描仪、摄像头等,实现人与计算机之间的交互以及数据的输入和输出。 主板:连接和协调各硬件组件工作,包含芯片组、扩展插槽、接口等。 其他外设:如声卡、网卡、显卡等,提供特定功能支持。 计算机软件系统: 软件系统是指在硬件之上运行的各种程序和数据的集合,分为两大类: 系统软件: 操作系统 (OS):如Windows、macOS、Linux、Unix等,是管理和控制计算机硬件与软件资源、提供公共服务、协调计算机各部分工作的基础平台,是用户与计算机硬件之间的桥梁。 驱动程序:为特定硬件设备提供接口,使操作系统能够识别和控制这些设备。 实用工具:如编译器、链接器、调试器、文件管理器等,协助开发、维护和管理计算机系统。 应用软件: 办公套件:如Microsoft Office、LibreOffice,包括文字处理、电子表格、演示文稿等工具。 专业软件:如AutoCAD(工程制图)、Adobe Creative Suite(图形设计与多媒体编辑)、MATLAB(数值计算与数据分析)等,针对特定行业或任务的专业应用。 互联网应用:如浏览器、电子邮件客户端、即时通讯软件、社交媒体平台等。 游戏:休闲游戏、网络游戏、模拟游戏等各类娱乐软件。 信息系统: 在企业、机构或组织中,信息系统是指由硬件、软件、人员、数据资源、通信网络等组成的,用于收集、处理、存储、分发和管理信息,以支持决策制定、业务运营和战略规划的系统。这类系统包括: 数据库管理系统 (DBMS):如Oracle、MySQL、SQL Server,用于创建、维护和查询结构化数据。 企业资源计划 (ERP):整合企业的财务、供应链、人力资源、生产等多方面管理功能的综合性信息系统。 客户关系管理 (CRM):用于管理与客户互动的全过程,提升销售、营销和服务效率。 供应链管理 (SCM):优化供应链流程,包括采购、库存、物流、分销等环节。 决策支持系统 (DSS):辅助决策者分析复杂问题,提供数据驱动的决策建议。 网络系统: 包括局域网 (LAN)、广域网 (WAN)、互联网 (Internet) 等,通过路由器、交换机、调制解调器等网络设备,以及通信协议(如TCP/IP),实现计算机之间的数据传输和资源共享。 分布式系统: 由多台计算机通过网络互相协作,共同完成一项任务的系统。分布式系统可以提供高可用性、可扩展性、负载均衡等优点,如云计算平台、分布式数据库、区块链系统等。 安全系统: 旨在保护计算机系统免受恶意攻击、未经授权访问、数据泄露等安全威胁的措施和工具,包括防火墙、入侵检测系统、防病毒软件、身份认证与访问控制机制、数据加密技术等。 综上所述,计算机领域的“系统”概念广泛涉及硬件架构、软件层次、信息管理、网络通信、分布式计算以及安全保障等多个方面,它们相互交织,共同构成了现代计算机技术的复杂生态系统。
下面是一个示例代码,演示如何在Spring Boot中使用LibreOffice实现文档转换: 首先,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.artofsolving</groupId> <artifactId>jodconverter-core</artifactId> <version>3.0-beta-4</version> </dependency> ``` 然后,在Java类中注入LibreOffice相关的配置: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class LibreOfficeConfig { @Value("${libreoffice.home:}") private String officeHome; @Bean public LibreOfficeConverter libreOfficeConverter() { return new LibreOfficeConverter(officeHome); } } ``` 在上述代码中,我们使用了@Value注解来获取配置文件中的"libreoffice.home"属性值,并将其注入到officeHome字段中。然后,我们创建了一个名为"libreOfficeConverter"的Bean,用于将文档转换为PDF格式。 最后,我们可以在Controller中使用此Bean来实现文档转换: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; @RestController public class DocumentController { @Autowired private LibreOfficeConverter libreOfficeConverter; @PostMapping("/convert") public String convertDocument(@RequestParam("src") String srcPath, @RequestParam("dest") String destPath) throws IOException { File inputFile = new File(srcPath); File outputFile = new File(destPath); FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); libreOfficeConverter.convert(inputStream, outputFile); inputStream.close(); outputStream.close(); return "Document converted successfully!"; } } ``` 在上述代码中,我们注入了之前创建的"libreOfficeConverter" Bean,并在convertDocument方法中使用它来将文档从输入流转换为PDF格式。最后,我们关闭了输入流和输出流,并返回一个成功转换的提示消息。 需要注意的是,上述代码仅供参考,具体实现可能因环境和需求而异。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值