美文网首页
将ireport制作的.jrxml文件转成.html并输出到前端

将ireport制作的.jrxml文件转成.html并输出到前端

作者: 09c72470861c | 来源:发表于2019-04-30 16:15 被阅读0次

    springmvc中pom依赖:

    <!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports -->
            <dependency>
                <groupId>net.sf.jasperreports</groupId>
                <artifactId>jasperreports</artifactId>
                <version>6.8.0</version>
            </dependency>
            
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.0</version>
            </dependency>
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itext-pdfa</artifactId>
                <version>5.5.0</version>
            </dependency>
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itext-asian</artifactId>
                <version>5.2.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
            <dependency>
                <groupId>com.lowagie</groupId>
                <artifactId>itext</artifactId>
                <version>2.1.7</version>
            </dependency>
            
            <!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
            <dependency>
              <groupId>org.codehaus.groovy</groupId>
              <artifactId>groovy-all</artifactId>
             <version>2.5.6</version>
             <type>pom</type>
            </dependency>
    

    数据源的配置类

    package top.mau5.configuration;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    
    import java.util.HashMap;
    import java.util.Map;
    
    
    @Configuration
    @EnableAutoConfiguration
    public class DruidDBConfig {
    
        private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
    
        @Value("${spring.datasource.url}")
        private String dbUrl;
    
        @Value("${spring.datasource.username}")
        private String username;
    
        @Value("${spring.datasource.password}")
        private String password;
    
        @Value("${spring.datasource.driverClassName}")
        private String driverClassName;
    
    //    @Value("${spring.datasource.initialSize}")
    //    private int initialSize;
    //
    //    @Value("${spring.datasource.minIdle}")
    //    private int minIdle;
    //
    //    @Value("${spring.datasource.maxActive}")
    //    private int maxActive;
    //
    //    @Value("${spring.datasource.maxWait}")
    //    private int maxWait;
    //
    //    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    //    private int timeBetweenEvictionRunsMillis;
    //
    //    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    //    private int minEvictableIdleTimeMillis;
    //
    //    @Value("${spring.datasource.validationQuery}")
    //    private String validationQuery;
    //
    //    @Value("${spring.datasource.testWhileIdle}")
    //    private boolean testWhileIdle;
    //
    //    @Value("${spring.datasource.testOnBorrow}")
    //    private boolean testOnBorrow;
    //
    //    @Value("${spring.datasource.testOnReturn}")
    //    private boolean testOnReturn;
    //
    //    @Value("${spring.datasource.poolPreparedStatements}")
    //    private boolean poolPreparedStatements;
    //
    //    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    //    private int maxPoolPreparedStatementPerConnectionSize;
    //
    //    @Value("${spring.datasource.filters}")
    //    private String filters;
    //
    //    @Value("{spring.datasource.connectionProperties}")
    //    private String connectionProperties;
    
        @Bean     //声明其为Bean实例
        @Primary  //在同样的DataSource中,首先使用被标注的DataSource
        public DruidDataSource dataSource(){
            DruidDataSource datasource = new DruidDataSource();
    
            datasource.setUrl(this.dbUrl);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName);
    
    //        //configuration
    //        datasource.setInitialSize(initialSize);
    //        datasource.setMinIdle(minIdle);
    //        datasource.setMaxActive(maxActive);
    //        datasource.setMaxWait(maxWait);
    //        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    //        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    //        datasource.setValidationQuery(validationQuery);
    //        datasource.setTestWhileIdle(testWhileIdle);
    //        datasource.setTestOnBorrow(testOnBorrow);
    //        datasource.setTestOnReturn(testOnReturn);
    //        datasource.setPoolPreparedStatements(poolPreparedStatements);
    //        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    //        try {
    //            datasource.setFilters(filters);
    //        } catch (SQLException e) {
    //            logger.error("druid configuration initialization filter", e);
    //        }
    //        datasource.setConnectionProperties(connectionProperties);
    
            return datasource;
        }
    
        @Bean
        public ServletRegistrationBean druidServletRegistrationBean() {
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
            servletRegistrationBean.setServlet(new StatViewServlet());
            servletRegistrationBean.addUrlMappings("/druid/*");
            return servletRegistrationBean;
        }
    
        /**
         * 注册DruidFilter拦截
         *
         * @return
         */
        
        @Bean
        public FilterRegistrationBean duridFilterRegistrationBean() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
            filterRegistrationBean.setFilter(new WebStatFilter());
            Map<String, String> initParams = new HashMap<String, String>();
            //设置忽略请求
            initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
            filterRegistrationBean.setInitParameters(initParams);
            filterRegistrationBean.addUrlPatterns("/*");
            return filterRegistrationBean;
        }
    
    }
    

    controller:

    @RequestMapping(value = "report")
    @RestController
    public class ReportController {
        
        @Autowired
        DruidDataSource druidDataSource;
        
        @Autowired
        ReportService reportService;
        
        public static final String ROOT_PATH = "C:\\Users\\korin\\Desktop\\jaspertest\\";//本机文件保存地址
    //  public static final String ROOT_PATH = "C:\\jaspertest\\";//云服务器文件保存地址
        
        @RequestMapping("uploadJrxml")
        public Map<String,Object> fileUpload(MultipartFile file) throws IllegalStateException, IOException{
            System.out.println(file.getOriginalFilename());
            Filepath filepath = new Filepath();
            filepath.setName(file.getOriginalFilename());
            filepath.setPath(ROOT_PATH+filepath.getName());
            file.transferTo(new File(filepath.getPath()));
            
            reportService.insesrt(filepath);
            Map<String,Object> map = new HashMap<>();
            map.put("msg", "ok");
            map.put("uuid", filepath.getRid());
            return map;
        }
        
        @RequestMapping("showfilelist")
        public List<Filepath> showfilelist() throws IllegalStateException, IOException{
            return reportService.select(new Filepath());
        }
        /**
         * 通过jrxml文件生成html,参数固定测试版
         * 
         * 在这之前应该有个上传jrxml文件功能,上传到指定文件夹,存数据库(uuid,存储路径等)后返回uuid
         * 
         * @param jrxml_path jrxml存放路径
         * @param id 主键id
         * @return
         * @throws JRException 
         * @throws IOException 
         * @throws UnsupportedEncodingException 
         */
        @RequestMapping(value = "jrxml2html",produces = "text/html;charset=UTF-8")/* 返回格式为text/html */
        public String  jrxml2html(HttpServletRequest request,String jrxmlName,String id) throws JRException, UnsupportedEncodingException, IOException {
            
            JasperReport jasper = JasperCompileManager.compileReport(new FileInputStream(new File("C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".jrxml")));
            
            Map<String,Object> map = new HashMap<>();
            map.put("P_YHTZID", id);
            Connection conn = null;
            String str = "";
            try {
                /* 生成html文件 */
                conn = druidDataSource.getConnection();
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);
                JasperExportManager.exportReportToHtmlFile(jasperPrint,"C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
                
                /* 读取html文件 */
                URL url = new URL("file:\\C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
                BufferedReader br = null;
                br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
                String res;
                StringBuilder sb = new StringBuilder("");
                while ((res = br.readLine()) != null) {
                    sb.append(res.trim());
                }
                str = sb.toString();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return str;
        }
        
        //参数可变
        @RequestMapping(value = "jrxml2html_",produces = "text/html;charset=UTF-8")/* 返回格式为text/html */
        public String  jrxml2html_(HttpServletRequest request) throws JRException, UnsupportedEncodingException, IOException {
            Map<String,Object> map = getParameterMap(request);
            String jrxmlName = map.get("jrxmlName").toString();
            //,String jrxmlName,String paramId
            JasperReport jasper = JasperCompileManager.compileReport(new FileInputStream(new File("C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".jrxml")));
    //      map.put("P_YHTZID", id);
            Connection conn = null;
            String str = "";
            try {
                /* 生成html文件 */
                conn = druidDataSource.getConnection();
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);
                JasperExportManager.exportReportToHtmlFile(jasperPrint,"C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
                
                /* 读取html文件 */
                URL url = new URL("file:\\C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
                BufferedReader br = null;
                br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
                String res;
                StringBuilder sb = new StringBuilder("");
                while ((res = br.readLine()) != null) {
                    sb.append(res.trim());
                }
                str = sb.toString();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return str;
        }
        
        //优化后
        /**
         * @param request   参数中要带rid(在数据库filepath表中的rid)和相应的报表中所需的参数名和值(如P_YHTZID=...)
         * @return
         * @throws JRException
         * @throws UnsupportedEncodingException
         * @throws IOException
         */
        @RequestMapping(value = "jrxml2html__",produces = "text/html;charset=UTF-8")/* 返回格式为text/html */
        public String  jrxml2html__(HttpServletRequest request) throws JRException, UnsupportedEncodingException, IOException {
            Filepath filepath = new Filepath();
            Map<String,Object> map = getParameterMap(request);
            filepath.setRid(map.get("rid").toString());
            String filePath = reportService.select(filepath).get(0).getPath();
            InputStream is = new FileInputStream(new File(filePath));
            JasperReport jasper = JasperCompileManager.compileReport(is);
            Connection conn = null;
            String str = "";
            filePath = filePath.replaceAll(".jrxml", ".html");//html文件路径
            try {
                /* 生成html文件 */
                File file = new File(filePath);
                if(file.exists()) {
                    file.delete();//删除以前的html文件
                }
                conn = druidDataSource.getConnection();
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);
                JasperExportManager.exportReportToHtmlFile(jasperPrint,filePath);
                
                /* 读取html文件 */
                URL url = new URL("file:\\"+filePath);
                BufferedReader br = null;
                br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
                String res;
                StringBuilder sb = new StringBuilder("");
                while ((res = br.readLine()) != null) {
                    sb.append(res.trim());
                }
                str = sb.toString();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    is.close();//关流
                    conn.close();//关闭数据库连接
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return str;
        }
    
        protected Map<String, Object> getParameterMap(HttpServletRequest request) {
            return getParameterMap(request, false);
        }
    
        protected Map<String, Object> getParameterMap(HttpServletRequest request, boolean needNull) {
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String paramName : parameterMap.keySet()) {
                String[] paramValues = parameterMap.get(paramName);
                if (null != paramValues && paramValues.length > 1) {
                    map.put(paramName, paramValues);
                } else if (null != paramValues) {
                    String paramValue = parameterMap.get(paramName)[0];
                    if (StringUtils.isNotEmpty(paramValue) || needNull) {
                        map.put(paramName, paramValue);
                    }
                }
            }
            return map;
        }
    }
    

    相关文章

      网友评论

          本文标题:将ireport制作的.jrxml文件转成.html并输出到前端

          本文链接:https://www.haomeiwen.com/subject/ieuvnqtx.html