Embedding Apache fop 2.1 in java servlet

2019-02-23 18:19发布

问题:

I have an application that uses Apache FOP to generate PDF files. Everything works great, except Cyrillic letters in the generated PDF. As far as I understand, I am supposed to bundle font that has Cyrillic letters with the application.

So, I set the application as follows: I have config file in ../src/main/resources/conf/fop.xml (pretty much default one for PDF renderer) and initialise FOP like this:

FopFactoryBuilder fopBuilder =
  new FopFactoryBuilder(fileLoader.getFile("conf/fop.xml").toURI(),
    new ClasspathResolverURIAdapter());
fopFactory = fopBuilder.build();

fileLoader is my own utility for reading files, XSLT is loaded by it and everything works great. I tried another ways to do so, with no luck. Fop itself works great, except for the fonts.

In config I have:

<renderers>
    <renderer mime="application/pdf">
      <filterList>
        <value>flate</value>
      </filterList>
      <fonts>
        <directory recursive="true">./</directory>
        <auto-detect/>
      </fonts>
    </renderer>
  </renderers>

Fonts are in subdirectory under conf/.

My XSLT references the fonts and via command-line everything works fine, I get the result I want, so I guess, that XSLT is correct.

I see two problems:

  • I do not see any reaction from fop runtime, when I change the config, even if I make it broken.
  • Fonts, of course, are not loaded.

Probably I am missing something very obvious here and hope that someone could guide me.

回答1:

At the moment you are not using your configuration file, so the fonts are not configured and they are not embedded in the PDF output.

The URI parameter in the FopFactoryBuilder constructor is used to resolve relative URIs, not to load the configuration file.

As per embedding instructions, your code should have something similar to this:

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;

...

DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
Configuration cfg = cfgBuilder.buildFromFile(new File("conf/conf.xml"));
FopFactoryBuilder fopFactoryBuilder = new FopFactoryBuilder(new File(".").toURI()).setConfiguration(cfg);
FopFactory fopFactory = fopFactoryBuilder.build();