Creat rich text (HTML) emails with inline images from Japser Report

This blog demonstrates how to create and export a HTML file with inline images with Jasper Report for use as an email message in Java Mail.

First, create the report from Jasper Report template in JasperPrint object:

JasperPrint jasperPrint = … // Run report

Now setup HTML exporter:

JRHtmlExporter exporter = new JRHtmlExporter();

Map imageData = new HashMap();

exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, buffer);   exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, “cid:”);      exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesData);
exporter.exportReport();

Of particular interest is the parameters IMAGES_URI and IMAGES_MAP of the HTML exporter. You provide the URI for inlining and an empty hashmap for the exporter to store the images rendered in the  output html string.

Next add inline images to the Java Mail message by processing the imageData map populated by the exporter as follows using the addInLine method of Java Mail class MimeMessageHelper:

MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED);
// attach the html data from htmlOutputData to inline images
for (Iterator<Entry> it = imagesData.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = it.next();
String imageName = (String) entry.getKey();
byte[] imageData = (byte[]) entry.getValue();
// attach imageData using imageName as Content-ID
helper.addInline(imageName, new ByteArrayResource(imageData), “image/jpeg”);
}

2 thoughts on “Creat rich text (HTML) emails with inline images from Japser Report

  1. AndroidResearch March 31, 2012 / 8:06 pm

    From where I could download the JasperPrint library?

    • Raymond Lee March 31, 2012 / 9:27 pm

      JasperPrint is java class that you can find in jasperreports jar file under package net.sf.jasperreports.engine

      Hope above helps

Comments are closed.