You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX导出TableView为PDF遇ClassCastException及文件加载失败问题

JavaFX TableView导出PDF问题解决(iText 7.2.5)

1. 解决ClassCastException异常

  • 异常根源:你的TableView的Items集合中存储的是控制器实例(而非预期的业务数据对象),却被强制转换为int传给column.getCellData(int)重载方法。getCellData有两个重载:
    • getCellData(int index):通过行索引获取数据
    • getCellData(T item):通过行数据对象获取对应列的值
  • 代码修复:去掉强制转换,直接使用item作为参数,同时处理空值避免NPE:
    // 替换原254行代码
    Object cellValue = column.getCellData(item);
    pdfTable.addCell(cellValue != null ? cellValue.toString() : "");
    
  • 额外检查:确认TableView的Items中存储的是业务数据对象,而非控制器实例,这是类型转换异常的根本原因。

2. 修复PDF无法加载的问题

  • 问题原因:代码中同时创建FileOutputStream和直接传递filePath给PdfWriter,导致文件写入冲突;且未正确关闭资源,造成PDF文件损坏。
  • 代码修复:使用try-with-resources自动管理资源,避免泄漏:
    String filePath = selectedDirectory.getAbsolutePath() + File.separator + fileName;
    // try-with-resources自动关闭writer、pdfDoc和document
    try (PdfWriter writer = new PdfWriter(filePath);
         PdfDocument pdfDoc = new PdfDocument(writer);
         Document document = new Document(pdfDoc)) {
        
        Table pdfTable = new Table(TableName.getColumns().size());
        // 添加表头
        for (TableColumn<?, ?> column : TableName.getColumns()) {
            pdfTable.addCell(column.getText());
        }
        // 添加行数据
        for (Object item : TableName.getItems()) {
            for (TableColumn<?, ?> column : TableName.getColumns()) {
                Object cellValue = column.getCellData(item);
                pdfTable.addCell(cellValue != null ? cellValue.toString() : "");
            }
        }
        document.add(pdfTable);
    } catch (Exception e) {
        System.out.println("Exception while downloading pdf tableView: " + e);
        e.printStackTrace();
    }
    
  • 注意:删除原代码中的OutputStream file = new FileOutputStream(filePath);,PdfWriter会自行处理文件写入逻辑。

3. SLF4J依赖问题处理

  • iText 7仅需以下两个SLF4J依赖即可,无需slf4j-log4j12:
    • slf4j-api-2.0.6.jar:SLF4J核心API
    • slf4j-simple-2.0.6.jar:简单日志实现,用于控制台输出日志
  • 若使用构建工具,依赖配置示例:
    Maven:
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>2.0.6</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.6</version>
        <scope>runtime</scope>
    </dependency>
    
    Gradle:
    implementation 'org.slf4j:slf4j-api:2.0.6'
    runtimeOnly 'org.slf4j:slf4j-simple:2.0.6'
    

内容的提问来源于stack exchange,提问作者Sarmad Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:55:15