SpringBoot集成jodconverter
在SpringBoot项目中集成jodconvert+LibreOffice实现office文档转pdf
<!-- 核心包 -->
<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>
在application.properties中的添加配置
jodconverter.local.officeHome=C:/Program Files/LibreOffice #所在主机IP jodconverter.local.hostName=127.0.0.1 # 开启多个LibreOffice进程,每个端口对应一个进程 jodconverter.local.portNumbers=8102 # LibreOffice进程重启前的最大进程数 jodconverter.local.maxTasksPerProcess=5 #超时时间 jodconverter.local.processTimeout=120000
编写Spring配置类
@Slf4j
@Configuration
@ConfigurationProperties(value = "jodconverter.local")
public class JodconverterConfig {
private LocalOfficeManager officeManager;
@Value("${jodconverter.local.officeHome}")
private String officeHome;
@Value("${jodconverter.local.hostName}")
private String hostName;
@Value("${jodconverter.local.portNumbers}")
private String portNumbers;
@Value("${jodconverter.local.maxTasksPerProcess}")
private Integer maxTasksPerProcess;
@Value("${jodconverter.local.processTimeout}")
private Long processTimeout;
/**
* 启动Office组件进程
*
* @return
*/
@PostConstruct
public OfficeManager officeManager() {
// 多个端口处理
String[] portsString = portNumbers.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")
.hostName(hostName)
.portNumbers(ports)
.processTimeout(processTimeout)
.maxTasksPerProcess(maxTasksPerProcess)
.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);
}
}
}
编写controller
@RestController
@RequestMapping("/file")
public class FileConverterController {
String PATH = "C:/Users/Administrator/Desktop/importTest/test/";
@Resource
DocumentConverter documentConverter;
@RequestMapping("/convert")
public String convert(@RequestParam("file") MultipartFile file) throws OfficeException, IOException {
if (file.isEmpty()) {
return "请选择上传文件";
}
// 保存上传文件
String originalFilePath = PATH + file.getOriginalFilename();
File localFile = new File(originalFilePath);
try (OutputStream os = new FileOutputStream(localFile)) {
os.write(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
return "转换异常";
}
//刷新,将excel的表头都放置在同一页pdf
String newExcelPath = PATH+UUID.randomUUID().toString().replace("-", "")+".xlsx";
File newExcelFile = new File(newExcelPath);
refresh(localFile,"xlsx",newExcelFile);
// 转换成pdf的名称
String pdfName = UUID.randomUUID().toString().replace("-", "");
// 转换成pdf存放路径
File pdfFile = new File(PATH + pdfName + ".pdf");
// 开始转换
documentConverter.convert(newExcelFile)
.to(pdfFile).as(DefaultDocumentFormatRegistry.PDF)
.execute();
// 返回转换后的pdf文件的URL
Map<String,Object> map = new HashMap<>();
map.put("path",pdfFile.getAbsolutePath());
return JSON.toJSONString(map);
}
public static void refresh(File oldFilePath, String oldType, File newFilePath) throws IOException {
if (!"xlsx".equals(oldType)) {
throw new RuntimeException("仅支持xlsx");
} else {
Workbook workbook = null;
workbook = new XSSFWorkbook(new FileInputStream(oldFilePath));
Integer sheetCount = workbook.getNumberOfSheets();
for(int i = 0; i < sheetCount; ++i) {
Sheet sheet = workbook.getSheetAt(i);
XSSFPrintSetup printSetup = (XSSFPrintSetup)sheet.getPrintSetup();
printSetup.setFitHeight((short)0);
sheet.setFitToPage(true);
}
workbook.write(new FileOutputStream(newFilePath));
}
}
}
查看12道真题和解析