java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java Excel转PDF

Java+LibreOffice实现Excel转PDF并横向一页显示所有列

作者:懂行者,行天下。

在实际业务场景中,用户往往会提供格式不一的 Excel 文件,有时希望将其转换为 PDF 并横向显示,所有列压缩在一页内,下面我们来看看具体实现方法吧

背景需求

在实际业务场景中,用户往往会提供格式不一的 Excel 文件(尤其列非常多),希望将其转换为 PDF 并横向显示,所有列压缩在一页内

用户不会手动设置打印参数,因此希望通过 Java 代码实现自动化转换,保证视觉效果统一。

技术方案概览

技术栈

工具用途
Apache POI修改 Excel 页设置(横向、一页宽)
LibreOffice使用 headless 模式导出 PDF
Java实现逻辑控制和流程管理

页面设置关键代码

Apache POI 5.2.5

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public static void adjustExcelPageSetup(String inputPath, String tempPath) throws IOException {
    FileInputStream fis = new FileInputStream(inputPath);
    Workbook workbook = new XSSFWorkbook(fis);
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        PrintSetup printSetup = sheet.getPrintSetup();
        printSetup.setLandscape(true); // 横向打印
        sheet.setAutobreaks(true); // 自动分页
        sheet.setFitToPage(true); // 启用适应页面
        printSetup.setFitWidth((short) 1); // 一页宽度
        printSetup.setFitHeight((short) 0); // 高度不限(0 = 自动)
        }
        FileOutputStream fos = new FileOutputStream(tempPath);
        workbook.write(fos);
        workbook.close();
        fis.close();
        fos.close();
}

LibreOffice 命令行调用

public static void convertToPdf(String libreOfficePath, String inputPath, String outputDir) throws IOException, InterruptedException {
    List<String> command = Arrays.asList(
        libreOfficePath,
        “–headless”,
        “–norestore”,
        “–convert-to”, “pdf”,
        “–outdir”, outputDir,
        inputPath
        );
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.inheritIO();
        Process process = pb.start();
        int exitCode = process.waitFor();

if (exitCode == 0) {
    System.out.println("转换成功: " + inputPath);
    
} else {
    System.err.println("转换失败: " + inputPath);
    
}
    
}

常见问题 FAQ

1.setFitToWidth() 报错:方法不存在?

是早期示例误导,正确方法是:

printSetup.setFitWidth((short) 1);
printSetup.setFitHeight((short) 0);

2.temp_wide_excel.xlsx 是否需要预创建?

不需要,只要目录存在,程序会自动创建并写入该文件。

3.文件路径有空格导致 LibreOffice 转换失败?

请使用 “路径” 包含引号或使用 new File(path).getAbsolutePath() 避免错误。

4.Excel 很宽时 PDF 仍分页?

请务必:

使用 printSetup.setFitWidth((short) 1) 设置一页宽

启用 sheet.setFitToPage(true)

使用 LibreOffice 转换前,先保存好设置

完整流程

接收原始 Excel 文件(.xlsx)

使用 Apache POI 设置打印参数(横向、一页宽)

输出为临时文件(如 temp_wide_excel.xlsx)

使用 LibreOffice 命令行导出 PDF

输出 PDF 横向显示、列不分页

示例目录结构

D:\input\wide_excel.xlsx        // 原始文件
D:\input\temp_wide_excel.xlsx   // 临时设置后文件
D:\output\wide_excel.pdf        // 最终 PDF 输出

扩展建议

支持批量处理整个文件夹 Excel 文件

自动清理临时文件

包装为 CLI 工具或 Sp

到此这篇关于Java+LibreOffice实现Excel转PDF并横向一页显示所有列的文章就介绍到这了,更多相关Java Excel转PDF内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文