使用iText将Excel导出为pdf

博客提及Java使用iText创建PDF表格,涉及iText7和iText5版本。但创建时使用excel每列宽度比例,无法完美适应excel单元格数据长度,且未找到解决办法。

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

1、iText7版本

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext7-core -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.0.3</version>
            <type>pom</type>
        </dependency>
@Slf4j
public class ExcelToPdfConverter {

    public static void converter(SXSSFWorkbook workbook, FileOutputStream fos) {
        try  {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 创建PDF文档对象
            int colWidth = getColWidth(sheet);
            PageSize pageSize;
            if (colWidth <= 21000){
                pageSize = PageSize.A4;
            } else if (colWidth <= 29700){
                pageSize = PageSize.A3;
            } else if (colWidth <= 42000){
                pageSize = PageSize.A4.rotate();
            } else {
                pageSize = PageSize.A3.rotate();
            }
            PdfWriter pdfWriter = new PdfWriter(fos);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            Document document = new Document(pdfDocument, pageSize);
            // 创建PDF表格对象
            float[] colWidthRatio = getColWidthRatio(sheet);
            Table table = new Table(colWidthRatio, true);

            // 添加表格内容
            for (Row row : sheet) {
                for (Cell cell : row) {
                    com.itextpdf.layout.element.Cell add = new com.itextpdf.layout.element.Cell().add(cell.toString());
                    table.addCell(add);
                }
            }
            // 添加表格到PDF文档
            document.add(table);
            // 关闭PDF文档
            document.close();
        } catch (Exception e) {
            log.error("电子表格导出失败:" + e.getMessage());
        }

    }

    private static float[] getColWidthRatio(Sheet sheet) {
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();

        Row firstRow = sheet.getRow(firstRowNum);
        short firstCellNum = firstRow.getFirstCellNum();
        short lastCellNum = firstRow.getLastCellNum();

        float[] columnWidths = new float[lastCellNum - firstCellNum];
        Arrays.fill(columnWidths, 6);

        for (int rowIndex = firstRowNum; rowIndex <= lastRowNum; rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            for (int cellIndex = firstCellNum; cellIndex < lastCellNum; cellIndex++) {
                Cell cell = row.getCell(cellIndex);
                if (cell != null) {
                    String cellValue = cell.toString().trim();
                    int cellWidth = cellValue.length(); // 以字符数为单位
                    if (columnWidths[cellIndex] < cellWidth) {
                        columnWidths[cellIndex] = cellWidth;
                    }
                }
            }
        }
        return columnWidths;
    }

    private static int getColWidth(Sheet sheet) {
        int rowNum = sheet.getRow(0).getLastCellNum();
        Row row = sheet.getRow(rowNum);
        int cellCount = row.getPhysicalNumberOfCells();
        int sum = 0;

        for (int i = row.getFirstCellNum(); i < cellCount; i++) {
            Cell cell = row.getCell(i);
            if (cell != null) {
                sum += sheet.getColumnWidth(i);
            }
        }
        return sum / 2;
    }

}

2、iText5版本

		<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.1</version>
        </dependency>
@Slf4j
public class ExcelToPdfConverter {

    public static void converter(SXSSFWorkbook workbook, FileOutputStream fos) {
        try  {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 创建PDF文档对象
            int colWidth = getColWidth(sheet);
            Rectangle pageSize;
            if (colWidth <= 21000){
                pageSize = PageSize.A4;
            } else if (colWidth <= 29700){
                pageSize = PageSize.A3;
            } else if (colWidth <= 42000){
                pageSize = PageSize.A4.rotate();
            } else {
                pageSize = PageSize.A3.rotate();
            }
            Document document = new Document(pageSize);
            // 创建PDF输出流
            PdfWriter.getInstance(document, fos);
            // 打开PDF文档
            document.open();
            // 创建PDF表格对象
            PdfPTable table = new PdfPTable(sheet.getRow(0).getLastCellNum());
            table.setHeaderRows(0);
            table.setWidths(getColWidthRatio(sheet));
            // 设置表格宽度
            table.setWidthPercentage(100);
            // 添加表格内容
            for (Row row : sheet) {
                for (Cell cell : row) {
                    PdfPCell pdfCell = new PdfPCell(new Paragraph(cell.getStringCellValue()));
                    pdfCell.setBorderWidth(1f);
                    pdfCell.setBorderColor(BaseColor.BLACK);
                    pdfCell.setPadding(5f);
                    if (cell.getRowIndex() == 0) {
                        pdfCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    }
                    table.addCell(pdfCell);
                }
            }
            // 添加表格到PDF文档
            table.setSpacingBefore(20f);
            table.setSpacingAfter(20f);
            table.setKeepTogether(true);
            document.add(table);
            // 关闭PDF文档
            document.close();
        } catch (DocumentException e) {
            log.error("电子表格导出失败:" + e.getMessage());
        }

    }

    private static int[] getColWidthRatio(Sheet sheet) {
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();

        Row firstRow = sheet.getRow(firstRowNum);
        short firstCellNum = firstRow.getFirstCellNum();
        short lastCellNum = firstRow.getLastCellNum();

        int[] columnWidths = new int[lastCellNum - firstCellNum];
        Arrays.fill(columnWidths, 6);

        for (int rowIndex = firstRowNum; rowIndex <= lastRowNum; rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            for (int cellIndex = firstCellNum; cellIndex < lastCellNum; cellIndex++) {
                Cell cell = row.getCell(cellIndex);
                if (cell != null) {
                    String cellValue = cell.toString().trim();
                    int cellWidth = cellValue.length(); // 以字符数为单位
                    if (columnWidths[cellIndex] < cellWidth) {
                        columnWidths[cellIndex] = cellWidth;
                    }
                }
            }
        }
        return columnWidths;
    }

    private static int getColWidth(Sheet sheet) {
        int rowNum = sheet.getRow(0).getLastCellNum();
        Row row = sheet.getRow(rowNum);
        int cellCount = row.getPhysicalNumberOfCells();
        int sum = 0;

        for (int i = row.getFirstCellNum(); i < cellCount; i++) {
            Cell cell = row.getCell(i);
            if (cell != null) {
                sum += sheet.getColumnWidth(i);
            }
        }
        return sum / 2;
    }

}

注意:
这里貌似还有存在一个问题,就是创建pdf表格的使用的是excel每一列的宽度比例,并无法完美做到将excel每个单元格的数据的长度做到适应,思来想去没有想到什么好的方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值