java实现Word文件转换成PDF

使用document4j将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-api</artifactId>
    <version>1.0.3</version>
</dependency>

<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-transformer-msoffice-word</artifactId>
    <version>1.0.3</version>
</dependency>

第二步:后台代码

 @GetMapping("/wordToPdf")
    public void wordToPdf() throws Exception {
        ArrayList<User> users = new ArrayList<User>();
        User user = new User();
        user.setId("1");
        user.setName("小张");
        user.setAge("18");
        user.setTel("138383838383");
        users.add(user);

        users.add(new User("2","小王","22","384324324"));
        users.add(new User("3","小3","23","3843243224"));
        users.add(new User("4","小4","24","11122224"));
        users.add(new User("5","小5","25","14654324324"));

        File fileIn = new File("C:\\Users\\Administrator\\Desktop\\test\\template.docx");
        File fileOut = new File("C:\\Users\\Administrator\\Desktop\\test\\target.docx");
        OutputStream outputStream = new FileOutputStream(fileOut);


        Map<String,Object> data = new HashMap();
        data.put("data",users);
        InputStream inputStream = new FileInputStream(fileIn);
        MyXWPFDocument sourceDocument = new MyXWPFDocument(inputStream);
        WordExportUtil.exportWord07(sourceDocument, data);
        sourceDocument.write(outputStream);

        FileInputStream docxInputStream = new FileInputStream(fileOut);
        FileOutputStream pdfOutputStream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test\\targetPdf.pdf");
        IConverter converter = LocalConverter.builder().build();
        converter.convert(docxInputStream).as(DocumentType.DOCX).to(pdfOutputStream).as(DocumentType.PDF).execute();
        outputStream.close();
        pdfOutputStream.close();
    }

运行程序进行转换
在这里插入图片描述
转换成功!

问题:
documents4j是一个Java库,用于将文档转换为另一种文档格式。这是通过将转换委托给任何能够理解将给定文件转换为所需目标格式的本机应用程序来实现的。documents4j附带了适用于MS Word和MS Excel for Windows的功能,例如,它允许将docx文件转换为pdf文件,而不会在生成的文档中出现通常的扭曲,而在使用非Microsoft产品进行转换时,通常会观察到这种扭曲。

意思就是使用Windows产品进行的转换,因此当脱离了Windows部署到Linux上时,脱离了Microsoft产品,就会报错。
解决方案:
需要导入aspose-words-xxx.jar(用于PDF转换 )

你可能感兴趣的:(Java,java,开发语言)