2

使用 iText/XMLWorker 示例(主要是这个),我可以轻松编写简单的应用程序,能够使用我自己的额外字体从 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. 从临时文件中的资源中提取字体(参见此处
  2. 然后,在自定义字体工厂中预加载字体(参见那里
4

1 回答 1

3

我不得不指示 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>
于 2016-02-12T16:36:44.633 回答