如何更改 iText 中的单元格颜色 Java

How to change cell color in iText Java

我是 itext 的新手,我需要帮助才能更改单元格标题 1 和标题 2 的格式,我希望它具有不同的颜色背景和粗体字体。

下面的代码简单地创建了一个带有标题的 table。

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Font;
import java.io.FileOutputStream;
import java.util.Date;

public class Pdfcreate{

    public static void main(String[] args) {
        //PdfPrint pdf = new PdfPrint();
        try{
            Document document = new Document();
            PdfWriter.getInstance(document , new FileOutputStream("test.pdf")); // name of pdf
            document.open();

            PdfPTable table = new PdfPTable(2); 
            PdfPCell cell = new PdfPCell(new Paragraph("Title")); 
            cell.setColspan(2); // colspan 
            cell.setHorizontalAlignment(Element.ALIGN_CENTER); 
            cell.setBackgroundColor(BaseColor.GREEN); 
            table.addCell(cell);  

            table.addCell("heaading 1"); // how to change cell to have different font and bold and background color
            table.addCell("heading 2"); // how to change cell to have different font and bold and background color
            table.addCell("item3");
            table.addCell("item4");
            document.add(table);

            System.out.println("PRINTED");
            document.close();
        }catch(Exception e){
            System.out.println(e);
        }       
    }



}

解决方案在这里:

颜色:

public static String mColor = "#aa8cc5";
int aa = Integer.parseInt(mColor,16);
int colorArr = Color.rgb(Color.red(aa),Color.green(aa),Color.blue(aa));
cell1.setBackgroundColor(new BaseColor(colorArr));

字体:

FontSelector selector = new FontSelector();
Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12);
f1.setColor(BaseColor.BLUE);
Font f2 = FontFactory.getFont("MSung-Light",
    "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
f2.setColor(BaseColor.RED);
selector.addFont(f1);
selector.addFont(f2);
Phrase ph = selector.process(TEXT);