Scriptico

Apache FOP. embed-url and the classpath resource

Fortunately, I opened for myself incredible Apache FOP. So, I did few templates and faced up a problem to specified a path of the resource for the embed-url parameter in the following part of the apache fop config:

	
		
			
		
	


Ok, few words about my project. Apache FOP is embedded into a Java web application and obviously, I do use it through a servlet. Also, my pdf contains some special characters and it can’t be rendered correctly with “basic” fonts. As a result, I have to use a special font. Apache FOP configuration gives to me this opportunity and it could be done by using the configuration file as it shown above. Unfortunately, the embed-url parameter is not really smart guy and it understands only absolute paths. Apparently, I have no way to use an absolute path of the font and I must be able to load the font from the classpath location. No problem, I figured out how to achieve it!

1. Create a class wich implements javax.xml.transform.URIResolver interface as it shown below:

package com.project.pdf;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;

public final class CustomPathResolver implements URIResolver {

	@Override
	public Source resolve(String href, String base) throws TransformerException {
		return new StreamSource(getClass().getResourceAsStream(href));
	}
}

According to the Java API, the resolve method has the following parameters:

href – An href attribute, which may be relative or absolute.
base – The base URI against which the first argument will be made absolute if the absolute URI is required.

I do not care about the base parameter, yet the href parameter is a value of the embed-url guy. So, in the overridden resolve method I used a convenient way to rich a source from the passed class path.

2. Now I have to say to FOP to use the custom path resolver. To accomplish it, in my servlet I did the following:

import org.apache.fop.apps.FOURIResolver;

public final class PdfServlet extends HttpServlet {

	private FopFactory fopFactory = FopFactory.newInstance();

	@Override
	public void init() throws ServletException {
		FOURIResolver uriResolver = (FOURIResolver) fopFactory.getURIResolver();
		uriResolver.setCustomURIResolver(new CustomPathResolver());

		super.init();
	}

That is it! Everything works fine!

Category: Development, Java, WebApp

Tagged:

Leave a Reply

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.