使用 iText 从 *.ttf 文件创建字体

2024-04-04

这是我的 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 没有“捕获”任何错误。


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

//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类来帮助加载你的字体,你不再需要loadFont方法在你的Resources.

希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 iText 从 *.ttf 文件创建字体 的相关文章

随机推荐