在添加自定义字体"arial.ttf“时,我需要您的帮助,该字体存储在FontFactory.register方法中的iText项目的资源文件夹下。
Windows资源管理器中的项目中的字体路径如下:
public_html\resources\fonts\arial.ttf
引用字体的代码是:
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
但结果相同,无法找到该文件。那么如何引用文件呢?
发布于 2016-05-03 12:31:21
您可以使用contextClassLoader获取资源文件夹中的“字体”路径,并且可以在FontFactory文件路径中使用。
URL font_path = Thread.currentThread().getContextClassLoader().getResource("fontname");
FontFactory.register(font_path.toString(), "test_font");我已经测试过这段代码,它运行得很好。
发布于 2015-07-31 18:24:49
该守则是通过以下方式完成的:
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");发布于 2017-02-01 22:50:54
我尝试过将存储在文件夹"src/main/webapp/resources/ fonts“中的所有字体添加到XMLWorkerFontProvider中。
成功地发挥了作用。
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();https://stackoverflow.com/questions/31746950
复制相似问题