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

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容