背景需求
在实际业务场景中,用户往往会提供格式不一的 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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论