Java-基于Aspose方式将office文件转换成pdf格式
原始需求
首先说一下需求,java-web项目某页面,用户可上传office(wrod、excel、ppt)文档,上传后的文档名在页面展示,需要提供word文档的在线预览、下载功能。
产品要求不能使用第三方软件实现,因为这种实现方式效率不高,所以需要使用“纯Java代码”实现。同时也对跨平台有要求,系统需要运行在linux系统上。综合现阶段发现的方案,决定采用基于Aspose的方式进行实现。
一、Aspose方式转pdf的优缺点
结论
使用Aspose效果最好。
各种技术实现起来,综合来说Aspose是比较好的方案,唯一的缺点就是jar包收费,但是可以找到破解版的jar包资源。
二、实现步骤
1.下载jar包
office文件转pdf格式需要引入相关jar包:
aspose.slides-15.9.0.jar
aspose-cells-8.5.2.jar
aspose-words-16.8.0-javadoc.jar
aspose-words-16.8.0-jdk16.jar
直接将lib包放在src/main/webapp/lib/中
<!--aspose-cells-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>Cells</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<!--systemPath为具体的包的放置路径,可根据项目进行具体修改-->
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aspose-cells-8.5.2.jar</systemPath>
</dependency>
<!--aspose-Words-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>Words</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aspose-words-16.8.0-javadoc.jar</systemPath>
</dependency>
<!--aspose-Words16-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>Words16</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aspose-words-16.8.0-jdk16.jar</systemPath>
</dependency>
<!--aspose-slides-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>slides</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aspose.slides-15.9.0.jar</systemPath>
</dependency>
2.引入License.xml文件
将其放入项目中,优化后可以自定义位置。具体看代码
3.java代码编写
创建AsposeUtils工具类,方便项目中的调用
public class AsposeUtils {
private static final Logger logger = LoggerFactory.getLogger(AsposeUtils.class);
/**
*
* @param classPath
* @return
*/
public static boolean getLicense(String classPath) {
boolean result = false;
try {
InputStream is = AsposeUtils.class.getResourceAsStream("/license.xml");
Class clazz = Class.forName(classPath);
Object obj = clazz.newInstance();
clazz.getMethod("setLicense", InputStream.class).invoke(obj, is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 判断文件类型调用转换方法
* @param filePath
* @param pdfPath
* @throws Exception
* @return
*/
public static int officesToPdf(String filePath, String pdfPath, String type) throws Exception {
if (".doc".equals(type) || ".docx".equals(type)) {
wordToPdf(filePath, pdfPath);
} else if (".xls".equals(type) || ".xlsx".equals(type)) {
excelToPDF(filePath, pdfPath);
} else if ( ".ppt".equals(type) || ".pptx".equals(type)) {
pptToPDF(filePath, pdfPath);
}else{
logger.error("暂不支持该类型:"+type);
}
return 0;
}
/**
* wordToPdf
* @param wordPath
* @param pdfPath
*/
private static void wordToPdf(String wordPath,String pdfPath) {
// 验证License
if (!getLicense("com.aspose.words.License")) {
return;
}
try {
long old = System.currentTimeMillis();
Document doc = new Document(wordPath);// 原始word路径
File pdfFile = new File(pdfPath);// 输出路径
FileOutputStream fileOS = new FileOutputStream(pdfFile);
doc.save(fileOS, SaveFormat.PDF);
long now = System.currentTimeMillis();
logger.info("word转pdf成功,共耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* excelToPDF
* @param filePath
* @param pdfPath
* @throws Exception
*/
private static void excelToPDF(String filePath, String pdfPath) throws Exception {
if (!getLicense("com.aspose.cells.License")) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
long old = System.currentTimeMillis();
Workbook wb = new Workbook(filePath);// 原始excel路径
FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
int[] autoDrawSheets={3};
//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
autoDraw(wb,autoDrawSheets);
//隐藏workbook中不需要的sheet页,自定义需要展示的sheet页,showSheets为存放的需要转换的sheet页
int[] showSheets={0};
printSheetPage(wb,showSheets);
wb.save(fileOS, pdfSaveOptions);
fileOS.close();
long now = System.currentTimeMillis();
logger.info("excel转pdf成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* pptToPDF
* @param filePath
* @param pdfPath
* @throws Exception
*/
private static void pptToPDF(String filePath, String pdfPath) throws Exception {
if (!getLicense("com.aspose.slides.License")) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
long old = System.currentTimeMillis();
Presentation pres = new Presentation(filePath);
FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));
pres.save(fileOS,com.aspose.slides.SaveFormat.Pdf);
fileOS.close();
long now = System.currentTimeMillis();
logger.info("ppt转pdf成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 设置打印的sheet 自动拉伸比例
* @param wb
* @param page 自动拉伸的页的sheet数组
*/
public static void autoDraw(Workbook wb,int[] page) {
if (null != page && page.length > 0) {
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
}
}
}
/**
* 隐藏workbook中不需要的sheet页。
* @param wb
* @param page 显示页的sheet数组
*/
public static void printSheetPage(Workbook wb,int[] page){
for (int i= 1; i < wb.getWorksheets().getCount(); i++) {
wb.getWorksheets().get(i).setVisible(false);
}
if(null==page||page.length==0){
wb.getWorksheets().get(0).setVisible(true);
}else{
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).setVisible(true);
}
}
}
}
注:1.在实际使用过程中,由于excel表格可能包含多个sheet表以及宽度过宽的问题,因此对于excel表格的转换需根据实际进行更多的处理,例如代码中的autoDraw(),printSheetPage()方法等。
2. 注意验证License!!
若不验证则转化出的pdf文档会有类似"Evaluation Only. Created with Aspose.Words. Copyright 2003-2011 Aspose Pty Ltd."水印产生。
3.不同的格式在转换pdf时,所调用的包也不同,例如com.aspose.slides.SaveFormat.Pdf
pres.save(fileOS,com.aspose.slides.SaveFormat.Pdf);
4.方法调用
传入文件地址及PDF存储地址及文件格式调用即可
//aspose方式转pdf
int isSucc = AsposeUtils.officesToPdf(文件路径, pdf存储路径, 文件格式);
5.测试效果
word:
excel:
ppt:
三、文件资源
本文部分文件资源:
https://download.csdn.net/download/qq_39076017/21106426?spm=1001.2014.3001.5503