Adding images to html in Jasper Reports

In my last blog post I discussed about Generating jasper reports in different formats using json file as a data source.You can find my last post here. In this blog article I will discuss about exporting the jasperPrint object in different formats like pdf, html, csv, xls and docx using the newer API of jasper reports.

Exporting the jasperPrint object which consists of images into html format is a tedious task with the jasper’s deprecated API found all over the internet. I have tried using the JRHtmlExporter class that consists of mostly deprecated methods and using it I couldn’t get the images in the jrxml in the html format.

So, I wanted to write a blog post to help my fellow programmers to illustrate how it can be done with the new API of jasper reports. HtmlExporter class is part of new API and using it one can export the report to html format.

To do this first we need to place the jasperPrint object in the http session using the following code.

request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);

After placing the jasperPrint object in the session, we need to set the image handler for images in the report using the code,

exporterOutput.setImageHandler(new WebHtmlResourceHandler("image?image={0}"));

The images are served by ImageServlet which should be mapped to ‘/image’ in the web.xml. Here is the configuration that should be added to web.xml file.

 <servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class> </servlet>
 <servlet-mapping>
     <servlet-name>ImageServlet</servlet-name>
     <url-pattern>/image</url-pattern>
 </servlet-mapping>

The JasperCompileManager.compileReport(jrxmlSource) method compiles and generates a jasperReport object which is used to generate jasperPrint object using the JasperFillManager.fillReport(jasperReport, parameters, dataSource) method. In the following example the dataSource is populated using a string which is in json format. I am exporting the generated documents to the response. So, accordingly I have set content-type, content-disposition headers appropriately, which I have not shown in the code. The headers are set for all formats except for the type html as htmls are to be displayed in the browser along with images.

You can refer my previous blog post for maven dependencies. I have used commons-io dependency in addition to the previous dependencies.

		
        private static final Logger logger = LoggerFactory.getLogger(YOURCLASS.class);
	JRDataSource dataSource = getDataSource(jsonData);//pass jsonData to populate the dataSource
	JasperReport jasperReport = null;
	JasperPrint jasperPrint = null;
	//String type = Any of the types mentioned above
	//jrxmlSource is the the jrxml generated using the iReport
	
	Map<String, Object> parameters = new HashMap<String, Object>();
	//Add any parameters that are referenced in the jrxml to this map

	try {
		jasperReport = JasperCompileManager.compileReport(jRXMLSource);
		jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
	} catch (JRException ex) {
		ex.printStackTrace();
	}

	if ("pdf".equals(type)) {
		JRPdfExporter exporter = new JRPdfExporter();
		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
                        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
			exporter.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting for pdf format", e);
			e.printStackTrace();
		}

	} else if ("xls".equals(type)) {

		JRXlsExporter exporter = new JRXlsExporter();
		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
   		        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
			SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
			configuration.setOnePagePerSheet(true);
			exporter.setConfiguration(configuration);
			exporter.exportReport();
		} catch (JRException e) {
			logger.error("JRException while exporting for xls format", e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		}

	} else if ("csv".equals(type)) {
		JRCsvExporter exporter = new JRCsvExporter();
		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
			exporter.setExporterOutput(new SimpleWriterExporterOutput(response.getOutputStream()));
			exporter.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting report csv format", e);
			e.printStackTrace();
		}
	} else if ("html".equals(type)) {
		request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,jasperPrint);

		HtmlExporter exporterHTML = new HtmlExporter();
		SimpleExporterInput exporterInput = new SimpleExporterInput(jasperPrint);
		exporterHTML.setExporterInput(exporterInput);

		SimpleHtmlExporterOutput exporterOutput;
		try {
			exporterOutput = new SimpleHtmlExporterOutput(response.getOutputStream());
			exporterOutput.setImageHandler(new WebHtmlResourceHandler("image?image={0}"));
			exporterHTML.setExporterOutput(exporterOutput);
			
		        SimpleHtmlReportConfiguration reportExportConfiguration = new SimpleHtmlReportConfiguration();
			reportExportConfiguration.setWhitePageBackground(false);
			reportExportConfiguration.setRemoveEmptySpaceBetweenRows(true);
			exporterHTML.setConfiguration(reportExportConfiguration);
			exporterHTML.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting for html format", e);
			e.printStackTrace();
		}
	} else if ("docx".equals(type)) {
		JRDocxExporter exporter = new JRDocxExporter();

		try {
			exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
		        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
			exporter.exportReport();
		} catch (IOException e) {
			logger.error("IOException occured", e);
			e.printStackTrace();
		} catch (JRException e) {
			logger.error("JRException while exporting for docx format", e);
			e.printStackTrace();
		}
	}


	public JRDataSource getDataSource(String jsonData) {
		logger.info("jsonData = " + jsonData);
		JRDataSource dataSource = null;

		if ("null".equals(jsonData) || jsonData == null || "".equals(jsonData)) {
			logger.info("jsonData parameter value is null. Creating JREmptyDataSource");
			dataSource = new JREmptyDataSource();
			return dataSource;
		}

		InputStream jsonInputStream = null;
		try {
			// Convert the jsonData string to inputStream
			jsonInputStream = IOUtils.toInputStream(jsonData, "UTF-8");
			// selectExpression is based on the jsonData that your string contains
			dataSource = new JsonDataSource(jsonInputStream, "data");
		} catch (IOException ex) {
			logger.error("Couldn't covert string into inputStream", ex);
			ex.printStackTrace();
		} catch (JRException e) {
			logger.error("Couldn't create JsonDataSource", e);
			e.printStackTrace();
		}

		if (dataSource == null) {
			dataSource = new JREmptyDataSource();
			logger.info("dataSource is null. Request parameter jsondData is null");
		}

		return dataSource;
	}

Hope the above code helps to resolve the issue of getting the images in html format. The images can be placed in WEB-INF/classes directory if the directory is not mentioned in the jrxml. If the directory is mentioned then the path should supplied as a parameter which should be kept inside parameters map.

Wish you happy coding!!

Rajasekhar
Helical IT Solutions

PhantomJS and its “Render” function

PhantomJS – The Headless Webkit browser & its “Render” function

In this blog, we will have a quick introduction of PhantomJS and talk about its “Screen Capture” feature to render webpages or parts of webpages into images or PDFs.

PhantomJS is a headless browser which has a JavaScript API. It can be used for headless web-testing, page automation, network monitoring and the likes. It supports various test frameworks like Jasmine, Capybara, QUnit, Mocha, WebDriver, YUI Test, BusterJS, FuncUnit, Robot Framework. It has a native support for various web standards like DOM handling, CSS selectors, SVG, JSON etc. It can access and manipulate webpages with the standard DOM API or with libraries like JQuery. As PhantomJS permits the inspection of network traffic, it is suitable to build various analyses on the network behavior and performance as well.

PhantomJS – Screen Capture using “Render” function

Among one of its many capabilities, is the capability to programmatically capture web contents, including SVG and Canvas and save them as images or PDFs.
PhantomJS uses WebKit which is an open source web browser engine. As it uses a real layout and rendering engine, it can capture a web page as a screenshot. Because PhantomJS can render anything on the web page, it can be used to convert contents not only in HTML and CSS, but also SVG and Canvas. The PDFs are generated with selectable texts and embedded fonts.
The function used for this is –

render(filename [, {format, quality}]) {void}

Renders the web page to an image buffer and saves it as the specified filename. The output format is automatically set based on the file extension.

Supported formats:
PNG
GIF
JPEG
PDF

Quality:An integer between 0 and 100.

Working Example:

var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = { width: 1920, height: 1080 };
page.open("http://www.google.com", function start(status) {
page.render('google_home.jpeg', {format: 'jpeg', quality: '100'});
phantom.exit();
});

You can selectively render contents in the webpage by using another function –

clipRect {object}
This property defines the rectangular area of the web page to be rasterized when page.render is invoked. If no clipping rectangle is set, page.render will process the entire web page.

Working Example –

var webPage = require('webpage');
var page = webPage.create();
page.clipRect = {
  top: 14,
  left: 3,
  width: 400,
  height: 300
};

You might want to render only a single element, for example your content div or a SVG, for this, you can use the element.getBoundingClientRect and PhantomJS page.clipRect together to get the desired output.

Shraddha
Helical IT Solutions