Spring Boot Jasper Report Directly to Printer Example

Overview

In this tutorial, we show you how to print Jasper Report directly to printer. In this example, we'll build a Application to choose a printer from select box then print report directly to it.

Spring Boot Jasper Report Directly to Printer

Prerequisites

  • Eclipse Oxygen and Install Spring Tool Suite for Eclipse IDE
  • Spring Boot v2.0.1.RELEASE
  • spring-boot-starter-web
  • spring-boot-starter-jdbc
  • spring-boot-devtools
  • spring-boot-configuration-processor
  • spring-boot-starter-test
  • jstl
  • org.webjars Bootstrap 4
  • tomcat-embed-jasper
  • mysql-connector-java 5.1.46
  • groovy-all 2.0.1
  • itext-pdfa 5.5.0
  • itextpdf 5.5.0
  • jasperreports 6.0.0
  • jackson-core
  • jackson-databind
  • jackson-annotations
  • Java 1.8+
Reference: Spring Boot with JasperReports Example

Create database and tables in MySQL Databases

We'll create a database called jack_rutorial and a tables called user in jack_rutorial database.
CREATE DATABASE `jack_rutorial` /*!40100 DEFAULT CHARACTER SET utf8 */;

DROP TABLE IF EXISTS `jack_rutorial`.`user`;
CREATE TABLE  `jack_rutorial`.`user` (
  `user_id` int(11) NOT NULL auto_increment,
  `user_name` varchar(45) NOT NULL default '',
  `email` varchar(45) NOT NULL default '',
  PRIMARY KEY  (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

Project Directory Structure

The following screenshot shows final structure of the project.
Project Directory Structure

Start to create a web application with Spring Boot

Launch Eclipse IDE. Go to File -> New -> Other... Select Spring Starter Project under Spring Boot category then click Next as shown below


In the next screen, you enter the content as shown below then click Next

Spring Boot with JasperReports Example
In the next step, you choose Spring Boot Version is 2.1.0 and choose the Web, DevTools, MySQL, JDBC, then click Finish.

Spring Boot with JasperReports Example

Create the rpt_users report template file

We create the rpt_users.jrxml file under src/main/resources/ folder. This template contains the columnHeader band and the detail band. Inside a detail band, each element is repeated for every record provided by the data source.
<field name="user_id" class="java.lang.Integer">
 <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="user_name" class="java.lang.String">
 <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="email" class="java.lang.String">
 <fieldDescription><![CDATA[]]></fieldDescription>
</field>
We have three fields in the report. The fields are mapped to the elements of the data source beans.
<textField>
 <reportElement stretchType="RelativeToBandHeight" x="0" y="0" width="120" height="20" uuid="f9cf1e93-86de-42d4-a337-09152af5589f"/>
 <box>
  <pen lineWidth="0.5"/>
  <topPen lineWidth="0.5"/>
  <leftPen lineWidth="0.5"/>
  <bottomPen lineWidth="0.5"/>
  <rightPen lineWidth="0.5"/>
 </box>
 <textElement textAlignment="Center" verticalAlignment="Middle"/>
 <textFieldExpression><![CDATA[$F{user_id}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true" isBlankWhenNull="true">
 <reportElement stretchType="RelativeToBandHeight" x="120" y="0" width="275" height="20" uuid="9978c830-cf98-456a-b030-d96c07de7854"/>
 <box leftPadding="3">
  <pen lineWidth="0.5"/>
  <topPen lineWidth="0.5"/>
  <leftPen lineWidth="0.5"/>
  <bottomPen lineWidth="0.5"/>
  <rightPen lineWidth="0.5"/>
 </box>
 <textElement verticalAlignment="Middle"/>
 <textFieldExpression><![CDATA[$F{user_name}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true" isBlankWhenNull="true">
 <reportElement stretchType="RelativeToBandHeight" x="395" y="0" width="160" height="20" uuid="35a6355d-8307-4414-bf43-8a7788ec81c3"/>
 <box leftPadding="3">
  <pen lineWidth="0.5"/>
  <topPen lineWidth="0.5"/>
  <leftPen lineWidth="0.5"/>
  <bottomPen lineWidth="0.5"/>
  <rightPen lineWidth="0.5"/>
 </box>
 <textElement verticalAlignment="Middle"/>
 <textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
</textField>
rpt_users.jrxml
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="rpt_users" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="809a3f44-f151-4225-8db5-d8f7ef0ad887">
 <property name="ireport.zoom" value="1.0"/>
 <property name="ireport.x" value="0"/>
 <property name="ireport.y" value="0"/>
 <queryString>
  <![CDATA[select * from user]]>
 </queryString>
 <field name="user_id" class="java.lang.Integer">
  <fieldDescription><![CDATA[]]></fieldDescription>
 </field>
 <field name="user_name" class="java.lang.String">
  <fieldDescription><![CDATA[]]></fieldDescription>
 </field>
 <field name="email" class="java.lang.String">
  <fieldDescription><![CDATA[]]></fieldDescription>
 </field>
 <background>
  <band splitType="Stretch"/>
 </background>
 <title>
  <band height="79" splitType="Stretch">
   <staticText>
    <reportElement x="0" y="0" width="555" height="34" uuid="b30be92d-c6fd-4736-ad12-76a9317e274b"/>
    <textElement textAlignment="Center" verticalAlignment="Middle">
     <font size="16" isBold="true"/>
    </textElement>
    <text><![CDATA[USERS LIST]]></text>
   </staticText>
  </band>
 </title>
 <pageHeader>
  <band splitType="Stretch"/>
 </pageHeader>
 <columnHeader>
  <band height="20" splitType="Stretch">
   <staticText>
    <reportElement x="0" y="0" width="120" height="20" uuid="d9efce97-b36d-4b32-a494-46857cdee4e4"/>
    <box>
     <pen lineWidth="0.5"/>
     <topPen lineWidth="0.5"/>
     <leftPen lineWidth="0.5"/>
     <bottomPen lineWidth="0.5"/>
     <rightPen lineWidth="0.5"/>
    </box>
    <textElement textAlignment="Center" verticalAlignment="Middle">
     <font isBold="true"/>
    </textElement>
    <text><![CDATA[#ID]]></text>
   </staticText>
   <staticText>
    <reportElement x="120" y="0" width="275" height="20" uuid="bb85b6d2-f2b1-4cb8-9f17-53376a9139c1"/>
    <box>
     <pen lineWidth="0.5"/>
     <topPen lineWidth="0.5"/>
     <leftPen lineWidth="0.5"/>
     <bottomPen lineWidth="0.5"/>
     <rightPen lineWidth="0.5"/>
    </box>
    <textElement textAlignment="Center" verticalAlignment="Middle">
     <font isBold="true"/>
    </textElement>
    <text><![CDATA[Username]]></text>
   </staticText>
   <staticText>
    <reportElement x="395" y="0" width="160" height="20" uuid="e7915756-0ff0-49c9-87c0-2bfbd29ad7e4"/>
    <box>
     <pen lineWidth="0.5"/>
     <topPen lineWidth="0.5"/>
     <leftPen lineWidth="0.5"/>
     <bottomPen lineWidth="0.5"/>
     <rightPen lineWidth="0.5"/>
    </box>
    <textElement textAlignment="Center" verticalAlignment="Middle">
     <font isBold="true"/>
    </textElement>
    <text><![CDATA[Email]]></text>
   </staticText>
  </band>
 </columnHeader>
 <detail>
  <band height="20" splitType="Stretch">
   <textField>
    <reportElement stretchType="RelativeToBandHeight" x="0" y="0" width="120" height="20" uuid="f9cf1e93-86de-42d4-a337-09152af5589f"/>
    <box>
     <pen lineWidth="0.5"/>
     <topPen lineWidth="0.5"/>
     <leftPen lineWidth="0.5"/>
     <bottomPen lineWidth="0.5"/>
     <rightPen lineWidth="0.5"/>
    </box>
    <textElement textAlignment="Center" verticalAlignment="Middle"/>
    <textFieldExpression><![CDATA[$F{user_id}]]></textFieldExpression>
   </textField>
   <textField isStretchWithOverflow="true" isBlankWhenNull="true">
    <reportElement stretchType="RelativeToBandHeight" x="120" y="0" width="275" height="20" uuid="9978c830-cf98-456a-b030-d96c07de7854"/>
    <box leftPadding="3">
     <pen lineWidth="0.5"/>
     <topPen lineWidth="0.5"/>
     <leftPen lineWidth="0.5"/>
     <bottomPen lineWidth="0.5"/>
     <rightPen lineWidth="0.5"/>
    </box>
    <textElement verticalAlignment="Middle"/>
    <textFieldExpression><![CDATA[$F{user_name}]]></textFieldExpression>
   </textField>
   <textField isStretchWithOverflow="true" isBlankWhenNull="true">
    <reportElement stretchType="RelativeToBandHeight" x="395" y="0" width="160" height="20" uuid="35a6355d-8307-4414-bf43-8a7788ec81c3"/>
    <box leftPadding="3">
     <pen lineWidth="0.5"/>
     <topPen lineWidth="0.5"/>
     <leftPen lineWidth="0.5"/>
     <bottomPen lineWidth="0.5"/>
     <rightPen lineWidth="0.5"/>
    </box>
    <textElement verticalAlignment="Middle"/>
    <textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
   </textField>
  </band>
 </detail>
 <columnFooter>
  <band splitType="Stretch"/>
 </columnFooter>
 <pageFooter>
  <band splitType="Stretch"/>
 </pageFooter>
 <summary>
  <band splitType="Stretch"/>
 </summary>
</jasperReport>

Project Dependencies

We will add the following dependencies to the pom.xml file. jstl
<dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>jstl</artifactId>
</dependency>
Bootstrap 4.0.0
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>4.0.0</version>
  </dependency>
apache.tomcat.embed
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
mysql-connector-java
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.46</version>
  </dependency>
spring-boot-configuration-processor
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-configuration-processor</artifactId>
   <optional>true</optional>
  </dependency>
spring-boot-starter-jdbc
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
jasperreports
<dependency>
 <groupId>org.codehaus.groovy</groupId>
 <artifactId>groovy-all</artifactId>
 <version>2.0.1</version>
</dependency>
<dependency>
 <groupId>com.itextpdf</groupId>
 <artifactId>itext-pdfa</artifactId>
 <version>5.5.0</version>
</dependency>
<dependency>
 <groupId>com.itextpdf</groupId>
 <artifactId>itextpdf</artifactId>
 <version>5.5.0</version>
</dependency>
<dependency>
 <groupId>net.sf.jasperreports</groupId>
 <artifactId>jasperreports</artifactId>
 <version>6.0.0</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-annotations</artifactId>
</dependency>
The updated pom.xml file will have the following code
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.jackrutorial</groupId>
 <artifactId>SpringBootJasperReports</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootJasperReports</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.0.BUILD-SNAPSHOT</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
  </dependency>
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>4.0.0</version>
  </dependency>
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.46</version>
  </dependency>
  <dependency>
   <groupId>org.codehaus.groovy</groupId>
   <artifactId>groovy-all</artifactId>
   <version>2.0.1</version>
  </dependency>
  <dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext-pdfa</artifactId>
   <version>5.5.0</version>
  </dependency>
  <dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.5.0</version>
  </dependency>
  <dependency>
   <groupId>net.sf.jasperreports</groupId>
   <artifactId>jasperreports</artifactId>
   <version>6.0.0</version>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-annotations</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-configuration-processor</artifactId>
   <optional>true</optional>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

 <repositories>
  <repository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </repository>
 </repositories>

 <pluginRepositories>
  <pluginRepository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </pluginRepository>
  <pluginRepository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </pluginRepository>
 </pluginRepositories>


</project>

application.properties

In the sources folder, we will look for this project's a resource file under src/main/resources/application.properties. Open application.properties file and add the following properties.
#config db
spring.datasource.jdbcUrl=jdbc:mysql://localhost:3306/jack_rutorial
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

#jsp
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

server.port=8080
server.servlet.context-path=/jackrutorial

WebConfig

We configure the DataSource in the WebConfig class. The main Spring Boot configuration file is called application.properties. Spring Boot automatically configures HikariCP connection pool. Create a WebConfig class under com.jackrutorial.config package with the following code.
package com.jackrutorial.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class WebConfig {
 
 @Bean(name = "db")
 @ConfigurationProperties(prefix = "spring.datasource")
 public DataSource dataSource() {
  return DataSourceBuilder.create().build();
 }

 @Bean(name = "jdbcTemplate")
 public JdbcTemplate jdbcTemplate(@Qualifier("db") DataSource ds) {
  return new JdbcTemplate(ds);
 }
}

Model

Printer.java
package com.jackrutorial.model;

public class Printer {
 private String printerName;

 public String getPrinterName() {
  return printerName;
 }

 public void setPrinterName(String printerName) {
  this.printerName = printerName;
 }
}

PrinterForm.java
package com.jackrutorial.model;

public class PrinterForm {
 
 private String printerName;

 public String getPrinterName() {
  return printerName;
 }

 public void setPrinterName(String printerName) {
  this.printerName = printerName;
 }
}

DAO Layer

We'll compile the rpt_users.jrxml file, then fill it with data using the JasperCompilerManager class.
String path = resourceLoader.getResource("classpath:rpt_users.jrxml").getURI().getPath();
JasperReport jasperReport = JasperCompileManager.compileReport(path);
JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, conn);
UserDaoImpl.java
package com.jackrutorial.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.PrinterName;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimplePrintServiceExporterConfiguration;

@Transactional
@Repository
public class UserDaoImpl {

 @Autowired
 @Qualifier("jdbcTemplate")
 private JdbcTemplate jdbcTemplate;

 @Autowired
 private ResourceLoader resourceLoader;

 public JasperPrint exportPdfFile() throws SQLException, JRException, IOException {
  Connection conn = jdbcTemplate.getDataSource().getConnection();

  String path = resourceLoader.getResource("classpath:rpt_users.jrxml").getURI().getPath();

  JasperReport jasperReport = JasperCompileManager.compileReport(path);

  // Parameters for report
  Map<String, Object> parameters = new HashMap<String, Object>();

  JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, conn);

  return print;
 }

 public void printReport(JasperPrint jasperPrint, String selectedPrinter) throws JRException {
  PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
  printRequestAttributeSet.add(MediaSizeName.ISO_A4);
  if (jasperPrint.getOrientationValue() == net.sf.jasperreports.engine.type.OrientationEnum.LANDSCAPE) {
   printRequestAttributeSet.add(OrientationRequested.LANDSCAPE);
  } else {
   printRequestAttributeSet.add(OrientationRequested.PORTRAIT);
  }
  PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
  printServiceAttributeSet.add(new PrinterName(selectedPrinter, null));

  JRPrintServiceExporter exporter = new JRPrintServiceExporter();
  SimplePrintServiceExporterConfiguration configuration = new SimplePrintServiceExporterConfiguration();
  configuration.setPrintRequestAttributeSet(printRequestAttributeSet);
  configuration.setPrintServiceAttributeSet(printServiceAttributeSet);
  configuration.setDisplayPageDialog(false);
  configuration.setDisplayPrintDialog(false);

  exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
  exporter.setConfiguration(configuration);

  PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
  PrintService selectedService = null;
  if (services.length != 0 || services != null) {
   for (PrintService service : services) {
    String existingPrinter = service.getName();
    if (existingPrinter.equals(selectedPrinter)) {
     selectedService = service;
     break;
    }
   }
  }

  if (selectedService != null) {
   exporter.exportReport();
  } else {
   System.out.println("You did not set the printer!");
  }
 }
}

Service Layer

Create a UserService class under com.jackrutorial.service package and write the following code in it.
package com.jackrutorial.service;

import java.io.IOException;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jackrutorial.dao.UserDaoImpl;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;

@Service
public class UserService {

 @Autowired
 private UserDaoImpl userDao;

 public JasperPrint exportPdfFile() throws SQLException, JRException, IOException {
  return userDao.exportPdfFile();
 }
 
 public void printReport(JasperPrint jasperPrint, String selectedPrinter) throws JRException {
  userDao.printReport(jasperPrint, selectedPrinter);
 }
}

UserController Controller

Create a UserController class under com.jackrutorial.controller package and write the following code in it.
package com.jackrutorial.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.jackrutorial.model.Printer;
import com.jackrutorial.model.PrinterForm;
import com.jackrutorial.service.UserService;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;

@Controller
@RequestMapping("/")
public class UserController {

 @Autowired
 private UserService userService;

 @RequestMapping(value = { "/", "" }, method = RequestMethod.GET)
 public ModelAndView home() {
  ModelAndView model = new ModelAndView();
  PrinterForm printerForm = new PrinterForm();

  PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
  List<Printer> printers = new ArrayList<Printer>();
  for (PrintService service : services) {
   Printer printer = new Printer();
   printer.setPrinterName(service.getName());

   printers.add(printer);
  }

  model.addObject("listPrinters", printers);
  model.addObject("printerForm", printerForm);

  model.setViewName("home");
  return model;
 }

 @RequestMapping(value = "/printDirect", method = RequestMethod.POST)
 public void printDirect(@ModelAttribute("printerForm") PrinterForm printerForm, ModelAndView model)
   throws IOException, JRException, SQLException {
  JasperPrint jasperPrint = null;
  jasperPrint = userService.exportPdfFile();

  userService.printReport(jasperPrint, printerForm.getPrinterName());
 }
}

View Layer

Create jsp folder under src\main\webapp\WEB-INF\ folder.
Create home.jsp file under src\main\webapp\WEB-INF\jsp\ folder and write the following code in it. home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Users</title>
<link href="webjars/bootstrap/4.0.0/css/bootstrap.min.css"
 rel="stylesheet" />
<script src="webjars/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="webjars/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
 <div class="container">
  <div class="card-deck mt-2">
   <div class="card">
    <div class="card-header">
     <span class="font-weight-bold">Users</span>
    </div>
    <div class="card-body">
     <spring:url value="/printDirect" var="actionURL" />
     <form:form modelAttribute="printerForm" method="post" action="${actionURL }">
      <form:select path="printerName" cssClass="form-control">
       <form:option value="0" label="Select printer" />
       <form:options items="${listPrinters}" itemValue="printerName" itemLabel="printerName" />
      </form:select>

      <button type="submit" class="btn btn-info mt-2">Print</button>
     </form:form>
    </div>
   </div>
  </div>
 </div>
</body>
</html>

Run Spring Boot Application

Right click to the Project and follow the below steps:
select Run As -> Maven clean.
select Run As -> Maven install.
select Run As -> Spring Boot App.
View console output in eclipse, you will see following output:
 INFO 1908 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
 INFO 1908 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
 INFO 1908 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.10
 INFO 1908 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/test]   : Initializing Spring embedded WebApplicationContext
 INFO 1908 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1359 ms
 INFO 1908 --- [  restartedMain] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
 INFO 1908 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
 INFO 1908 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
 INFO 1908 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'formContentFilter' to: [/*]
 INFO 1908 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
 INFO 1908 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService  'applicationTaskExecutor'
DEBUG 1908 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/**/favicon.ico] in 'faviconHandlerMapping'
DEBUG 1908 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 @ModelAttribute, 0 @InitBinder, 1 RequestBodyAdvice, 1, ResponseBodyAdvice
DEBUG 1908 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : 4 mappings in 'requestMappingHandlerMapping'
DEBUG 1908 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
DEBUG 1908 --- [  restartedMain] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 @ExceptionHandler, 1 ResponseBodyAdvice
 INFO 1908 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
 INFO 1908 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path '/jackrutorial'
 INFO 1908 --- [  restartedMain] c.j.SpringBootJasperReportsApplication   : Started SpringBootJasperReportsApplication in 2.773 seconds (JVM running for 3.592)

Demo Application

Type the following URLs in browser's address bar to open user page. Then choose the printer. Finally click Print button.
http://localhost:8080/jackrutorial/
demo

Previous Post
Next Post

post written by: