因为jasperReort是开源的,所以用来做小项目非常合适,原理就是使用Soft工具设计模板,生成jasper文件,将jasper放在java项目静态资源目录,使用工具类将数据库数据写入模板中,返回流给客户端下载或返回PDF给客户端。
(一)pom依赖
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.16.0</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
(二)中文字体依赖和配置
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.xml
(三)核心工具类
@Slf4j
public class JasperReportUtil {
final static String jasperDir = "report";
public static String getJasperFileDir(String fileName) {
return jasperDir + File.separator + fileName + ".jasper";
}
private static String getContentType(ReportType type) {
String contentType;
switch (type) {
case HTML:
contentType = "text/html;charset=utf-8";
break;
case PDF:
contentType = "application/pdf";
break;
case IMAGE:
contentType = "image/jpeg";
break;
case XLS:
contentType = "application/vnd.ms-excel";
break;
case XLSX:
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case XML:
contentType = "text/xml";
break;
case RTF:
contentType = "application/rtf";
break;
case CSV:
contentType = "text/plain";
break;
case DOC:
contentType = "application/msword";
break;
default:
contentType = "text/html;charset=utf-8";
}
return contentType;
}
static JasperPrint getJasperPrint(InputStream jasperStream, Map parameters, List<?> list) throws JRException {
JRDataSource dataSource = null;
if (null == list || list.size() == 0) {
dataSource = new JREmptyDataSource();
} else {
dataSource = new JRBeanCollectionDataSource(list);
}
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperStream, parameters, dataSource);
return jasperPrint;
}
public static void exportToPdf(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
OutputStream outputStream = response.getOutputStream();
try {
ClassPathResource resource = new ClassPathResource(jasperPath);
response.setContentType(getContentType(ReportType.PDF));
InputStream jasperStream = resource.getInputStream();
JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
} catch (Exception e) {
log.error("读取报表异常", e);
System.out.println("读取报表异常"+ e.toString());
outputStream.write("读取报表异常".getBytes());
} finally {
outputStream.flush();
outputStream.close();
}
}
public static void exportToPdfFile(String jasperPath, Map parameters, List<?> list,String desFilePath) throws Exception {
try {
ClassPathResource resource = new ClassPathResource(jasperPath);
InputStream jasperStream = resource.getInputStream();
JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
System.out.println("写入文件路径:"+desFilePath);
// 输出文档
JasperExportManager.exportReportToPdfFile(jasperPrint, desFilePath);
} catch (Exception e) {
log.error("读取报表异常", e);
System.out.println("读取报表异常"+ e.toString());
} finally {
}
}
public static byte[] exportToPdfBytes(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
try {
ClassPathResource resource = new ClassPathResource(jasperPath);
//response.setContentType(getContentType(ReportType.PDF));
InputStream jasperStream = resource.getInputStream();
JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
byte[] body = JasperExportManager.exportReportToPdf(jasperPrint);
return body;
} catch (Exception e) {
log.error("读取报表异常", e);
System.out.println("读取报表异常"+ e.toString());
} finally {
}
return null;
}
public static void exportToXml(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
OutputStream outputStream = response.getOutputStream();
try {
ClassPathResource resource = new ClassPathResource(jasperPath);
response.setContentType(getContentType(ReportType.XML));
InputStream jasperStream = resource.getInputStream();
JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
JasperExportManager.exportReportToXmlStream(jasperPrint, outputStream);
} catch (Exception e) {
log.error("读取报表异常", e);
outputStream.write("读取报表异常".getBytes());
} finally {
outputStream.flush();
outputStream.close();
}
}
public static void exportToHtml(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
response.setHeader("Content-type", "text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType(getContentType(ReportType.HTML));
PrintWriter out = response.getWriter();
HtmlExporter exporter = new HtmlExporter();
try {
ClassPathResource resource = new ClassPathResource(jasperPath);
InputStream jasperStream = resource.getInputStream();
JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
SimpleHtmlReportConfiguration configuration = new SimpleHtmlReportConfiguration();
exporter.setConfiguration(configuration);
HtmlExporterOutput outPut = new SimpleHtmlExporterOutput(out);
exporter.setExporterOutput(outPut);
exporter.exportReport();
} catch (Exception e) {
log.error("读取报表异常", e);
out.write("读取报表异常");
} finally {
out.flush();
out.close();
}
}
public static void exportToImage(String jasperPath, Map parameters, List<?> list, HttpServletResponse response) throws Exception {
//生成图片报表
OutputStream outputStream = response.getOutputStream();
response.setContentType(getContentType(ReportType.IMAGE));
ClassPathResource resource = new ClassPathResource(jasperPath);
InputStream jasperStream = resource.getInputStream();
JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
JRGraphics2DExporter exporter = new JRGraphics2DExporter();//创建graphics输出器
//创建一个影像对象
BufferedImage bufferedImage = new BufferedImage(jasperPrint.getPageWidth() * 4, jasperPrint.getPageHeight() * 4, BufferedImage.TYPE_INT_RGB);
//取graphics
Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
//设置相应参数信息
exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, g);
exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, Float.valueOf(4));
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
g.dispose();//释放资源信息
//这里的bufferedImage就是最终的影像图像信息,可以通过这个对象导入到cm中了.
//ImageIO.write(bufferedImage, "JPEG", new File("d:/aa.jpg"));
ImageIO.write(bufferedImage,"JPEG", outputStream);
}
public static void exportToImageFile(String jasperPath, Map parameters, List<?> list,String desFilePath) throws Exception {
//生成图片报表
byte[] data = null;
ClassPathResource resource = new ClassPathResource(jasperPath);
InputStream jasperStream = resource.getInputStream();
JasperPrint jasperPrint = getJasperPrint(jasperStream, parameters, list);
JRGraphics2DExporter exporter = new JRGraphics2DExporter();//创建graphics输出器
//创建一个影像对象
BufferedImage bufferedImage = new BufferedImage(jasperPrint.getPageWidth() * 4, jasperPrint.getPageHeight() * 4, BufferedImage.TYPE_INT_RGB);
//取graphics
Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
//设置相应参数信息
exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, g);
exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, Float.valueOf(4));
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
g.dispose();//释放资源信息
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//这里的bufferedImage就是最终的影像图像信息,可以通过这个对象导入到cm中了.
System.out.println("写入文件路径:"+desFilePath);
ImageIO.write(bufferedImage, "JPEG", new File(desFilePath));
// ImageIO.write(bufferedImage,"JPEG", baos);
// baos.flush();
// data = baos.toByteArray();
// baos.close();
// return data;
}
public enum ReportType {
HTML,
PDF,
XLS,
XLSX,
XML,
RTF,
CSV,
DOC,
IMAGE
}
}
控制层调用:
如果是返回PDF需要推送插件打印,控制层url一定记得配置白名单
@GetMapping("/fileTickertape")
@ApiOperation(value = "根据人员档案号生成建档凭条")
public void registeredReceipt(HttpServletResponse response , @ApiParam(name = "personalId",value = "personalId",required = true)
@RequestParam Integer personalId)
throws Exception {
Map<String, Object> parameters =personalFilesService.getOneFiles(personalId);
if(parameters==null){
throw new BusinessException("找不到该人员档案记录,无法生成建档凭条");
}
parameters.put("title","xxxx建档凭条");
parameters.put("qrcode","http://weixin.qq.com/xxxxxxx-");
List <Map<String,Object>> patrolCardSortInfo=new ArrayList<>();
String jasperPath = JasperReportUtil.getJasperFileDir("personalFileTickertape");
JasperReportUtil.exportToPdf(jasperPath, parameters, patrolCardSortInfo, response);
}
其中第三个参数patrolCardSortInfo实际上就是你需要遍历循环打印的对象集合,第二个参数是全局变量