Search code examples
apachepdfsvgapache-fop

Apache FOP embedded, how to use config file


I'm using Apache FOP to render an SVG to PDF. This SVG has a special font, that i want to use in the resulting PDF also.

I'm using a config File that looks like this:

<?xml version="1.0"?>
<fop version="1.0">
    <base>.</base>
    <source-resolution>72</source-resolution>
    <target-resolution>72</target-resolution>
    <default-page-settings height="11.00in" width="8.50in" />
    <renderers>
        <renderer mime="application/pdf">
            <filterList>
                <value>flate</value>
            </filterList>
            <fonts>
                <font
                    metrics-url="path/to/metrics.xml"
                    kerning="yes"
                    embed-url="path/to/font.ttf">
                    <font-triplet name="font name" style="normal" weight="normal" />
                </font>
            </fonts>
        </renderer>
    </renderers>
</fop>

Which i copied and pasted from the example config, and edited out all the renderers i don't need. Now i'm trying to use the configuration like this:

public void convertSVG2PDF(String svg, OutputStream out) throws IOException, TranscoderException {

        // Create transcoder
        AbstractFOPTranscoder transcoder = new PDFTranscoder();
        DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
        Configuration cfg;

        try {
            File configFile = new File("path/to/config.xml");

            cfg = cfgBuilder.buildFromFile(configFile);
            transcoder.configure(cfg);
            System.err.println(cfg.getValue());
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        // Setup input
        Reader in = new java.io.StringReader(svg);

        try {
            TranscoderInput input = new TranscoderInput(in);
            // Setup output
            try {
                TranscoderOutput output = new TranscoderOutput(out);
                // Do the transformation
                transcoder.transcode(input, output);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }

This renders a perfectly fine PDF, but the font is not used. I also get this message when i try cfg.getValue()

No value is associated with the configuration element "fop" at file:/path/to/conf.xml:1:20

I also tried renaming the config to .xconf, but that didn't change anything.


Solution

  • Try this...It worked for me:

    FopFactory fopFactory;
    fopFactory = FopFactory.newInstance();
    
    
    
    File configFile = new File("path/to/config.xml");
    fopFactory.setUserConfig(configFile);