如何在PDFTable中为PDFCell定义不同的字体样式

时间:2015-07-27 18:10:53

标签: java fonts pdf-generation itext

我需要你的助手应用不同的字体样式,使字体粗体和对齐为PDFTable中标题单元格的中心,下面的单元格不是粗体,但左边的对齐方式不同。

使用当前代码,我只能将标题单元格设置为粗体并将标题内容对齐到中心,我需要您的帮助来修改动态生成的下面单元格的字体并更改对齐方式向左。那我怎么能这样做呢?

目前的代码是:

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

1 个答案:

答案 0 :(得分:1)

你可以包装那些字体&amp; alignment属性作为Phrase构造函数的参数,然后将其传递给.addCell( )。第一个arg。用于对齐和第3个字体。

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

对于左对齐,您只需将元素属性设置为Element.ALIGN_LEFT&amp;使用非粗体字体Font.NORMAL

所以它会是:

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

只是为了让您记住Font课程来自com.itextpdf.text.Font而不是java.awt.Font