我正在使用 itext 库将 html 转换为 pdf。我可以正确转换,但无法添加字体。我的转换器代码在这里
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
Template t = new Template("templateName", new StringReader(templateHTML), cfg);
Writer out = new FileWriter(new File(TARGET + documentName + ".html"));
t.process(model, out);
out.close();
ConverterProperties properties = new ConverterProperties();
properties.setBaseUri(TARGET);
File output = new File(TARGET + documentName + ".pdf");
FontProvider fontProvider = new DefaultFontProvider();
FontProgram fontProgram = FontProgramFactory.createFont(FONT);
fontProvider.addFont(fontProgram);
properties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(
new FileInputStream(TARGET + documentName + ".html"),
new FileOutputStream(TARGET + documentName + ".pdf"),
properties);
我的目标和字体在这里
public static String TARGET = "target/classes/documentsTemplate/";
public static final String FONT = "./src/main/resources/fonts/special.ttf";
我也尝试过像这样向 html 添加字体
* {
font-family: myFirstFont;
src: local("C:/font/special.ttf");
}
.text-font {
font-family: "myFirstFont";
}
我用这个代码解决了。
FontProvider fontProvider = new DefaultFontProvider(false, false, false);
fontProvider.addFont(FONT);
properties.setFontProvider(fontProvider);
但我无法将字体设为粗体
使用以下 gradle 依赖项:
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
implementation group: 'com.itextpdf', name: 'itext7-core', version: '7.2.5'
implementation group: 'com.itextpdf', name: 'html2pdf', version: '5.0.0'
implementation group: 'ognl', name: 'ognl', version: '3.1.12'
我附上了对我有用的解决方案:
// file is inside resources at the path specified here
public static final String FONT = "templates/fonts/Sans-Serif-Medium.ttf";
// font set up
FontProvider fontProvider = new DefaultFontProvider(false, false, false);
FontProgram fontProgram = FontProgramFactory.createFont(FONT);
fontProvider.addFont(fontProgram);
converterProperties.setFontProvider(fontProvider);
不幸的是,粗体不起作用。