Java 基于aspose将word转换pdf格式
网上有很多将word文档转换成pdf格式的例子,如windows平台安装插件,或者linux服务器上安装插件,或者JDK中加入dll等方式,我个人感觉局限性比较大。如何说?
是不是我在另一个电脑上操作转换,我就必须安装一个什么插件?是不是我的JDK也必须安装插件,换另一台服务器是不是也必须要换?
太复杂了,其实有一个JAR包,只要引入,几句代码就能搞定,但是不好的是这个JAR是收费的,并且maven仓库上不好找到,但是自然会有人出来破解的
JAR包位置:https://pan.baidu.com/s/1oFVzcChH1R_p9SrYHuLzfA
准备工作
创建项目
用IDEA创建一个普通maven项目,pom文件中做好准备工作,如编译版本,打包插件等,后续可以把转换写成一个工具,被其他项目引入jar方式使用
<groupId>com.wordToPdf</groupId>
<artifactId>converter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>converter</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>Main</mainClass>
</manifest>
<!-- 添加本地的jar -->
<manifestEntries>
<Class-Path>lib/aspose-words-16.8.0-jdk16.jar</Class-Path> <!-- 这个>lib/class-util-1.0.jar 路径是已经被打包到target/lib里的,多个包用空格隔开就可以了 -->
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<targetPath>lib/</targetPath>
<directory>lib/</directory>
<includes>
<include>**/aspose-words-16.8.0-jdk16.jar</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.ftl</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.ftl</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
打包插件中有两个特殊的地方,用于将本地jar依赖一起打包,一个是includes
标签,一个是manifestEntries
标签
引入jar包
在项目根目录(src同级)创建一个文件夹,取名叫lib
,将下载好的依赖放进去,鼠标点击右键jar,有个Add as Library
选项,点击之后将jar依赖入项目中,右键点击lib
目录,有个Mark Directory as
选项,鼠标放上去会跳出二级菜单,选择Resources Root
,将文件夹设置为资源路径
在src/main/resource
目录下创建一个XML文件,取名叫license.xml
,主要作用是去除水印以及破解jar包收费限制
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
写转换的工具类
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import java.io.*;
/**
* @Author: ChenBin
* @Date: 2018/10/17/0017 22:09
*/
public class WordToPdf {
private static boolean getLicense() {
boolean result = false;
try {
InputStream license = WordToPdf.class.getResourceAsStream("/license.xml");
License aposeLic = new License();
aposeLic.setLicense(license);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void converter(String resource, String targer){
// 验证License
if (!getLicense()) {
return;
}
try {
long old = System.currentTimeMillis();
File inputFile = new File(resource);
InputStream inputStream = new FileInputStream(inputFile);
Document doc = new Document(inputStream);
File outPut = new File(targer);
OutputStream outputStream = new FileOutputStream(outPut);
doc.save(outputStream, SaveFormat.PDF);
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
System.out.println("文件保存在:" + outPut.getPath());
}catch (Exception e){
e.printStackTrace();
}
}
}
这么一个简单的程序就完成了文件转换,重要是利用Java IO流,将文件目标读取,再进行转换,再利用流写出
实际运用到项目中
以上只是完成了一个准备,做了一个转换工具,但是实际运行到项目中的时候,就满足不了需求,这个时候就要再写一个Java类,用于扩展
public class Converter {
//系统临时路径,用于保存word文件和pdf文件
private static String CONVERT_FILE_DIR = System.getProperty("java.io.tmpdir");
private static FileManagerClient fileManagerClient = new DefaultFileManagerClient(false);
private byte[] download(String path){
byte[] data = null;
Result<byte[]> result = fileManagerClient.download(path);
if (result.getData() != null){
data = result.getData();
}
return data;
}
private String upload(byte[] data, String fileName){
String path = "";
Result<FileItem> result = fileManagerClient.upload(data, fileName);
if (result.getData() != null){
path = result.getData().getVirtualPath();
}
return path;
}
//外部引入调用此方法进行转换以及获取上传后的路径地址
public String startConverter(String path) {
//传入下载地址,下载文件并用流写入临时文件夹
byte[] downData = this.download(path);
//保存到本地的绝对路径(系统临时路径 + 文件名)
String srcFilePath = CONVERT_FILE_DIR.concat(File.separator).concat(fileName) ;
File srcFile = new File(srcFilePath);
OutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(srcFile);
fileOutputStream.write(downData) ;
}catch (Exception e){
e.printStackTrace();
}finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
//写入完成后定义转换后的文件路径
//开始转换并上传服务器返回上传后的路径
String outFilePath = srcFilePath.substring(0, srcFilePath.lastIndexOf(".")).concat(".pdf");
//转换
WordToPdf.converter(srcFilePath, outFilePath);
String uploadFileName = fileName.substring(0, fileName.lastIndexOf(".")).concat(".pdf");
byte[] uploadBytes = null;
try {
InputStream in = new FileInputStream(outFilePath);
uploadBytes = toByteArray(in);
in.close();
}catch (Exception e){
e.printStackTrace();
}
String uploadPath = this.upload(uploadBytes, uploadFileName);
return uploadPath;
}
private byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
}
文件上传下载的工具类大家自行补充,主要是传入一个文件下载地址,将文件下载并且写入到本地临时文件夹中,因为转换工具类中需要两个参数,一个源文件路径和转换后文件路径。再通过刚写好的转换工具类,将下载好的文件通用IO读取,转换成pdf后被保存到指定路径,由于我上传的工具类是需要传入字节数组,所以将转换后的文件用IO读取,利用ByteArrayOutputStream
转换成byte
数组,再上传到服务器,返回上传后的路径地址。