繁体   English   中英

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

[英]How to change cell color in iText Java

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

下面的代码只是制作了一个带有标题的表格。 这是pdf上的当前输出

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM