协会
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
package io.v.nutz.base.utils;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import com.aspose.cells.PdfSaveOptions;
|
||||
import com.aspose.cells.Workbook;
|
||||
import com.aspose.words.Document;
|
||||
import com.aspose.words.SaveFormat;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 文档转换
|
||||
*/
|
||||
@Slf4j
|
||||
public class OfficePlusUtil {
|
||||
|
||||
/**
|
||||
* 转换
|
||||
*
|
||||
* @param sourcePath 源文件路径
|
||||
* @param targetPath 目标文件路径
|
||||
*/
|
||||
public static void convert(String sourcePath, String targetPath) {
|
||||
String suffix = FileUtil.getSuffix(sourcePath);
|
||||
if (suffix.equals("doc") || suffix.equals("docx")) {
|
||||
wordConvertPdf(sourcePath, targetPath);
|
||||
} else if (suffix.equals("xls") || suffix.equals("xlsx")) {
|
||||
excelConvertPdf(sourcePath, targetPath);
|
||||
} else {
|
||||
throw new RuntimeException("不支持的文档格式");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* excel转pdf
|
||||
*
|
||||
* @param sourcePath 源文件路径
|
||||
* @param targetPath 目标文件路径
|
||||
*/
|
||||
public static void excelConvertPdf(String sourcePath, String targetPath) {
|
||||
FileOutputStream fileOS = null;
|
||||
try {
|
||||
Workbook wb = new Workbook(sourcePath);
|
||||
fileOS = new FileOutputStream(targetPath);
|
||||
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
|
||||
pdfSaveOptions.setOnePagePerSheet(true);
|
||||
// for (int i = 0; i < 3; i++) {
|
||||
// wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
|
||||
// wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
|
||||
// }
|
||||
// for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
|
||||
// wb.getWorksheets().get(i).setVisible(false);
|
||||
// }
|
||||
wb.getWorksheets().get(0).setVisible(true);
|
||||
wb.save(fileOS, pdfSaveOptions);
|
||||
fileOS.flush();
|
||||
} catch (Exception e) {
|
||||
log.info("转换pdf报错", e);
|
||||
} finally {
|
||||
if (fileOS != null) {
|
||||
try {
|
||||
fileOS.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* word转pdf
|
||||
*
|
||||
* @param sourcePath 源文件路径
|
||||
* @param targetPath 目标文件路径
|
||||
*/
|
||||
public static void wordConvertPdf(String sourcePath, String targetPath) {
|
||||
FileOutputStream os = null;
|
||||
try {
|
||||
File file = new File(targetPath);
|
||||
os = new FileOutputStream(file);
|
||||
Document doc = new Document(sourcePath);
|
||||
doc.save(os, SaveFormat.PDF);
|
||||
} catch (Exception e) {
|
||||
log.info("转换pdf报错", e);
|
||||
} finally {
|
||||
try {
|
||||
os.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user