如何在运行时以编程方式加载字体扩展?
How to programmatically load font extension at runtime?
我知道 jasperreports_extension.properties
以及如何放入类路径以使字体可用于 jasper 报告。
我想在运行时动态加载它们的字体,而不是在应用程序启动时在类路径中提供它们。
Jasper 中是否有我可以使用的 API,如果可以,如何使用?
如果可能的话,我更喜欢 Jasper 5.x.
的答案
您可以通过创建 JasperReportsContext
实例(例如 SimpleJasperReportsContext
)以编程方式注册字体扩展和其他扩展类型,将扩展添加到上下文对象,然后在填充和导出报告时使用它.
代码看起来像这样:
//create the context object and the font extension
SimpleJasperReportsContext jasperReportsContext = new SimpleJasperReportsContext();
SimpleFontFamily fontFamily = new SimpleFontFamily(jasperReportsContext);
fontFamily.setName("family name");//to be used in reports as fontName
fontFamily.setPdfEmbedded(true);
fontFamily.setPdfEncoding("Identity-H");
SimpleFontFace regular = new SimpleFontFace(jasperReportsContext);
regular.setTtf("font ttf path");
fontFamily.setNormalFace(regular);
jasperReportsContext.setExtensions(FontFamily.class, Arrays.asList(fontFamily));
//use the context when filling and exporting reports
//note that there are variations here depending on the API you use for filling and exporting
JasperPrint jasperPrint = JasperFillManager.getInstance(jasperReportsContext).fill(jasperReport, params);
...
JasperExportManager.getInstance(jasperReportsContext).exportToPdf(jasperPrint);
...
JRPdfExporter exporter = new JRPdfExporter(jasperReportsContext);
我知道 jasperreports_extension.properties
以及如何放入类路径以使字体可用于 jasper 报告。
我想在运行时动态加载它们的字体,而不是在应用程序启动时在类路径中提供它们。
Jasper 中是否有我可以使用的 API,如果可以,如何使用? 如果可能的话,我更喜欢 Jasper 5.x.
的答案您可以通过创建 JasperReportsContext
实例(例如 SimpleJasperReportsContext
)以编程方式注册字体扩展和其他扩展类型,将扩展添加到上下文对象,然后在填充和导出报告时使用它.
代码看起来像这样:
//create the context object and the font extension
SimpleJasperReportsContext jasperReportsContext = new SimpleJasperReportsContext();
SimpleFontFamily fontFamily = new SimpleFontFamily(jasperReportsContext);
fontFamily.setName("family name");//to be used in reports as fontName
fontFamily.setPdfEmbedded(true);
fontFamily.setPdfEncoding("Identity-H");
SimpleFontFace regular = new SimpleFontFace(jasperReportsContext);
regular.setTtf("font ttf path");
fontFamily.setNormalFace(regular);
jasperReportsContext.setExtensions(FontFamily.class, Arrays.asList(fontFamily));
//use the context when filling and exporting reports
//note that there are variations here depending on the API you use for filling and exporting
JasperPrint jasperPrint = JasperFillManager.getInstance(jasperReportsContext).fill(jasperReport, params);
...
JasperExportManager.getInstance(jasperReportsContext).exportToPdf(jasperPrint);
...
JRPdfExporter exporter = new JRPdfExporter(jasperReportsContext);