上一个博客已经对aspose开发的准备工作说完了。
1.封装获取Presentation的方法
private static final Logger LOGGER = LoggerFactory.getLogger(OfficeTransferUtil.class);
private static Presentation presentation = null;
private static final String license = "\n" +
" \n" +
" \n" +
" Aspose.Total for Java \n" +
" Aspose.Words for Java \n" +
" \n" +
" Enterprise \n" +
" 20991231 \n" +
" 20991231 \n" +
" 8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7 \n" +
" \n" +
" sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU= \n" +
" ";
/**
* @param sourceFilePath ppt文件资源路径
* @return
*/
public static Presentation getPresentationFromSourcePPT(String sourceFilePath) {
if (presentation == null) {
ByteArrayInputStream is = new ByteArrayInputStream(license.getBytes());
com.aspose.slides.License license = new com.aspose.slides.License();
license.setLicense(is);
presentation = new Presentation(sourceFilePath);
}
return presentation;
}
2. ppt,pptx转图片的方法。
这一步是和poi唯一不同的一步,即实现ppt生成图片的方式不一样。这里用的是apose的 ISlide ,第二步图片转pdf是同一个方法。
/**
* @param sourceFilePath 资源文件路径
* @param pptType ppt的类型:ppt,pptx
* @return
*/
public static List convertPptToImages(String sourceFilePath, String pptType) {
long startTime = System.currentTimeMillis();
List pngFileList = new ArrayList<>();
Presentation pres = getPresentationFromSourcePPT(sourceFilePath);
ISlideCollection slides = pres.getSlides();
int idx = 1;
for (int i = 0; i < slides.size(); i++) {
ISlide slide = slides.get_Item(i);
int height = (int) (pres.getSlideSize().getSize().getHeight() - 150);
int width = (int) (pres.getSlideSize().getSize().getWidth() - 150);
BufferedImage img = slide.getThumbnail(new java.awt.Dimension(width, height));
FileOutputStream out = null;
File pngFile = null;
try {
if ("ppt".equalsIgnoreCase(pptType)) {
pngFile = new File(sourceFilePath.replace(".ppt", String.format("-%04d.png", idx++)));
} else {
pngFile = new File(sourceFilePath.replace(".pptx", String.format("-%04d.png", idx++)));
}
out = new FileOutputStream(pngFile);
ImageIO.write(img, "png", out);
pngFileList.add(pngFile);
} catch (Exception e) {
LOGGER.error("{}2Png exception:{}", pptType, e);
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (img != null) {
img.flush();
}
} catch (IOException e) {
LOGGER.error("{}2Png close exception:{}", pptType, e);
}
}
}
long endTime = System.currentTimeMillis();
LOGGER.info("PPT转PNG耗时:{}", endTime - startTime);
return pngFileList;
}
3.将png转pdf
/**
* @param pngFiles png格式的图片文件
* @param pdfFilePath 指定pdf的文件路径
* @param watermarkPath 水印的图片地址
* @return
*/
public static File coverPng2Pdf(List pngFiles, String pdfFilePath, String watermarkPath) {
long startTime = System.currentTimeMillis();
Document document = new Document();
File tempPdfFile = null;
FileOutputStream fileOutputStream = null;
try {
String tempPdfFilePath = pdfFilePath.replace(".pdf", ".in.pdf");
tempPdfFile = new File(tempPdfFilePath);
fileOutputStream = new FileOutputStream(tempPdfFile);
PdfWriter.getInstance(document, fileOutputStream);
document.open();
pngFiles.forEach(pngFile -> {
try {
com.itextpdf.text.Image png = Image.getInstance(pngFile.getCanonicalPath());
png.scalePercent(90f);
document.add(png);
} catch (Exception e) {
LOGGER.error("png2Pdf exception", e);
}
});
document.close();
fileOutputStream.flush();
// 添加水印
boolean ret = PDFWatermarkUtil.addWatermark(tempPdfFilePath, pdfFilePath, watermarkPath);
long endTime = System.currentTimeMillis();
LOGGER.info("PNG转PDF并加上水印耗时:{}", endTime - startTime);
if (ret) {
File pdfFile = new File(pdfFilePath);
return pdfFile;
}
} catch (Exception e) {
LOGGER.error(String.format("png2Pdf %s exception", pdfFilePath), e);
} finally {
try {
if (document.isOpen()) {
document.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (tempPdfFile != null) {
tempPdfFile.delete();
}
} catch (IOException e) {
LOGGER.error("fileOutputStream close false:{}", e);
}
}
return null;
}
4.下面是直接将ppt转pdf的方法
/**
* @param sourceFilePath ppt文件资源路径
* @param watermarkPath pdf水印文件路径
* @return
*/
public static File convertPPTToPDF(String sourceFilePath, String watermarkPath) {
String extension = "";
long startTime = System.currentTimeMillis();
Integer index = sourceFilePath.lastIndexOf(".");
if (index > 0) {
extension = sourceFilePath.substring(index + 1);
}
if (extension.equals("ppt") || extension.equals("pptx")) {
String outputTempPdfFilePath = sourceFilePath.substring(0, index) + ".temp.pdf";
File tempPdfFile = new File(outputTempPdfFilePath);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(tempPdfFile);
Presentation pres = getPresentationFromSourcePPT(sourceFilePath);
pres.save(fileOutputStream, com.aspose.slides.SaveFormat.Pdf);
fileOutputStream.flush();
LOGGER.info("Powerpoint file converted to PDF successfully!");
long endTime = System.currentTimeMillis();
LOGGER.info("PPT转PDF耗时:{}", endTime - startTime);
String pdfFilePath = outputTempPdfFilePath.replace(".temp.pdf", ".pdf");
// 添加水印,这个时候pdf文件已经有了。
boolean ret = PDFWatermarkUtil.addWatermark(outputTempPdfFilePath, pdfFilePath, watermarkPath);
if (ret) {
File pdfFile = new File(pdfFilePath);
return pdfFile;
}
} catch (Exception e) {
LOGGER.error("ppt,pptx转pdf异常:{}", e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
//删除 .temp.pdf的文件
if (tempPdfFile.exists()) {
tempPdfFile.delete();
}
} catch (IOException e) {
LOGGER.error("关闭输出流异常:{}", e);
}
}
}
return null;
}