Generate PDF, HTML, and XML Reports in Spring Boot 3 with JasperReports
This tutorial walks through setting up Spring Boot 3.4.2 with JasperReports to design, configure, and export professional PDF, HTML, and XML reports, covering environment preparation, font configuration, code implementation, and testing endpoints.
Spring Boot applications can integrate JasperReports to generate PDF, HTML, and XML reports with a single click. By adding the JasperReports dependencies, designing .jrxml templates in Jaspersoft Studio, and configuring fonts for Chinese characters, developers can produce professional reports.
Environment
SpringBoot 3.4.2
1. Introduction
Integrate JasperReports in a Spring Boot app to generate reports in PDF, HTML, and XML formats. Use the JasperReports template engine for rapid report creation.
Design .jrxml templates with Jaspersoft Studio, defining fields, layout, and grouping.
Load and compile templates in Spring Boot, fill them with data via JasperFillManager, and export using JasperExportManager.
2. Practical Example
2.1 Prepare Environment
First, add the required Maven dependencies:
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-pdf</artifactId>
<version>7.0.3</version>
</dependency>Configure fonts to support Chinese characters (e.g., "黑体") by copying the font file to the project and defining fonts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<fontFamilies>
<fontFamily name="黑体">
<normal>fonts/simhei.ttf</normal>
<bold>fonts/simhei.ttf</bold>
<italic>fonts/simhei.ttf</italic>
<boldItalic>fonts/simhei.ttf</boldItalic>
<pdfEncoding>Identity-H</pdfEncoding>
<pdfEmbedded>true</pdfEmbedded>
<exportFonts>
<export key="net.sf.jasperreports.html">'黑体', Arial, Helvetica, sans-serif</export>
<export key="net.sf.jasperreports.xhtml">'黑体', Arial, Helvetica, sans-serif</export>
</exportFonts>
</fontFamily>
</fontFamilies>Add the following properties to the resources directory:
net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.lobstertwo=fonts/fonts.xml2.2 Design Report
Download Jaspersoft Studio from https://community.jaspersoft.com/download-jaspersoft/community-edition/jaspersoft-studio_windows_7.x , create a report with the "黑体" font, add parameters ($P) and fields ($F), and place them in the layout. Save the report as user.jrxml and put it into the project.
2.3 Export Report
Load the report, fill data, and export based on the requested format:
public byte[] getReportData(List<User> users, String format) throws Exception {
System.err.println(users);
ClassPathResource resource = new ClassPathResource("templates/user.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(resource.getInputStream());
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(users);
Map<String, Object> parameters = new HashMap<>();
parameters.put("title", "用户列表");
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
byte[] reportContent;
try {
switch (format) {
case "pdf" -> reportContent = JasperExportManager.exportReportToPdf(jasperPrint);
case "xml" -> reportContent = JasperExportManager.exportReportToXml(jasperPrint).getBytes();
case "html" -> {
String path = "f:/user.html";
JasperExportManager.exportReportToHtmlFile(jasperPrint, path);
reportContent = Files.readAllBytes(Paths.get(path));
}
default -> throw new RuntimeException("未知报表格式");
}
} catch (JRException e) {
throw new RuntimeException(e);
}
return reportContent;
}2.4 Controller Endpoint
Expose a REST endpoint to download the report:
@GetMapping("/export/{format}")
public ResponseEntity<Resource> getItemReport(@PathVariable String format) throws Exception {
List<User> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new User(i + 0L, "姓名 - " + i, new Random().nextInt(100), i + "@qq.com", "地址 - " + i));
}
byte[] reportContent = getReportData(list, format);
ByteArrayResource resource = new ByteArrayResource(reportContent);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(resource.contentLength())
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment().filename("user-report." + format).build().toString())
.body(resource);
}2.5 Test URLs
Access the following URLs to download reports in different formats:
http://localhost:8080/users/export/pdf http://localhost:8080/users/export/xml http://localhost:8080/users/export/html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
