Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

java - Load a font from JAR for FOP

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...