Word2PDF

word 转 pdf

使用aspose.words库实现,兼容doc,docx格式。

maven 依赖

1
2
3
4
5
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>

工具实现

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.*;

public class WordToPdf implements Converter{
private static WordToPdf wordToPdf = null;

private WordToPdf(){}

public static WordToPdf create(){
if (wordToPdf == null){
wordToPdf = new WordToPdf();
}
return wordToPdf;
}

public byte[] convertToPdf(File file) throws Exception {
InputStream docInputStream = null;
try {
docInputStream = new FileInputStream(file);
return core(docInputStream);
}finally {
docInputStream.close();
}
}

public byte[] convertToPdf(byte[] file) throws Exception {
InputStream docInputStream = null;
try {
docInputStream = new ByteArrayInputStream(file);
return core(docInputStream);
}finally {
docInputStream.close();
}
}

private byte[] core(InputStream inputStream) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
String s = "加载授权";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
License license = new License();
license.setLicense(is);

Document document = new Document(inputStream);
document.save(outputStream, SaveFormat.PDF);

return outputStream.toByteArray();
}finally {
outputStream.close();
}

}

}