逻辑很简单、就是不用spire.pdf。用他的pdf转换会在你的文件里面生成水印、每一页都有,用doc生成只有首页有,只需要替换掉首页的水印就可以了
1. 首先使用spire.doc生成word文档
Document doc2 = new Document(new FileInputStream(new File(name))); Section sec = doc2.addSection(); doc2.saveToFile(name2, FileFormat.Docx_2010);//保存文件 生成word doc2.close();
2、引用documents4j转换成pdf
InputStream docxInputStream = null;
OutputStream outputStream = null;
try {
// 原word地址
docxInputStream = new FileInputStream("E:\\\\test2\\\\word模板.docx");
// 转换后pdf生成地址
outputStream = new FileOutputStream("E:\\\\test2\\\\word模板转pdf.pdf");
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream)
.as(DocumentType.DOCX)
.to(outputStream)
.as(DocumentType.PDF).execute();
// 关闭
converter.shutDown();
// 关闭
outputStream.close();
// 关闭
docxInputStream.close();
} catch (Exception e) {
System.out.println("[documents4J] word转pdf失败:" + e.toString());
} finally {
if (outputStream != null) {
outputStream.close();
}
if (docxInputStream != null) {
docxInputStream.close();
}
}
3、引用的jar包
<repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.cn/repository/maven-public/</url> </repository>
<dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-local</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-transformer-msoffice-word</artifactId> <version>1.0.3</version> </dependency>
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>5.4.10</version> </dependency>
4、这个 IConverter converter = LocalConverter.builder().build();方法是不支持linux的、linux的解决办法可以参考这个大佬的方法