基于java实现excel转pdf(libreoffice)

前言:

        当今数字化时代,电子文档的使用越来越广泛,而Excel和PDF是其中两种常见的文档格式。Excel作为一种强大的电子表格工具,广泛应用于数据分析、报表生成等领域;而PDF作为一种可靠的文档格式,被广泛用于文档的共享和打印。

        然而,在某些情况下,我们可能需要将Excel文件转换为PDF格式,以便更好地共享、打印或保护文档内容。在Java技术中,我们可以使用一些开源库来实现Excel到PDF的转换,如Apache POI和iText等。

        在本文中,我们将探讨如何使用Java技术将Excel文件转换为PDF格式。

libreoffice下载、安装、启动步骤在专栏【word、excel转pdf】的《基于java技术实现word转pdf》文章中有详细步骤(链接放到文章最后),这里就不在重新写了。因为Aspose.Words是商业版的需要购买证书,原理和word转pdf一样,依赖word换成excel就好,本文提一下libreoffice-excel转pdf    

代码:

package com.atxinxin;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;

import java.io.File;

/**
 * @author weixinxin 2024-01-30
 **/
public class ExcelToPdf {

    public static boolean xlsxToPDF(String wordPath, String pdfPath) {
        try {
            long startTime = System.currentTimeMillis();
            File inputFile = new File(wordPath);
            File outputFile = new File(pdfPath);
            OpenOfficeConnection connection = new SocketOpenOfficeConnection("libreoffice安装的服务器ip",1998);//启动命令的指定端口
            System.out.println(" 连接到libreoffice==="+ (System.currentTimeMillis() - startTime));
            connection.connect();
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

            converter.convert(inputFile,outputFile);
            connection.disconnect();
            System.out.println("time==" + (System.currentTimeMillis() - startTime));
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    public static void main(String[] args) throws Exception {
        String wordPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试excel转pdf.xlsx";
        String pdfPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试excel转pdf.pdf";
        xlsxToPDF(wordPath, pdfPath);
    }

}

结果:

提一下libreoffice中的converter.convert方法

可以看到这个方法中的参数类型有四种

一、流+文件格式

二、文件+文件格式

三、文件+输出文件+输出文件格式

四、文件

向这种方式,就算不指定格式也会按照文件后缀生成

文章开头提到的文章链接:http://t.csdnimg.cn/gZ9lf

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值