如何使用自定义字体从servlet使用iText + XMLWorker创建PDF?

时间:2015-06-08 14:58:25

标签: java pdf servlets itext xmlworker

使用iText / XMLWorker示例(主要是this one),我可以轻松编写能够使用我自己的额外字体从HTML代码创建PDF文件的简单应用程序,但是一旦尝试在某些Web中使用我的东西服务代码,我结束了例外:

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

...似乎指出在Web服务上下文中,字体文件无法按预期加载。这是我的大部分代码:

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());
    ...

我应该依赖这样的事情:

  1. 从临时文件中的资源中提取字体(参见here
  2. 然后,在自定义字体工厂中预加载字体(参见there
  3. 感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

回答自己,因为我找到了问题的来源:我不得不指示Maven做资源字体文件的文字副本(常规过滤过程正在改变文件并破坏字体):

    <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>