How to create a PDF with iText+XMLWorker from servlet using custom font?

元气小坏坏 提交于 2019-12-30 07:31:33

问题


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:

  1. Extract fonts from resources in temporary files (cf. here)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!