Load a font from JAR for FOP
Asked Answered
C

2

10

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?

Cincture answered 19/7, 2013 at 11:34 Comment(0)
T
8

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>
Tinny answered 9/11, 2016 at 14:18 Comment(0)
C
1

I finally have a solution for apache fop 2.9 for referencing and using fonts within a jar file (and I included images and xsl file includes as well - because chances are that you would want to do that as well).

Full project code can be found: https://github.com/synapticloop/pdf-embed-test

For my purposes - I wish to have everything run through a jar file with no dependences on a filesystem. and by everything I mean:

  • fonts (i.e. <font kerning="yes" embed-url="classpath:///fonts/Poppins-LightItalic.ttf" embedding-mode="subset">)
  • images (i.e. <fo:external-graphic src="classpath:///images/puppy.jpg" content-width="7.02cm" />)
  • included stylesheets (i.e. <xsl:include href="/xsl/includes/page-templates.xsl" />)

For Fonts

To reference fonts within a jar file you will need to set the internal resource resolver on the fopFactory (this is what loads fonts from the fop config file).

FopFactory fopFactory = fopFactoryBuilder.build();

// This will allow you to load fonts from the fopconfig.xml i.e.
// <font kerning="yes" embed-url="classpath:///fonts/Poppins-LightItalic.ttf" embedding-mode="subset">
fopFactory.getFontManager().setResourceResolver(
        ResourceResolverFactory.createInternalResourceResolver(
                DEFAULT_BASE_URI,
                new ClasspathResourceResolver()));

For images

(i.e. external-graphics, you neet to set the resolver on the FopFactoryBuilder):

// this will allow you to reference external graphics from within a jar file
// i.e. <fo:external-graphic src="classpath:///images/puppy.jpg" content-width="7.02cm" />
FopFactoryBuilder fopFactoryBuilder = new FopFactoryBuilder(
        DEFAULT_BASE_URI,
        new ClasspathResourceResolver())
        .setConfiguration(cfg);

For xsl includes

You need to set the resource resolver on the TransformerFactory

    TransformerFactory factory = TransformerFactory.newInstance();

    // This allows you to reference includes within the xsl file
    // <xsl:include href="/xsl/includes/page-templates.xsl" />
    factory.setURIResolver(new ClasspathResourceURIResolver());

The complete Main file

import org.apache.fop.apps.*;
import org.apache.fop.apps.io.ResourceResolverFactory;
import org.apache.fop.configuration.DefaultConfiguration;
import org.apache.fop.configuration.DefaultConfigurationBuilder;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.net.URI;

public class Main {

    public static final URI DEFAULT_BASE_URI = new File(".").toURI();

    public static void main(String[] args) throws Exception {
        StreamSource xmlSource = new StreamSource(Main.class.getResourceAsStream("/xml/blank.xml"));

        DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
        DefaultConfiguration cfg = cfgBuilder.build(Main.class.getResourceAsStream("/config/fopconfig.xml"));

        // this will allow you to reference external graphics from within a jar file
        // i.e. <fo:external-graphic src="classpath:///images/puppy.jpg" content-width="7.02cm" />
        FopFactoryBuilder fopFactoryBuilder = new FopFactoryBuilder(
                DEFAULT_BASE_URI,
                new ClasspathResourceResolver())
                .setConfiguration(cfg);

        FopFactory fopFactory = fopFactoryBuilder.build();

        // This will allow you to load fonts from the fopconfig.xml i.e.
        // <font kerning="yes" embed-url="classpath:///fonts/Poppins-LightItalic.ttf" embedding-mode="subset">
        fopFactory.getFontManager().setResourceResolver(
                ResourceResolverFactory.createInternalResourceResolver(
                        DEFAULT_BASE_URI,
                        new ClasspathResourceResolver()));


        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

        // Setup output
        try (OutputStream out = new FileOutputStream("./embed-test.pdf")) {

            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

            TransformerFactory factory = TransformerFactory.newInstance();

            // This allows you to reference includes within the xsl file
            // <xsl:include href="/xsl/includes/page-templates.xsl" />
            factory.setURIResolver(new ClasspathResourceURIResolver());

            InputStream resourceAsStream = Main.class.getResourceAsStream("/xsl/embed-test.xsl");
            Transformer transformer = factory.newTransformer(new StreamSource(resourceAsStream));

            SAXResult res = new SAXResult(fop.getDefaultHandler());
            transformer.transform(xmlSource, res);
        }
    }
}

The ClasspathResourceResolver

import org.apache.xmlgraphics.io.Resource;
import org.apache.xmlgraphics.io.ResourceResolver;

import java.io.*;
import java.net.URI;

public class ClasspathResourceResolver implements ResourceResolver {
    @Override
    public Resource getResource(URI uri) throws IOException {
        String uriString = uri.toASCIIString();
        System.out.println(uriString);

        if(uriString.startsWith("classpath://")) {
            String substring = uriString.substring(12);
            System.out.println(substring);
            InputStream resourceAsStream = ClasspathResourceResolver.class.getResourceAsStream(substring);
            return (new Resource(resourceAsStream));
        } else if(uriString.startsWith("file://")) {
            String substring = uriString.substring(7);
            InputStream resourceAsStream = new FileInputStream(new File(substring));
            return(new Resource(resourceAsStream));
        } else {
            return new Resource(ClasspathResourceResolver.class.getResourceAsStream(uriString));
        }
    }

    @Override
    public OutputStream getOutputStream(URI uri) throws IOException {
        return new FileOutputStream(new File(uri));
    }
}

The ClasspathResourceURIResolver

import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;

public class ClasspathResourceURIResolver implements URIResolver {
    @Override
    public Source resolve(String href, String base) {
        InputStream resourceAsStream = ClasspathResourceURIResolver.class.getResourceAsStream(href);
        return new StreamSource(resourceAsStream);
    }
}
Codger answered 3/4 at 4:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.