Jasper父子报表

package com.test.controller;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class JasperController {
    /**
     * 父子报表
     */
    @GetMapping("/testJasper")
    public void createPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.引入jasper文件
        Resource resource = new ClassPathResource("template/main.jasper");//父报表
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.创建JasperPrint,向jasper文件中填充数据
        ServletOutputStream os = response.getOutputStream();
        try {
            Map parameters = new HashMap<>();
            Resource subResource = new ClassPathResource("template/son.jasper");//子报表
            //sublist为创建的parameter的名称,value的类型选择集合
            parameters.put("sublist","子报表需要的数据集合");
            //子报表的数据需要JRBeanCollectionDataSource传递,这里是map传递的集合,所以需要子报表从集合中解析
            //new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{sublist})
            //JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource("对象集合");
            //JasperPrint print = JasperFillManager.fillReport(fis, parameters,ds);
            parameters.put("subpath",subResource.getFile().getPath());//子报表的路径
            JasperPrint print = JasperFillManager.fillReport(fis, parameters,new JREmptyDataSource());
            //3.将JasperPrint以PDF的形式输出
            JasperExportManager.exportReportToPdfStream(print,os);
        } catch (JRException e) {
            e.printStackTrace();
        }finally {
            os.flush();
        }
    }
}

 

posted @ 2020-12-27 00:14  lost_s  阅读(307)  评论(0编辑  收藏  举报