iText生成一个单元格中包含不同的样式的PDF表格

  • 项目中有的时候需要生成一个这样的PDF表格:

  • 一个单元格中包含不同的字体, 实现方式如下:

PDFTest.java

package com.ehi.rc.util.export;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class PDFTest {
    Font boldFont = FontFactory
            .getFont(FontFactory.HELVETICA, 10, Font.BOLD, Color.BLACK);

    Font normalFont = FontFactory
            .getFont(FontFactory.HELVETICA, 10, Font.NORMAL, Color.RED);

    public byte[] generatePDF() {

        // init
        Document doc = new Document(PageSize.A4.rotate(), 10f, 10f, 10f, 10f);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {

            PdfWriter.getInstance(doc, output);
            doc.open();

            // create pdf table
            PdfPTable pdftable = new PdfPTable(2);

            Phrase phrase = new Phrase();
            phrase.add(new Chunk("Blod red Font", boldFont));
            phrase.add(" : ");
            phrase.add(new Chunk("Normal blank Font", normalFont));
            
           
            pdftable.addCell(phrase);
            pdftable.addCell("Another cell");
            
            phrase = new Phrase();
            phrase.add(new Chunk("Blod red Font", boldFont));
            phrase.add(" : ");
            phrase.add(new Chunk("Normal blank Font", normalFont));
            
           
            pdftable.addCell(phrase);
            pdftable.addCell("Another cell");

            doc.add(pdftable);

        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } finally {
            if (doc.isOpen()) {
                doc.close();
            }
        }

        return output.toByteArray();
    }

    public static void main(String[] args) throws IOException {
        File file = new File("D://test.pdf");
        FileOutputStream out = new FileOutputStream(file);
        out.write(new PDFTest().generatePDF());
    }
}

<< IT is an art

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值