Creating fonts from *.ttf files using iText

2019-03-03 14:17发布

问题:

This is a method inside my Resources.class:

public static Font loadFont(String fontFileName)
    {
        BaseFont base = null;

        try
        {
            base = BaseFont.createFont(Resource.class.getResource(fontFileName + "_font.ttf").toString(), BaseFont.WINANSI, true);
        }
        catch (DocumentException | IOException e)
        {
            e.printStackTrace();
        }

        Font font = new Font(base, Font.BOLD, 15);
        return font;
    }

Structure of my program is:

src (folder)
    core (package)
        //all (but one) classes used for program
    resources (package)
        class Resources (used to load resources into the "core" classes)
        wingding_font.ttf

This is the snippet of the code which isn't working:

p = new Phrase("some random text");
p.setFont(Resource.loadFont("wingding"));
pa = new Paragraph(p);
pa.setFont(Resource.loadFont("wingding"));
document.add(pa);

When I open the PDF, text is there, but some font, which I guess is the default font, is used.

Note1: I tried to setting font to only Phrase(p), and to only Paragraph(pa), but that didn't change output in any way.

Note2: The Resource.loadFont("wingding"); methods try/catch didn't "catch" any errors.

回答1:

Try to create an embedded font object and use this font to render your text:

//this code should run once at initialization/application startup
FontFactory.register("resources/wingding_font.ttf");
Font textFont = FontFactory.getFont("wingding", BaseFont.IDENTITY_H, 
    BaseFont.EMBEDDED, 10); //10 is the size
...
//reuse the reference to the font object when rendering your text
Paragraph p = new Paragraph("someText", textFont);

By the way, iText has the FontFactory class to help load your fonts, you don't need anymore the loadFont method in your Resources.

Hope it helps.