2020-12-26 02:31:34 +08:00
|
|
|
package cn.keking.service;
|
2020-05-15 18:09:19 +08:00
|
|
|
|
2018-01-17 14:10:40 +08:00
|
|
|
import org.artofsolving.jodconverter.OfficeDocumentConverter;
|
|
|
|
|
import org.springframework.stereotype.Component;
|
2020-05-15 18:09:19 +08:00
|
|
|
|
2018-01-17 14:10:40 +08:00
|
|
|
import java.io.File;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @author yudian-it
|
|
|
|
|
*/
|
|
|
|
|
@Component
|
2020-12-26 02:31:34 +08:00
|
|
|
public class OfficeToPdfService {
|
2020-12-26 19:13:50 +08:00
|
|
|
private final OfficePluginManager officePluginManager;
|
2020-05-15 18:09:19 +08:00
|
|
|
|
2020-12-26 19:13:50 +08:00
|
|
|
public OfficeToPdfService(OfficePluginManager officePluginManager) {
|
|
|
|
|
this.officePluginManager = officePluginManager;
|
2020-05-15 18:09:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void openOfficeToPDF(String inputFilePath, String outputFilePath) {
|
|
|
|
|
office2pdf(inputFilePath, outputFilePath);
|
2018-01-17 14:10:40 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static void converterFile(File inputFile, String outputFilePath_end,
|
|
|
|
|
OfficeDocumentConverter converter) {
|
|
|
|
|
File outputFile = new File(outputFilePath_end);
|
|
|
|
|
// 假如目标路径不存在,则新建该路径
|
|
|
|
|
if (!outputFile.getParentFile().exists()) {
|
|
|
|
|
outputFile.getParentFile().mkdirs();
|
|
|
|
|
}
|
|
|
|
|
converter.convert(inputFile, outputFile);
|
|
|
|
|
}
|
|
|
|
|
|
2020-05-15 18:09:19 +08:00
|
|
|
|
|
|
|
|
public void office2pdf(String inputFilePath, String outputFilePath) {
|
2020-12-26 19:13:50 +08:00
|
|
|
OfficeDocumentConverter converter = officePluginManager.getDocumentConverter();
|
2018-01-17 14:10:40 +08:00
|
|
|
if (null != inputFilePath) {
|
|
|
|
|
File inputFile = new File(inputFilePath);
|
|
|
|
|
// 判断目标文件路径是否为空
|
|
|
|
|
if (null == outputFilePath) {
|
|
|
|
|
// 转换后的文件路径
|
|
|
|
|
String outputFilePath_end = getOutputFilePath(inputFilePath);
|
2020-05-15 18:09:19 +08:00
|
|
|
if (inputFile.exists()) {
|
|
|
|
|
// 找不到源文件, 则返回
|
|
|
|
|
converterFile(inputFile, outputFilePath_end,converter);
|
2018-01-17 14:10:40 +08:00
|
|
|
}
|
|
|
|
|
} else {
|
2020-05-15 18:09:19 +08:00
|
|
|
if (inputFile.exists()) {
|
|
|
|
|
// 找不到源文件, 则返回
|
|
|
|
|
converterFile(inputFile, outputFilePath, converter);
|
2018-01-17 14:10:40 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static String getOutputFilePath(String inputFilePath) {
|
2020-05-15 18:09:19 +08:00
|
|
|
return inputFilePath.replaceAll("."+ getPostfix(inputFilePath), ".pdf");
|
2018-01-17 14:10:40 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static String getPostfix(String inputFilePath) {
|
|
|
|
|
return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|