SpringBoot整合JasperReport报表生成PDF
SpringBoot整合JasperReport生成PDF
步骤:
- pom文件引入JasperReport坐标
- 生成JasperReport模板文件
- 开发代码
引入依赖
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.19.0</version>
<exclusions>
<exclusion>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
<exclusion>
<artifactId>commons-collections</artifactId>
<groupId>commons-collections</groupId>
</exclusion>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
生成JasperReport模板
生成JasperReport模板网上有很多资料,这里只提注意项!
需要给列表画框,可以选择给Text Field、Static Text的基本属性中选择对应的边框,也可以在基本元素中选择画矩形。
开发代码
//引入JasperReport模板
ClassPathResource resource = new ClassPathResource("templates/pdf/Blank_A4_Landscape.jasper");
ServletOutputStream os = response.getOutputStream();
FileInputStream fs = new FileInputStream(resource.getFile());
//创建了Parameters参数,只需要将数据封装进map
Map<String, Object> map = new HashMap<>();
map.put("title","中文");
//创建了fields参数,需要将数据封装成List<Map>
List< Map<String, Object>> listmap = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name","小明");
Map<String, Object> map2 = new HashMap<>();
map2.put("name","小红");
listmap.add(map1);
listmap.add(map2);
//只创建了Parameters参数,选这种
JasperPrint jasperPrint1 = JasperFillManager.fillReport(fs,map,new JREmptyDataSource());
//同时创建了Parameters、fields参数,选这种,将List<Map>添加到JRBeanCollectionDataSource数据源中
JasperPrint jasperPrint2 = JasperFillManager.fillReport(fs,map,new JRBeanCollectionDataSource(listmap));
JasperExportManager.exportReportToPdfStream(jasperPrint2,os);
注意,pdf数据中带有中文,输出pdf无法展示,可以采用引入外部字体(字体需与模板文件中的字体想对应)
字体的xml文件,如果输出数据为垂直输出,如图修改就可以了