99maas
99maas

Reputation: 1267

How to define different font styles to PDFCells in a PDFTable

I need your assistant in applying different font styles to make the font bold and the alignment to center for the header cell in a PDFTable and the below cells to be not bold, but with different alignment to the left.

With the current code, I am able only to set the header cell to bold and to align the header content to center, where I need your help to modify the font for the below cells which are generated dynamically and to change the alignment to left. So how can I do this?

The current code is:

dfPTable table = new PdfPTable(2);
Font earningsTitlefont = new Font(Font.TIMES_ROMAN,12, Font.BOLD);
PdfPCell c1 = new PdfPCell(new Phrase("Earnings Description",earningsTitlefont));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Earnings Amount",earningsTitlefont));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

for (int i = 0; i < listEarnings.size(); i++) {
    String temp1 = listEarnings.get(i).getEarningsDescriptionSS();
    String temp2 = listEarnings.get(i).getEarningsAmountSS();

    table.addCell(temp1); 
    table.addCell(temp2);
}

Upvotes: 0

Views: 2246

Answers (1)

Fevly Pallar
Fevly Pallar

Reputation: 3099

You can wrap those font & alignment attributes as arguments for Phrase constructor, then you pass it to .addCell( ). 1st arg. for alignment & 3rd for font.

table.addCell( new Phrase(Element.ALIGN_LEFT,"text",new Font(..,..,...) ));

For the left align, you just need to set element attribute to Element.ALIGN_LEFT & to use non-bold font use Font.NORMAL

So it would be:

Font plainFont= new Font(Font.FontFamily.COURIER, 14,
                    Font.NORMAL);

for (int i = 0; i < listEarnings.size(); i++) {
    String temp1 = listEarnings.get(i).getEarningsDescriptionSS();
    String temp2 = listEarnings.get(i).getEarningsAmountSS();


      table.addCell( new Phrase(Element.ALIGN_LEFT,temp1,plainFont));
     table.addCell( new Phrase(Element.ALIGN_LEFT,temp2,plainFont));
   // table.addCell(temp1); 
   // table.addCell(temp2);
}

Just to make you remember that the Font class comes from com.itextpdf.text.Font not java.awt.Font

Upvotes: 1

Related Questions