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

如何用iTextPdf 5.5.13.3创建第一行整行、第二行两列的PdfPTable?

实现iTextPdf 5.5.13.3中混合列数的PdfPTable需求

不需要嵌套表格,直接用单元格跨列就能实现你要的效果。核心是创建一个2列的表格,第一行的单元格设置跨2列,第二行正常放两个单元格即可,具体代码示例如下:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.IOException;

public class MixedColumnTable {
    public static void main(String[] args) throws DocumentException, IOException {
        // 初始化文档和输出流
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("mixed_column_table.pdf"));
        document.open();

        // 创建一个2列的表格
        PdfPTable table = new PdfPTable(2);
        // 可选:设置表格宽度占满页面
        table.setWidthPercentage(100);

        // 第一行:跨2列的单元格
        PdfPCell fullRowCell = new PdfPCell(new Phrase("第一行:整行显示的内容"));
        fullRowCell.setColspan(2);
        // 可选:设置单元格内边距,优化显示
        fullRowCell.setPadding(10);
        table.addCell(fullRowCell);

        // 第二行:两个普通单元格
        PdfPCell cell1 = new PdfPCell(new Phrase("第二行:第一列内容"));
        cell1.setPadding(10);
        table.addCell(cell1);

        PdfPCell cell2 = new PdfPCell(new Phrase("第二行:第二列内容"));
        cell2.setPadding(10);
        table.addCell(cell2);

        // 将表格加入文档
        document.add(table);
        document.close();
    }
}

关键要点:

  • 表格的列数按最大拆分列数设置(这里是2列)
  • 跨列的单元格通过setColspan(int)方法指定要跨越的列数
  • 避免嵌套表格,这种方式更简洁且样式易控制

内容的提问来源于stack exchange,提问作者julien carax

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:33:18