Itext新字体加粗和下划线。

6

我正在尝试向我的pdf文件中添加新字体,我需要将其加粗并带下划线。

我可以添加新字体,但无法同时将其加粗和带下划线。

我尝试了以下方法:

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个回答

22

您可以定义一个同时具有样式的字体对象:

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

它能够提供帮助并减少编码工作量。感谢@carlos。 - Kamal kannan

8

如果你正在使用IText库,请阅读这里的内容:链接

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

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

我自己没有尝试过,所以还不知道结果如何。进一步阅读iText文档后,似乎需要先定义一个粗体字体,然后再实现它。 这个教程展示了使用iText制作粗体文本的示例。从那里开始,我相信你可以将上面的代码实现到粗体文本中,然后就有了加粗和下划线的文字:D


2
您可以在类中定义您的字体,如下所示:
 public final static Font CUSTOM_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD | Font.UNDERLINE);

然后将其用作:
paragraph.add(new Phrase( " YOUR TEXT HERE ",PDFCreator.CUSTOM_FONT));

1

尝试一下

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

并且使用 Font.UNDERLINE 来添加下划线。


0
你可以使用以下代码来同时实现加粗和下划线效果:
Chunk buyerOrder = new Chunk("Buyer's Order Number", FontFactory.getFont(FontConstants.TIMES_ROMAN,8,Font.BOLD));
buyerOrder.setUnderline(0.1f, -2f); 

希望能有所帮助!谢谢


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接