如何在iText中的FontFactory.register中加载自定义字体 [英] How to load custom font in FontFactory.register in iText

查看:1151
本文介绍了如何在iText中的FontFactory.register中加载自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助,在iText的 FontFactory.register 方法中添加一个自定义字体arial.ttf,该字体存储在我的项目的resources文件夹下。 / p>

在Windows资源管理器中,字体路径如下:


public_html \resources\fonts\arial.ttf


引用字体的代码是:

  FontFactory.register(/ resources / fonts / arial.ttf,my_bold_font); 
Font myBoldFont = FontFactory.getFont(my_bold_font);

但是,当我运行Java方法时,它总是给我错误:
$ b


java.io.IOException:/resources/fonts/arial.ttf未找到文件或
资源。


我尝试了不同的路径,例如:

lockquote
p public_html / resources / fonts /arial.ttf

../ resources / fonts / arial.ttf

/fonts/arial.ttf

/arial.ttf

但结果是一样的文件无法找到。那么如何引用这个文件?

解决方案

您可以获取资源文件夹中的字体 ,使用 contextClassLoader ,可以在 FontFactory 文件路径中使用。

  URL font_path = Thread.currentThread()。getContextClassLoader()。getResource(fontname); 
FontFactory.register(font_path.toString(),test_font);

我测试了这个代码,它工作的很好。


I need your help in adding a custom font "arial.ttf" which is stored under the resources folder in my project in the FontFactory.register method in iText.

The font path is as follows in the project from Windows Explorer:

public_html\resources\fonts\arial.ttf

The code for referring to the font is:

FontFactory.register("/resources/fonts/arial.ttf", "my_bold_font");
Font myBoldFont = FontFactory.getFont("my_bold_font");

However when I ran the Java method, it always gives me the error:

java.io.IOException: /resources/fonts/arial.ttf not found as file or resource.

I tried with different paths for example:

/public_html/resources/fonts/arial.ttf

../resources/fonts/arial.ttf

/fonts/arial.ttf

/arial.ttf

But the result is the same that the file can't be found. So how to refer to the file?

解决方案

You can get the path of the 'font' which are present in the resources folder, using contextClassLoader and can be used in the FontFactory file path.

URL font_path = Thread.currentThread().getContextClassLoader().getResource("fontname");
FontFactory.register(font_path.toString(), "test_font");

I have tested this code and it works fine.

这篇关于如何在iText中的FontFactory.register中加载自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆