Set FopFactoryBuilder baseURI to jar classpath

我怕爱的太早我们不能终老 提交于 2019-11-29 11:07:29

We also used FOP 2.1 and want to achieve, that images inside jars-classpath will be found. Our tested and used solution is the following:

Create your own ResourceResolver

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;

import org.apache.fop.apps.io.ResourceResolverFactory;
import org.apache.xmlgraphics.io.Resource;
import org.apache.xmlgraphics.io.ResourceResolver;

public class ClasspathResolverURIAdapter implements ResourceResolver {

  private final ResourceResolver wrapped;


  public ClasspathResolverURIAdapter() {
    this.wrapped = ResourceResolverFactory.createDefaultResourceResolver();
  }


  @Override
  public Resource getResource(URI uri) throws IOException {
    if (uri.getScheme().equals("classpath")) {
      URL url = getClass().getClassLoader().getResource(uri.getSchemeSpecificPart());

      return new Resource(url.openStream());
    } else {
      return wrapped.getResource(uri);
    }
  }

  @Override
  public OutputStream getOutputStream(URI uri) throws IOException {
    return wrapped.getOutputStream(uri);
  }

}
  1. Create the FOPBuilderFactory with your Resolver
FopFactoryBuilder fopBuilder = new FopFactoryBuilder(new File(".").toURI(), new ClasspathResolverURIAdapter());
  1. Finally address your image
<fo:external-graphic src="classpath:com/mypackage/image.jpg" />

Because you use our own Resolver it is possible to do every lookup which you want.

By specifying the URL as a classpath URL like:

<fo:external-graphic src="classpath:fop/images/myimage.jpg"/>

In this example the file is a resource in the resource-package fop.images but the actual file gets later packed to some entirely different place inside the JAR, which is - however - part of the classpath, so the lookup as above works.

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