java将office转换为的思路:借助第三方的插件;
1、项目中先引入jar包:
解释一下:aspose-cells.jar是用来Excel的转换的,aspose-slides.jar是用来PPT转换的,aspose-word是用来word转换的,license.xml是用来去水印的,这里暂时只有word去水印的。
2、新建一个转换的工具类:基本不用改,复制就能用。
public class YdUtils {
//校验license
private static boolean judgeLicense() {
boolean result = false;
try {
InputStream is = YdUtils.class.getResourceAsStream("/lib/license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void trans(String filePath, String pdfPath, String type) {
if (!judgeLicense()) {
System.out.println("license错误");
}
try {
System.out.println("as开始:" + filePath);
long old = System.currentTimeMillis();
File file = new File(pdfPath);
toPdf(file, filePath, type);
long now = System.currentTimeMillis();
System.out.println("完成:" + pdfPath);
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void toPdf(File file, String filePath, String type) {
if ("word".equals(type) || "txt".equals(type)) {
wordofpdf(file, filePath);
} else if ("excel".equals(type)) {
exceOfPdf(file, filePath);
} else if ("ppt".equals(type)) {
pptofpdf(file, filePath);
}else{
System.out.println("暂不支持该类型:"+type);
}
}
private static void wordofpdf(File file, String filePath) {
FileOutputStream os = null;
Document doc;
try {
os = new FileOutputStream(file);
doc = new Document(filePath);
doc.save(os, com.aspose.words.SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void exceOfPdf(File file, String filePath) {
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
Workbook wb = new Workbook(filePath);
wb.save(os, com.aspose.cells.SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void pptofpdf(File file, String filePath) {
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
Presentation pres = new Presentation(filePath);// 输入pdf路径
pres.save(os, SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、实际调用:这里需要做下判断,不同类型的文件需要传入不同的参数,YdUtils就是转换的工具类,trans就是转换方式,类型的参数不一样而已。第一个参数是需要转换的文件路径,第二个参数是转换成的PDF放在哪,第三个参数就是文件类型。
if (".pdf".equals(str)) {
// 如果本身就是pdf
s2 = scwj;
} else if (".xlsx".equals(str) || ".xls".equals(str)) {
YdUtils.trans(scwj,rootPath.substring(0,7) + "/pdf/" + s + ".pdf","excel");
} else if (".doc".equals(str) || ".docx".equals(str) || ".txt".equals(str)){
YdUtils.trans(scwj,rootPath.substring(0,7) + "/pdf/" + s + ".pdf","word");
} else if (".ppt".equals(str) || ".pptx".equals(str)){
YdUtils.trans(scwj,rootPath.substring(0,7) + "/pdf/" + s + ".pdf","ppt");
}
4、直接调用,即可生成。附jar包下载,含license文件