JasperConfig.java 2.4 KB
package com.huaheng.framework.jasper;

import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.util.JRLoader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/jasper")
public class JasperConfig {

    @Resource
    private DataSource dataSource;
    @Resource
    private InventoryDetailService inventoryDetailService;


    /**
     * 转换为pdf展示
     *
     * @param reportName
     * @param parameters
     * @param response
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws JRException
     * @throws IOException
     */
    @GetMapping("/{reportName}")
    public void getReportByParam(
            @PathVariable("reportName") final String reportName,
            @RequestParam(required = false) Map<String, Object> parameters,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

//        parameters = parameters == null ? new HashMap<>() : parameters;
//        //获取文件流
//        ClassPathResource resource = new ClassPathResource("jaspers" + File.separator + reportName + ".jasper");
//        InputStream jasperStream = resource.getInputStream();
//
//        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
//        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection());
//        // JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, new JREmptyDataSource());
//        response.setContentType("application/pdf");
//        response.setHeader("Content-Disposition", "inline;");
//        final OutputStream outputStream = response.getOutputStream();
//        JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        parameters = inventoryDetailService.getinventory();
        JasperReportsPdfView jasperReportsPdfView = new JasperReportsPdfView("jaspers/mypage.jasper","mypage.pdf");
        jasperReportsPdfView.renderMergedOutputModel(parameters,request,response);
    }
}