Java工具类实现word转pdf结果几乎一模一样
·
Background
- 【封装好的工具类】【转换效果99%】【无水印】
- 实现技术【Aspose】
- 这里给出需要的依赖包 aspose-words-15.8.0.jar和word-license.xml,提取码:king
- excel转pdf可以参考另一篇博客【Java工具类实现excel转pdf结果几乎一模一样】
先看下效果哈(左word右pdf),格式基本没乱,几乎一模一样

直接上源码
注意:使用前,先安装下载的
aspose-words-15.8.0.jar包,然后把word-license.xml放在resources目录下就行了。
package com.cloudansys.core.utils;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
@Slf4j
public class DocUtil {
/**
* 获取 license 去除水印
* 若不验证则转化出的pdf文档会有水印产生
*/
private static void getLicense() {
String licenseFilePath = "word-license.xml";
try {
InputStream is = DocUtil.class.getClassLoader().getResourceAsStream(licenseFilePath);
License license = new License();
license.setLicense(Objects.requireNonNull(is));
} catch (Exception e) {
log.error("license verify failed");
e.printStackTrace();
}
}
/**
* word 转 pdf
* @param wordFile word 文件路径
* @param pdfFile 生成的 pdf 文件路径
*/
public static void word2Pdf(String wordFile, String pdfFile) {
File file = new File(pdfFile);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
getLicense();
try (FileOutputStream os = new FileOutputStream(new File(pdfFile))) {
Document doc = new Document(wordFile);
doc.save(os, SaveFormat.PDF);
} catch (Exception e) {
log.error("word转pdf失败", e);
e.printStackTrace();
}
}
}
使用就非常简单了
package com.cloudansys.test;
import com.cloudansys.core.utils.DocUtil;
public class TestWord2Pdf {
public static void main(String[] args) {
String docFilePath = "D:/test/某项目日报表.docx";
String pdfFilePath = "D:/test/某项目日报表.pdf";
DocUtil.word2Pdf(docFilePath, pdfFilePath);
}
}
更多推荐


所有评论(0)