Itext New Font with Bold and Underline

Shr*_*rey 5 java fonts itext

我正在尝试为我的pdf添加新字体,我需要将其加粗和加下划线..

我可以添加新的Font,但不能同时加粗和加下划线.

我尝试了以下方式..

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

    }

}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

小智 18

您可以使用两种样式定义字体对象:

private static final Font SUBFONT = new Font(Font.getFamily("TIMES_ROMAN"), 12,    Font.BOLD|Font.UNDERLINE);
Run Code Online (Sandbox Code Playgroud)


pat*_*ter 7

在您使用IText库时,请阅读此处.

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

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

我自己没试过,所以我不知道结果如何.进一步阅读iText文档,似乎必须先定义粗体字然后再实现它.本教程显示了使用iText加粗字体使用并使用粗体文本制作pdf的示例.从那里,我确信你可以将上面的代码实现为粗体文本和walah !,带下划线的粗体文本:D