java 通过 冰蓝 word 转pdf ,最大程度包装pdf 样式和word接近

这篇博客介绍了如何在Java应用中使用Spire.Doc库将Word文档转换为PDF。首先,通过Maven添加Spire.Doc依赖,并配置仓库URL。然后,展示了测试代码,展示如何加载Word文件并保存为PDF。在实际应用中,代码演示了从流中读取替换后的Word文档,再将其转换为PDF,并上传到服务器的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 所需依赖

        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>3.9.0</version>
        </dependency>

 <repositories> 
    <repository>
      <id>com.e-iceblue</id>
      <name>e-iceblue</name>
      <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>

  </repositories>

 测试代码

    public static void main(String[] args) {
        Document document =new Document();
        document.loadFromFile("C:\\Users\\11949\\Desktop\\工作票3.docx"); 
        document.saveToFile("C:\\Users\\11949\\Desktop\\工作票3.pdf", FileFormat.PDF); 
    }

实际使用

    @GetMapping(value = "/exportWordTestPDFUrl")
    public R<?> exportWordTestUrl(@RequestParam Map<String , Object> mapCon , HttpServletResponse response ) throws Exception {
        R resultBody = replaceWordDataService.replaceWord( mapCon  );
        if(resultBody.getCode() == 0 ){
            byte[] array = null;
            ExportWordDTO data = (ExportWordDTO) resultBody.getData();
            XWPFTemplate template = data.getXwpfTemplate();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            template.writeAndClose( baos );//文档写入流
            array = baos.toByteArray();
            baos.close();
            template.close();
            // 替换后的word转流
            InputStream inputStream = new ByteArrayInputStream( array ) ;

            Document document =new Document();
            document.loadFromStream(inputStream,FileFormat.Docx_2013); 
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             document.saveToStream(outputStream, FileFormat.PDF); 
            byte[] pdfArray = null;
            pdfArray = outputStream.toByteArray();
            outputStream.close();
            R<ResultFileModel> upload =
                    remoteFileService.upload(pdfArray, 1, applicationName,  data.getOutFileName()+".pdf");
            if (null !=  upload && upload.getCode() == 0){
                // 将url 返回前端
                ResultFileModel fileModel = upload.getData();
                String path = fileModel.getAddress() +  fileModel.getPath();
                return R.ok().data( path );
            }else {
                return R.fail().msg( "文件上传失败!" );
            }
        }
        return R.fail().msg(resultBody.getMsg());
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值