RSS

Category Archives: E-Books

Print iReport in Java Code

Choosing a printer programmatically in Jasper Reports


JasperPrint print = JasperFillManager.<strong>fillReport</strong>(  this.class.<strong>getResource</strong>("<em>/classpath/yourReport.jasper</em>").<strong>getPath</strong>(),  new <strong>HashMap</strong>(), new <strong>yourReportDataSource</strong>());
 PrinterJob job = PrinterJob.getPrinterJob();
 /* Create an array of PrintServices */
 PrintService[] services = PrintServiceLookup.<strong>lookupPrintServices</strong>(null,  null);
 int selectedService = 0;
 /* Scan found services to see if anyone suits our needs */
 for(int i = 0; i < services.length;i++){
 if(services[i].<strong>getName</strong>().<strong>toUpperCase</strong>().<strong>contains</strong>("<em>Your  printer's name</em>")){
 /*If the service is named as what we are querying we select it */
 selectedService = i;
 }
 }
 job.<strong>setPrintService</strong>(services[selectedService]);
 PrintRequestAttributeSet printRequestAttributeSet = new <strong>HashPrintRequestAttributeSet</strong>();
 MediaSizeName mediaSizeName = MediaSize.<strong>findMedia</strong>(4,4,MediaPrintableArea.INCH);
 printRequestAttributeSet.<strong>add</strong>(mediaSizeName);
 printRequestAttributeSet.<strong>add</strong>(new Copies(1));
 JRPrintServiceExporter exporter;
 exporter = new <strong>JRPrintServiceExporter</strong>();
 exporter.<strong>setParameter</strong>(JRExporterParameter.JASPER_PRINT,  print);
 /* We set the selected service and pass it as a paramenter */
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.PRINT_SERVICE,  services[selectedService]);
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET,  services[selectedService].getAttributes());
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET,  printRequestAttributeSet);
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG,  Boolean.FALSE);
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG,  Boolean.TRUE);
 exporter.exportReport();

In the above code you can see how to accomplish our purpose. The first part of all is generating our JasperPrint, this is common to all methods of report printing. Then comes the important part. First we look for the available printServices in the computer. Second, we scan the found services to see if there is anyone that suits our needs. Finally we set the selected print service in the exporter.

You will also find methods to choose the paper output and the number of copies to print.

Reference by:  http://blog.marcnuri.com/blog/default/2007/03/22/Choosing-a-printer-programmatically-in-Jasper-Reports

 
3 Comments

Posted by on April 6, 2010 in Java