WORD转PDF—方法1
如果你在项目中需要考虑到你用到的依赖是否开源 不是开源 使用方可以可能回收到起诉 自己使用不影响 有问题可以评论 需要帮助的话也可以评论
//用下面的代码就需要引入此依赖 我这用的maven 如果你需要jar可以评论留下联系方式
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>20.12</version>
</dependency>
/**
* word转pdf
* <hr>
*
* @date 2023年02月13日 下午6:46:25
* @since 0.0.1
* @param wordPath
* word文件位置
* @param pdfPath
* PDF文件位置 void
*/
public static void wordToPdf(String wordPath, String pdfPath) {
try {
long old = System.currentTimeMillis();
// 新建一个空白pdf文档
File file = new File(pdfPath); //pdfPath:F:\\file\\pdf\\name.pdf 即可 name就是文件名 自定义
FileOutputStream os = new FileOutputStream(file);
// Address是将要被转化的word文档
Document doc = new Document(wordPath);
//加粗的代码可以有也可以不要 这里防止出现格式不对的情况 不加有可能会导致word第一页的尾部内容会在Pdf 的第二页显示 注:doc.removeAllChildren以及doc.appendDocument(doc, ImportFormatMode.USE_DESTINATION_STYLES);//保留样式的方法不行 也可以自己测试下
**ParagraphFormat defaultParagraphFormat = doc.getStyles().getDefaultParagraphFormat();
defaultParagraphFormat.clearFormatting();**
// 全面支持DOC, DOCX, OOXML, RTF HTML,
// OpenDocument, PDF, EPUB, XPS, SWF
// 相互转换
doc.save(os, SaveFormat.PDF); //此方法就是word文件里面的内容copy到你指定的文件中(pdfPath)
long now = System.currentTimeMillis();
os.close();
// 转化用时
System.out.println(file.getName() + ",共耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
WORD转PDF—方法2
//通过dom4j进行转换
<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>
public static void WordToPdf(String wordPath, String pdfPath) {
File inWord = new File(wordPath);
File outPdf = new File(pdfPath);
try {
InputStream docxInputStream = new FileInputStream(inWord );
OutputStream outputStream = new FileOutputStream(outPdf );
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream)
.as(DocumentType.DOCX) //此处可以设置你的文本类型 这是需要转换的文件类型
.to(outputStream)
.as(DocumentType.PDF).execute(); //转换成的文件类型
outputStream.close();
} catch (Exception e) {
log.error("[documents4J] word转pdf失败:{}", e.toString());
}
}