org.apache.poi——將 office的各種類型文件(word等文件類型)轉為 pdf
- 簡介
- 使用方法
- word轉pdf
- 使用示例
- word轉pdf
簡介
使用方法
word轉pdf
Maven坐標為
<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>
核心方法如下所示。
//創建轉換器
IConverter converter = LocalConverter.builder().build();
//轉換需要的參數,依次是輸入流、轉換前的原類型、輸出流、轉換后的目標類型
boolean execute = converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).schedule().get();
使用示例
word轉pdf
親測有效
// public static void main(String[] args) {
// WordToPdfConverter converter = new WordToPdfConverter("C:\\Users\\LJH\\Desktop\\上傳文件sha1為02.docx","C:\\Users\\LJH\\Desktop\\testConvert.pdf");
// converter.convert();
// }public class WordToPdfConverter {String sourcePath;String targetPath;public WordToPdfConverter(String sourcePath, String targetPath){this.sourcePath = sourcePath;this.targetPath = targetPath;}/*** 輸入:目前被限制為Path.toUri()* return:可能為null* */public File convert() {File inputWord = new File(sourcePath.toUri());File outputPdf = new File(targetPath.toUri());InputStream docxInputStream = null;OutputStream outputStream = null;try {docxInputStream = new FileInputStream(inputWord);outputStream = new FileOutputStream(outputPdf);IConverter converter = LocalConverter.builder().build();boolean execute = converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).schedule().get();if (execute) {System.out.println("轉換完畢 targetPath = " + outputPdf.getAbsolutePath());} else {System.out.println("[documents4J] word轉pdf失敗:");return null;}converter.shutDown();} catch (Exception e) {System.out.println("[documents4J] word轉pdf失敗:"+e.toString());return null;}finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}if (docxInputStream != null) {try {docxInputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}}return outputPdf;}
}