0

这是我的 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;
    }

我的程序结构是:

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

这是不起作用的代码片段:

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

当我打开 PDF 时,文本在那里,但使用了一些我猜是默认字体的字体。

注意1:我尝试将字体设置为仅短语(p)和仅段落(pa),但这并没有以任何方式改变输出。

注2:Resource.loadFont("wingding"); 方法 try/catch 没有“捕获”任何错误。

4

1 回答 1

4

尝试创建一个嵌入的字体对象并使用此字体来呈现您的文本:

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

顺便说一句,iText 有帮助加载字体的类,你FontFactory不再需要.loadFontResources

希望能帮助到你。

于 2012-09-08T18:04:37.447 回答