I am a programmer but I hate grammar. Here you will find what I did, doing , will do ... Scattered pieces of knowledge that I have deleted from my mind to the trash bin through out my boring daily coding life. I will also report some of my failures in life so dear to me not success, because I have always learnt much only when I fail.
Showing posts with label JASPER REPORT. Show all posts
Showing posts with label JASPER REPORT. Show all posts
Thursday, May 13, 2021
18 - Generate PDF with Jasperreport and Spring Boot SOLVED
In this tutorial, I show you how to generate a PDF with Jasperreport and Spring Boot .
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/YOURDATABASE?autoReconnect=true spring.datasource.username=YOURUSERNAME spring.datasource.password=YOURPASSWORD spring.jpa.generate-ddl=true
net.sf.jasperreports jasperreports 6.16.0 org.springframework spring-context-support
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServiceJpasql001Application {
public static void main(String[] args) {
SpringApplication.run(ServiceJpasql001Application.class, args);
}
}
package com.example.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student{
@Id
@Column(name="stid")
private int stid;
@Column(name="name")
private String name;
@Column(name="programme")
private String Programme;
public int getStid() {
return stid;
}
public void setStid(int stid) {
this.stid = stid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProgramme() {
return Programme;
}
public void setProgramme(String programme) {
Programme = programme;
}
public Student(int stid, String name, String programme) {
super();
this.stid = stid;
this.name = name;
Programme = programme;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
}
package com.example.demo.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.model.Student; public interface StudentRepository extends JpaRepository{ List findByName(String name); }
package com.example.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public Student addStudent(Student student) {
return studentRepository.save(student);
}
public void deleteStudent(Student student) {
studentRepository.delete(student);
}
public List getStudent() {
return studentRepository.findAll();
}
public List getStudentByName(String name) {
return studentRepository.findByName(name);
}
}
package com.example.demo.controller;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
@RestController
public class StudentController {
@Autowired
StudentService studentService;
@RequestMapping("/all")
public List getStudent() {
return studentService.getStudent();
}
@RequestMapping("/studentByName/{name}")
public List getStudentByName(@PathVariable String name) {
return studentService.getStudentByName(name);
}
@RequestMapping("/save")
public Student saveStudent(@RequestBody Student student) {
return studentService.addStudent(student);
}
@RequestMapping("/delete")
public void deleteStudent(@RequestBody Student student) {
studentService.deleteStudent(student);
}
@RequestMapping("/pdf")
public void getReportsinPDF(HttpServletResponse response) throws JRException, IOException {
//Compiled report
InputStream jasperStream = (InputStream) this.getClass().getResourceAsStream("/StudentList.jasper");
//Adding attribute names
Map params = new HashMap<>();
params.put("stid","stid");
params.put("name","name");
params.put("programme","programme");
// Fetching the student from the data database.
final JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(studentService.getStudent());
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, source);
response.setContentType("application/x-pdf");
response.setHeader("Content-disposition", "inline; filename=StudentList.pdf");
final ServletOutputStream outStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
}
}
Friday, May 29, 2020
Dev Tips#43 Connect MYSQL to a Jasper report in Java and JDBC
In this tutorial, I show you how to retrieve data from MySQL to a Jasper Report in Java. JDBC is used to get an instance of the connection and passed to the jasper report engine...
Settings.xml:
POM.xml:
Main Java Class:
Settings.xml:
mirror1 central mirror1 https://repo.maven.apache.org/maven2/
net.sf.jasperreports jasperreports 6.8.0 jar compile commons-collections commons-collections commons-beanutils commons-beanutils commons-digester commons-digester commons-logging commons-logging commons-digester commons-digester 2.1 compile false mysql mysql-connector-java 5.1.6
package com.mycompany.mavenprojectdemov1;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Hello world!
*
*/
public class App
{
public static Connection getDbaseConnection(String HOST_NAME, String DBASE_NAME,
String USER_NAME, String USR_PASS) throws SQLException,
ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
//String connectionURL = "jdbc:mysql://" + hostName + ":3306/" + dbName;
String CNTION_URL = "jdbc:mysql://" + HOST_NAME + "/" + DBASE_NAME;
Connection conn = DriverManager.getConnection(CNTION_URL, USER_NAME,USR_PASS);
return conn;
}
public static void main( String[] args )
{
//Database credential
String hostName = "localhost";
String dbName = "springboot";
String userName = "springboot";
String password = "springboot";
//Jasper file location
String fileNameJrxml = "E:/Jasper/jasperv1.jrxml";
String fileNamePdf = "E:/Jasper/jasperv1.pdf";
try {
//Getting a connection instance
Connection connInstance = getDbaseConnection(hostName,dbName,userName,password);
System.out.println("Loading the .JRMXML file ....");
JasperDesign jasperDesign = JRXmlLoader.load(fileNameJrxml);
System.out.println("Compiling the .JRMXML file to .JASPER file....");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
System.out.println("filling parameters to .JASPER file....");
JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport(jasperReport, null,connInstance);
System.out.println("exporting the JASPER file to PDF file....");
JasperExportManager.exportReportToPdfFile(jprint, fileNamePdf);
System.out.println("Successfully completed the export");
} catch (Exception e) {
System.out.print("Exception:" + e);
}
}
}
Wednesday, May 27, 2020
Dev Tips#42 Passing parameters to a Jasper Report in Java
In this tutorial, I show you how to pass parameteres to a Jasper report in JAVA running in Netbeans IDE 8.
Settings.xml:
POM.xml:
Main Java Class:
Settings.xml:
mirror1 central mirror1 https://repo.maven.apache.org/maven2/
net.sf.jasperreports jasperreports 6.8.0 jar compile commons-collections commons-collections commons-beanutils commons-beanutils commons-digester commons-digester commons-logging commons-logging commons-digester commons-digester 2.1 compile false
package com.mycompany.mavenprojectdemov1;
import java.util.HashMap;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
String fileNameJrxml = "E:/Jasper/Blank_A4_Paramv2.jrxml";
String fileNamePdf = "E:/Jasper/Blank_A4_Paramv2.pdf";
try {
System.out.println("Loading the .JRMXML file ....");
JasperDesign jasperDesign = JRXmlLoader.load(fileNameJrxml);
System.out.println("Compiling the .JRMXML file to .JASPER file....");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
String first_language = "Java";
String second_language = "Structured text";
HashMap hm = new HashMap();
hm.put("Param_First_Language", first_language);
hm.put("Param_Second_Language", second_language);
System.out.println("filling parameters to .JASPER file....");
JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport(jasperReport, hm, new JREmptyDataSource());
System.out.println("exporting the JASPER file to PDF file....");
JasperExportManager.exportReportToPdfFile(jprint, fileNamePdf);
System.out.println("Successfully completed the export");
} catch (Exception e) {
System.out.print("Exception:" + e);
}
}
}
Friday, May 22, 2020
Dev Tips#39 Jasper report in Java 8 and Netbeans 8
In this video I show you how to create a jasper report in Java 8 and Netbeans 8 with dependencies handled by maven to export a PDF. How to export a PDF in java.
Settings.xml:
Dependencies:
Java code:
Settings.xml:
mirror1 central mirror1 https://repo.maven.apache.org/maven2
Dependencies:
net.sf.jasperreports jasperreports 6.8.0 jar compile commons-collections commons-collections commons-beanutils commons-beanutils commons-digester commons-digester commons-logging commons-logging commons-digester commons-digester 2.1 compile false net.sf.jasperreports jasperreports-fonts 6.8.0
Java code:
package com.mycompany.mavenprojectdemov1;
import java.util.HashMap;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
String fileNameJrxml = "E:/Jasper/HelloPDF.jrxml";
String fileNamePdf = "E:/Jasper/HelloPDFv2.pdf";
try {
System.out.println("Loading the .JRMXML file ....");
JasperDesign jasperDesign = JRXmlLoader.load(fileNameJrxml);
System.out.println("Compiling the .JRMXML file to .JASPER file....");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
HashMap hm = new HashMap();
System.out.println("filling parameters to .JASPER file....");
JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport(jasperReport, hm, new JREmptyDataSource());
System.out.println("exporting the JASPER file to PDF file....");
JasperExportManager.exportReportToPdfFile(jprint, fileNamePdf);
System.out.println("Successfully completed the export");
} catch (Exception e) {
System.out.print("Exception:" + e);
}
}
}
Sunday, May 17, 2020
Dev Tips#37 Create your first Jasper report in Java and VS code maven
In this tutorial, I show you how to create a simple jasper report with a static text in TIBCO Jasper Report Studio. Then run the jrmxl file in a Maven Java Project in visual studio code to get a pdf.
Main Class
package com.abc;
import java.util.HashMap;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
String fileNameJrxml = "E:/Jasper/HelloPDF.jrxml";
String fileNamePdf = "E:/Jasper/HelloPDF.pdf";
try {
System.out.println("Loading the .JRMXML file ....");
JasperDesign jasperDesign = JRXmlLoader.load(fileNameJrxml);
System.out.println("Compiling the .JRMXML file to .JASPER file....");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
HashMap hm = new HashMap();
System.out.println("filling parameters to .JASPER file....");
JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport(jasperReport, hm, new JREmptyDataSource());
System.out.println("exporting the JASPER file to PDF file....");
JasperExportManager.exportReportToPdfFile(jprint, fileNamePdf);
System.out.println("Successfully completed the export");
} catch (Exception e) {
System.out.print("Exception:" + e);
}
}
}
junit junit 4.11 test net.sf.jasperreports jasperreports 6.8.0 commons-beanutils commons-beanutils 1.9.3 compile false commons-digester commons-digester 2.1 compile false commons-logging commons-logging 1.1.1 compile false org.apache.commons commons-collections4 4.2 compile false com.lowagie itext 2.1.7.js6 compile false org.bouncycastle bcmail-jdk15on org.bouncycastle bcpkix-jdk15on org.apache.poi poi 4.0.1 compile true org.apache.poi poi-ooxml 4.0.1 compile true org.eclipse.jdt.core.compiler ecj 4.4.2 compile false org.codehaus.groovy groovy-all 2.4.5 compile true org.apache.logging.log4j log4j-core 2.8.2 test org.apache.logging.log4j log4j-jcl 2.8.2 test net.sf.jasperreports jasperreports-fonts 6.8.0 test org.apache.lucene lucene-core 7.3.0 compile true org.apache.lucene lucene-analyzers-common 7.3.0 compile true org.apache.lucene lucene-queryparser 7.3.0 compile true org.olap4j olap4j 0.9.7.309-JS-3 compile true org.apache.commons commons-pool2 2.4.2 compile true commons-codec commons-codec 1.5 compile true net.sf.jasperreports jasperreports-metadata 6.8.0 compile true
Saturday, May 16, 2020
Thursday, January 30, 2014
Location of Jars in ireport
Many tend to be confused about the location of jars libraries in jasper ireport. In fact for the case of Microsoft Windows, after the installation yours jars will reside inside the following location:
C:\Program Files\Jaspersoft\iReport-XXX\ireport\modules\ext
C:\Program Files\Jaspersoft\iReport-XXX\ireport\modules\ext
Friday, January 10, 2014
Getting a org.springframework.beans.factory.BeanCreationException with my first Maven, Spring Project
If you are getting this error message, you maybe missing a crucial jar file in your project. Just download the spring- jar include it to your project, build it and move forward.
Caused by: java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser
Facing this problem can be very painful, I have been and lost a couple of my precious hours trying to dig it out. I won't talk much because it is not my field of predilection. I am pragmatic and let us go straight to the point.
Solution:
You have download two jars and include in your project.
Hopefully you have include them, build your project and regain your smiling face. Happy coding day though !!!
Solution:
You have download two jars and include in your project.
Hopefully you have include them, build your project and regain your smiling face. Happy coding day though !!!
Wednesday, January 8, 2014
Conditional expression in ireport
Expression condition for the first in ireport for many usually seems awkward given that we have to leave behind our programming legacy of IF ELSE and do it another way.
And here come the issue, suppose we have to define the following condition :
And here come the issue, suppose we have to define the following condition :
IF boolean condition THEN
execute true code snippet
ELSE
execute false codesnippet
END IF
Ireport we will otherwise do it as follow:
( boolean condition ? execute true codesnippet: execute false codesnippet)
e.g:
if ( conVar > 0 )
binVar= 1
else binVar= -1
Then becomes:
(conVar > 0 ? binVar= 1: binVar=-1)
It the similar way we can express some complicated and nested conditions.
If you still face any problems feel free to drop a comment.
Thursday, November 7, 2013
Irepot: Row transferred to next page get Calculated in the current page
This is a common problem with ireport but no formal ansvwer yet but some workarounds do exist and I will show you one.
Here is the problem: I have a report with a numeric column(suppose its name is quantity) per row which I want to show summation of that column for all records in every page, the desired value will calculate from summation of quantity columns in current page and all previous pages(suppose its name is qSum). If i allow splitting for Detail band rows, there is no problem, but when I prevent splitting, the quantity column value of splitted row will add to calculated summation (qSum) of current page, but the row itself will shown in the next page!
In order words how can I force the summation to be only for the row appearing on that page. (excluding the transferred row)
My column summation is the column footer.
Workaround: the key thing to do here is to create a dummy group for each row based on their primary key.
How ?
Whenever a row spread over two consecutives pages ireport becomes confused. Instead of using split type= prevent as option in the detail band , set it to split type= Stretch. Then create a dummy group (by primary key of the row) with group header and footer enabled that will act as a container for each row . Dummy group option are: reprint header=true, Min Height to start new= value of detail band height, Footer Position= normal, Keep together= true.
Now if each is processed as group and will be forwarded to next page it cannot fit a the current one. This scenario is common with financial accounting report when you have credit , debit and has to calculate a running balance with carry forward and bring forward totals.
I will try on my next post to illustrate this solution with some screenshots, but for now I hope you have got some ideas at least. Feel free to comment or knock me.
Here is the problem: I have a report with a numeric column(suppose its name is quantity) per row which I want to show summation of that column for all records in every page, the desired value will calculate from summation of quantity columns in current page and all previous pages(suppose its name is qSum). If i allow splitting for Detail band rows, there is no problem, but when I prevent splitting, the quantity column value of splitted row will add to calculated summation (qSum) of current page, but the row itself will shown in the next page!
In order words how can I force the summation to be only for the row appearing on that page. (excluding the transferred row)
My column summation is the column footer.
Workaround: the key thing to do here is to create a dummy group for each row based on their primary key.
How ?
Whenever a row spread over two consecutives pages ireport becomes confused. Instead of using split type= prevent as option in the detail band , set it to split type= Stretch. Then create a dummy group (by primary key of the row) with group header and footer enabled that will act as a container for each row . Dummy group option are: reprint header=true, Min Height to start new= value of detail band height, Footer Position= normal, Keep together= true.
Now if each is processed as group and will be forwarded to next page it cannot fit a the current one. This scenario is common with financial accounting report when you have credit , debit and has to calculate a running balance with carry forward and bring forward totals.
I will try on my next post to illustrate this solution with some screenshots, but for now I hope you have got some ideas at least. Feel free to comment or knock me.
Thursday, September 19, 2013
Control line spacing in ireport
Is it possible to control the line spacing in ireport ? Yes
I have recently come through this problem during one of project as the requirement was to have something line the following
but what I had by defaut in ireport is
The question is How to reach my target of reducing line spacing ?
For the remaining option s, you can easily test them yourself.
Note:
I assume you can insert a newline in ireport , if not here is how you can do that using \n.
As in the preceding example , we want to insert four (04) fields in a single textfield and each appearing in a newline.
$F{empName}+"\n\n"+$F{comment1}+"\n"+$F{comment2}+"\n"+$F{comment3}
Hope you find it useful.
I have recently come through this problem during one of project as the requirement was to have something line the following
but what I had by defaut in ireport is
The question is How to reach my target of reducing line spacing ?
This is easily achievable in ireport (version 5.00 ) . In fact ireport offer various properties for controlling line
spacing . If you click on a textfield and go to properites you get the following options
line spacing has many options available :
- single (default)
- 1.5
- Double
- At least
- Fixed
- Proportional
For the remaining option s, you can easily test them yourself.
Note:
I assume you can insert a newline in ireport , if not here is how you can do that using \n.
As in the preceding example , we want to insert four (04) fields in a single textfield and each appearing in a newline.
$F{empName}+"\n\n"+$F{comment1}+"\n"+$F{comment2}+"\n"+$F{comment3}
Hope you find it useful.
Wednesday, December 26, 2012
Leading zeroes formatting ireport
Hi, welcome to my blog. Are you having problem formatting leading zeroes in jasper ireport
for example:
1--->001
10-->010
Steps:
1.Right clikc the textfield -->field pattern --->put the number of zero corresponding to the number of digit you want.
2. For the above example , I have three digits so I should put 000
3. Rock it !!!!!!!!!
for example:
1--->001
10-->010
Steps:
1.Right clikc the textfield -->field pattern --->put the number of zero corresponding to the number of digit you want.
2. For the above example , I have three digits so I should put 000
3. Rock it !!!!!!!!!
Monday, September 17, 2012
Jasper report: column footer not appearing directly below detail band
Maybe you wanted the column footer to appear directly below the detail band without success.
Certainly this tips may help you.
1.Go to designer view ---> Report inspector -->right click report name --->properties-->Check "Float column Footer".
2.Go back to design view --->set the height of summary band to zero or just delete it.
3. Rock your world.
Certainly this tips may help you.
1.Go to designer view ---> Report inspector -->right click report name --->properties-->Check "Float column Footer".
2.Go back to design view --->set the height of summary band to zero or just delete it.
3. Rock your world.
Thursday, July 19, 2012
Ireport : forward a broken row to the new page
Suppose a row height is so long that it is spread on two pages.
Using this option will do the job
<columnHeader>
<band height="20" splitType="Prevent">
<staticText>
</staticText>
</band>
</columnHeader>
<detail>
<band height="18" splitType="Prevent">
<textField isStretchWithOverflow="true" isBlankWhenNull="false">
.....
</textField>
</detail>
Using this option will do the job
<columnHeader>
<band height="20" splitType="Prevent">
<staticText>
</staticText>
</band>
</columnHeader>
<detail>
<band height="18" splitType="Prevent">
<textField isStretchWithOverflow="true" isBlankWhenNull="false">
.....
</textField>
</detail>
Subscribe to:
Posts (Atom)