itext7在pdf中生成表格

1、引入依赖

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.1.16</version>
        </dependency>

2、具体实现

    public static void main(String[] args) {
        Path path = Path.of("./files/" + UUID.randomUUID() + ".pdf");
        // 创建PDF文档
        PdfWriter pdfWriter;
        try {
            pdfWriter = new PdfWriter(path.toString());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);

        // 添加中文字体,不添加ttf,中文不会显示
        PdfFont chineseFont;
        try {
            chineseFont = PdfFontFactory.createFont("./files/simsun.ttf", PdfEncodings.IDENTITY_H, true);
        } catch (IOException e) {
            throw new RuntimeException("Font simsun.ttf not found", e);
        }
        // 创建表格
        Table table = new Table(UnitValue.createPercentArray(4)); // 4 列
        table.setWidth(UnitValue.createPercentValue(100));
        // 添加表头
        table.addCell(createCell("列1", chineseFont));
        table.addCell(createCell("列2", chineseFont));
        table.addCell(createCell("列3", chineseFont));
        table.addCell(createCell("列4", chineseFont));
        for (int i = 0; i < 10; i++) {
            // 添加数据
            table.addCell(createCell(STR."数据1-\{i}", chineseFont));
            table.addCell(createCell(STR."数据2-\{i}", chineseFont));
            table.addCell(createCell(STR."数据3-\{i}", chineseFont));
            table.addCell(createCell(STR."数据4-\{i}", chineseFont));
        }
        // 添加表格到文档
        document.add(table);
        // 关闭文档
        document.close();
    }

    private static Cell createCell(String text, PdfFont font) {
        Paragraph paragraph = new Paragraph(text).setFont(font).setTextAlignment(TextAlignment.CENTER); // 设置文本居中对齐
        return new Cell().add(paragraph).setBorder(new SolidBorder(new DeviceRgb(0, 0, 0), 1));
    }

3、结果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值