0%

【工作技能】word转pdf

如何利用java实现word转pdf


1 aspose-words工具包

1.1 依赖准备

1
2
3
4
5
6
7
8
9
<!--收费jar,需要下载到本地,通过本地导入-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>18.6</version>
<classifier>jdk16</classifier>
<scope>system</scope>
<systemPath>${project.basedir}/lib/aspose-words-18.6-jdk16-crack.jar</systemPath> <!--jar包路径-->
</dependency>

1.2 准备license.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
<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>

1.3 修改Pom文件

1
2
3
4
5
6
7
8
9
10
11
<!--编译java时,java文件夹下能携带xml文件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>

1.4 转换工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* word工具类 - word转pdf
* @author letere
* @create 2021-06-16 16:36
*/
public class WordUtil {

/**
* word文档转pdf
* @param inputStream word输入流
* @param pdfFile 转换后的pdf文件
*/
public static void wordToPdf(InputStream inputStream, File pdfFile) throws Exception{
if (getLicense()) {
OutputStream outputStream = new FileOutputStream(pdfFile);

//读取输入流
Document document = new Document(inputStream);
//按pdf形式写入输出流
document.save(outputStream, SaveFormat.PDF);
} else {
throw new Exception("license文件验证失败!");
}
}

/**
* 获取license(文件验证,通过验证,转换后pdf无水印)
* @return boolean
*/
private static boolean getLicense() {
try {
File file = new File("./src/main/java/util/aspose_words/license.xml");
InputStream is = new FileInputStream(file);
License aposeLic = new License();
aposeLic.setLicense(is);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

1.5 代码测试

1
2
3
4
5
6
7
8
9
10
11
@Test
public void asposeWordsTest() throws Exception{
//word文件输入流
InputStream inputStream = new FileInputStream("./src/main/resources/word/操作手册.docx");

//pdf输出文件
File pdfFile = new File("./src/main/resources/pdf/操作手册.pdf");

//工具类进行转换
WordUtil.wordToPdf(inputStream, pdfFile);
}