从jar为fop加载字体

ohfgkhjo  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(331)

我有一个ttf字体 fonts 我的应用程序的jar目录。

myapp.jar /
     fop /
        config.xml
        font.ttf

我创建fop的方式如下:

FopFactory fopFactory = FopFactory.newInstance();
    fopFactory.setStrictValidation(false);
    fopFactory.setUserConfig(getClasspathFile("/fop/config.xml"));
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
   ...

如何配置 config.xml 嵌入 font.ttf 在我正在渲染的pdf文件中?

5ktev3wc

5ktev3wc1#

看来我的帖子太迟了,但可能对其他人有用[java 8,fop 2.1版]

import lombok.SneakyThrows;
...
        @SneakyThrows
            private FopFactory getFopFactory(){
                InputStream fopConfigStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("/fop/config.xml");
                FopFactoryBuilder builder = new FopFactoryBuilder(new File(".").toURI(), new CustomPathResolver());
                FopFactory factory = builder.setConfiguration(new DefaultConfigurationBuilder().build(fopConfigStream)).build();
                fopConfigStream.close();
                return factory;
            }
    ...
        private static final class CustomPathResolver implements ResourceResolver {
            @Override
            public OutputStream getOutputStream(URI uri) throws IOException {
                return Thread.currentThread().getContextClassLoader().getResource(uri.toString()).openConnection()
                        .getOutputStream();
            }

            @Override
            public Resource getResource(URI uri) throws IOException {
                InputStream inputStream = ClassLoader.getSystemResourceAsStream("fop/" + FilenameUtils.getName(uri));
                return new Resource(inputStream);
            }
        }

config.xml文件:

<fop version="1.0">
    <renderers>
        <renderer mime="application/pdf">
            <fonts>
              <font kerning="yes" embed-url="font.ttf" embedding-mode="subset">
                <font-triplet name="Font name" style="normal" weight="normal"/>
              </font>
            </fonts>
        </renderer>
    </renderers>
</fop>

相关问题