I write solutions to the problems I can't find much about elsewhere on the Web, also some code/script snippets that are absolutely awesome and make my life easier. Will be glad if someone finds these posts interesting and helpful!

Monday, May 3, 2010

Silently print Jasper reports

I’ve recently come across an issue with the project I’m working on regarding what the title says. The thing is that the users didn’t want to see any kind of dialogs prompting to print the report. Well, it was pretty easy after all and the class I wrote follows.
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
public class SilentPrint {
public void printReport(Vector jasperPrintList, String selectedPrinter) {
try {
//first make sure that requested printService exists
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
PrintService printService = null;
for(PrintService ps : printServices) {
if(ps.getName().equals(selectedPrinter)) {
printService = ps;
break;
}
}
if(printService != null) {
JRExporter jrExporter = new JRPrintServiceExporter();
jrExporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,
jasperPrintList); //tell jasper what reports to export
jrExporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE,
printService); //tell jasper to export the report to selected printService
jrExporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET,
printService.getAttributes());
jrExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG,
Boolean.FALSE); //who doesn't like self-explanatory attributes!
jrExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG,
Boolean.FALSE);
jrExporter.exportReport();
}
else {
System.err.println("Printer " + selectedPrinter + " not found");
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}

And here’s a usage sample:
public void createReport(String[] jasperFileUrls, Map parameters, JRDataSource ds, String type,
String selectedPrinter) {
Vector jasperPrintList = new Vector(0);
for(String s : jasperFileUrls) {
try {
jasperPrintList.add(JasperFillManager.fillReport((JasperReport)JRLoader.loadObject(s), parameters, ds));
System.out.println("Added report: " + s + " to the printlist");
}
catch(JRException jre) {
System.err.println("Failed to add the report '" + s + "' due to exception: " +
jre.getMessage());
}
}
try {
printReport(jasperPrintList, selectedPrinter);
}
catch(Exception e) {
e.printStackTrace();
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Hope this helps anyone.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete