Load a font from JAR for FOP

最后都变了- 提交于 2021-01-15 18:00:29

问题


I have a TTF font in fonts directory in the JAR with my application.

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

I create my FOP this way:

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

How do I configure config.xml to embeddd font.ttf in the PDF file I am rendering?


回答1:


it seems that my post is too late, but may be it'll be useful for the others. [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>


来源:https://stackoverflow.com/questions/17745133/load-a-font-from-jar-for-fop

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