依賴:poi版本太高會報錯
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10.1</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.4</version>
</dependency>
實現:此方法只適用於docx文件轉pdf
/**
* word轉pdf
* @param wordPath word的路徑
* @param pdfPath pdf的路徑
*/
public static boolean wordToPdf(String wordPath, String pdfPath){
boolean result = false;
try {
XWPFDocument document=new XWPFDocument(new FileInputStream(new File(wordPath)));
File outFile=new File(pdfPath);
outFile.getParentFile().mkdirs();
OutputStream out=new FileOutputStream(outFile);
PdfOptions options= PdfOptions.create();
PdfConverter.getInstance().convert(document,out,options);
result = true;
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
如在出現以下錯誤:只需把poi版本依賴降低即可
java.lang.NoSuchMethodError:
org.apache.poi.POIXMLDocumentPart.getPackageRelationship()Lorg/apache/poi/openxml4j/opc/PackageRelationship;
如出現以下錯誤:是因爲word文檔格式不是2007版本的,調整格式爲2007版本的即可
org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException:
The supplied data appears to be a raw XML file. Formats such as Office 2003 XML are not supported