一、引入maven依赖
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>22.10</version>
</dependency>
二、核心代码
import com.aspose.pdf.Document;
import com.aspose.pdf.PageInfo;
import com.aspose.pdf.SaveFormat;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author :jerry
* @date :Created in 2022/11/15 19:00
* @description:PDF转word
* @version: V1.1
*/
public class PdfWord {
//测试
public static void main(String[] args) throws IOException {
pdfDoc("/Users/jerry/Downloads/考研背景知识盘点(政英数).pdf", ".DOCX");
}
//pdf转doc
public static String pdfDoc(String pdfPath, String fileFormatValue) {
String wordPath = pdfPath.substring(0, pdfPath.lastIndexOf(".")) + fileFormatValue;
try {
//新建一个word文档
FileOutputStream os = new FileOutputStream(wordPath);
//doc是将要被转化的word文档
Document doc = new Document(pdfPath);
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.setPageInfo(new PageInfo());
doc.save(os, getTypes(fileFormatValue));
os.close();
//转化用时
} catch (Exception e) {
System.out.println("Pdf 转 Word 失败...");
e.printStackTrace();
}
return wordPath;
}
public static SaveFormat getTypes(String fileFormatValue) {
Map<String, SaveFormat> formatMap = new HashMap<>();
formatMap.put(".DOCX", SaveFormat.DocX);
formatMap.put(".PDF", SaveFormat.Pdf);
formatMap.put(".Html", SaveFormat.Html);
formatMap.put(".Xml", SaveFormat.Xml);
formatMap.put(".XPS", SaveFormat.Xps);
formatMap.put(".Excel", SaveFormat.Excel);
formatMap.put(".svg", SaveFormat.Svg);
return formatMap.getOrDefault(fileFormatValue, SaveFormat.Doc);
}
}
注意事项:
1.有时候报错,可能是因为本机缺少相应的字体包,直接去字体网站 (https://cn.ffonts.net/)下载字体,放入本机的系统字体目录即可.