2013-03-20 1227 views
4

我尝试新的字体添加到我的PDF,我需要使它粗体和下划线..iText的新字体用粗体部分和下划线

我可以添加新的字体,但不能让它大胆和下划线同时。

我尝试以下方式..

public class PdfGenerator { 

    private static final String BASE_FONT = "Trebuchet MS"; 
    private static final String BASE_FONT_BOLDITALIC = "Trebuchet MS BI"; 
    private static final String BASE_FONT_BOLD = "Trebuchet MS B"; 

    private static final Font titlefontSmall = FontFactory.getFont(
      BASE_FONT_BOLD, 10, Font.UNDERLINE); 

    static { 
     String filePath = "..my font directory"; 
     String fontPath = filePath + "\\" + "trebuc.ttf"; 
     String fontPathB = filePath + "\\" + "TREBUCBD.TTF"; 
     String fontPathBI = filePath + "\\" + "TREBUCBI.TTF"; 

     FontFactory.register(fontPath, BASE_FONT); 
     FontFactory.register(fontPathB, BASE_FONT_BOLD); 
     FontFactory.register(fontPathBI, BASE_FONT_BOLDITALIC); 
    } 

    public void genMyPdf(String filePath) { 
     try { 
      Document document = new Document(); 
      PdfWriter writer = PdfWriter.getInstance(document, 
        new FileOutputStream(filePath)); 
      document.open(); 

      Paragraph p = new Paragraph("This should be bold & underline", 
        titlefontSmall); 
      document.add(p); 
      document.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (DocumentException e) { 
      e.printStackTrace(); 
     } 

    } 

} 

我在做什么错?

回答

5

HERE阅读了,因为你正在使用的iText库。

基本上使用块,然后将这些块添加到文档。

Chunk underline = new Chunk("Underline. "); 
underline.setUnderline(0.1f, -2f); //0.1 thick, -2 y-location 
document.add(underline); 

我还没有尝试过自己,所以我不知道它是如何变成了呢。 进一步阅读iText文档,似乎您必须先定义粗体字体,然后再实施它。 THIS TUTORIAL显示了一个使用iText粗体字体和使用粗体文本制作pdf的例子。从那里,我敢肯定,你可以实现上面的代码中的粗体文字和walah!粗体下划线的文本:d

+0

它的工作thankss .. :) – Shrey 2013-03-21 06:34:44

+0

@Shrey没问题! – pattmorter 2013-03-21 15:25:08

1

尝试

Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD); 
     document.add(new Paragraph("Times-Roman, Bold", fontbold)); 

和Font.UNDERLINE它undeline

+1

我想这两个大胆和强调.. – Shrey 2013-03-21 06:35:44

10

可以定义字体对象有两种风格:

private static final Font SUBFONT = new Font(Font.getFamily("TIMES_ROMAN"), 12, Font.BOLD|Font.UNDERLINE); 
+0

这应该是公认的答案! – Pali 2015-07-01 09:44:49

+0

它有助于减少代码的工作量。谢谢@卡洛斯 – 2017-04-05 13:09:35

相关问题