1.接上文,格式转换的基础问题已解决,但还有些细节问题需要单独处理,如excel转换至pdf时,如何将所有列显示在一页的问题,此问题大家都有遇到,解决方案也比较多,我也尝试过重写某类,来实现自定义pdf页面篇幅大小问题,但现在有个更优的方案给到大家,利用逆向思维,在excel转换pdf前,优先对excel进行预处理,如使用poi组件,将excel的所有列设置在一页,即可。
2.首先在build.gradle中引入POI依赖
implementation group: 'org.apache.poi', name: 'poi', version: '5.2.3'
implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '5.2.3'
implementation group: 'org.apache.poi', name: 'poi-scratchpad', version: '5.2.3'
3.书写工具类,优先对excel进行预处理,即可。
/*** change page size.*/public void refresh(String oldFilePath, String oldType, String newFilePath) throws IOException {Workbook workbook = null;if (oldType.equals("xls")) {workbook = new HSSFWorkbook(new FileInputStream(oldFilePath));} else if (oldType.equals("xlsx")) {workbook = new XSSFWorkbook(new FileInputStream(oldFilePath));}Integer sheetCount = workbook.getNumberOfSheets();for (int i = 0; i < sheetCount; i++) {Sheet sheet = workbook.getSheetAt(i);//通过此处即可将excel中所有列放置在一页显示(打印),转换至pdf后也将在一页显示XSSFPrintSetup printSetup = (XSSFPrintSetup) sheet.getPrintSetup();printSetup.setFitHeight((short) 0);sheet.setFitToPage(true);}workbook.write(new FileOutputStream(newFilePath));}
效果预览:
xlsx文件原来多页效果:
转换为PDF后效果: