问题
Playing with iText/XMLWorker samples (mostly this one), I could easily write simple applications able to create PDF files from HTML code using my own extra fonts, but as soon as tried to use my stuff in some web service code, I ended with exceptions like:
Table 'name' does not exist in file:/C:/work/MyServer/target/classes/fonts/My%20Font.ttf
ExceptionConverter: com.itextpdf.text.DocumentException: Table 'name' does not exist in file:/C:/work/MyServer/target/classes/fonts/My%20Font.ttf
...which seems to point out that in a web service context, the font file couldn't be loaded as expected. Here's most of my code:
public HtmlRenderer(final String css, final String[] fontPaths) {
// fontPaths = {
// "/fonts/My Font.ttf",
// "/fonts/My Other Font.ttf",
// ...
// };
// CSS
cssResolver = new StyleAttrCSSResolver();
if (css != null) {
final CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(css.getBytes()));
cssResolver.addCss(cssFile);
}
// HTML
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
if (fontPaths != null) {
for (final String fontPath : fontPaths) {
final String path = this.getClass().getResource(fontPath).toExternalForm();
fontProvider.register(path);
}
}
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
...
Should I rely on things like:
- Extract fonts from resources in temporary files (cf. here)
- Then, preload fonts in a custom font factory (cf. there)
Thanks for the help!
回答1:
answering myself since I have found where the problem come from: I had to instruct Maven to do literal copies of resource font files (the regular filtering process was altering the files and corrupting the fonts):
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.ttf</exclude>
</excludes>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/*.ttf</include>
</includes>
</resource>
...
</resources>
来源:https://stackoverflow.com/questions/30712551/how-to-create-a-pdf-with-itextxmlworker-from-servlet-using-custom-font