首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在FontFactory.register中iText中加载自定义字体

如何在FontFactory.register中iText中加载自定义字体
EN

Stack Overflow用户
提问于 2015-07-31 13:06:53
回答 4查看 16.6K关注 0票数 5

在添加自定义字体"arial.ttf“时,我需要您的帮助,该字体存储在FontFactory.register方法中的iText项目的资源文件夹下。

Windows资源管理器中的项目中的字体路径如下:

public_html\resources\fonts\arial.ttf

引用字体的代码是:

代码语言:javascript
复制
FontFactory.register("/resources/fonts/arial.ttf", "my_bold_font");
Font myBoldFont = FontFactory.getFont("my_bold_font");

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

java.io.IOException: /resources/fonts/arial.ttf没有作为文件或资源找到。

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

/public_html/resources/fonts/arial.ttf /资源/字体/arial.ttf /字体/arial.ttf /arial.ttf

但结果相同,无法找到该文件。那么如何引用文件呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-05-03 12:31:21

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

代码语言:javascript
复制
URL font_path = Thread.currentThread().getContextClassLoader().getResource("fontname");
FontFactory.register(font_path.toString(), "test_font");

我已经测试过这段代码,它运行得很好。

票数 7
EN

Stack Overflow用户

发布于 2015-07-31 18:24:49

该守则是通过以下方式完成的:

代码语言:javascript
复制
 FontFactory.register(System.getProperty("file.separator")+"resources"+System.getProperty("file.separator")+"fonts"+System.getProperty("file.separator")+"arial.‌​ttf", "my_bold_font");
 Font myBoldFont = FontFactory.getFont("my_bold_font");
票数 1
EN

Stack Overflow用户

发布于 2017-02-01 22:50:54

我尝试过将存储在文件夹"src/main/webapp/resources/ fonts“中的所有字体添加到XMLWorkerFontProvider中。

成功地发挥了作用。

代码语言:javascript
复制
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);

URL font_path = Thread.currentThread().getContextClassLoader().getResource("resources/fonts");

File directory = new File(font_path.getPath());

//get all the files from a directory

File[] fList = directory.listFiles();

for (File file : fList){

    System.out.println("Font File Path******************************   " +file.getPath());
    fontImp.register(file.getPath());
} 
FontFactory.setFontImp(fontImp);

Document document = new Document();
Rectangle one = new Rectangle(width,height);
document.setPageSize(one);
document.setMargins(1, 1, 1, 1);
ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
PdfWriter pdfWriter=PdfWriter.getInstance(document, new FileOutputStream(folderPath+"/"+fileName));
document.open();

InputStream is = new ByteArrayInputStream(html.getBytes());
//XMLWorkerHelper.getInstance().parseXHtml(pdfWriter,document, is);
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter,document, is, null, null,fontImp);
document.close();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31746950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档