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

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

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

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

我不得不指示 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>