Jasperreport之与Springboot整合
作者:互联网
环境:
jdk1.8
Jaspersoft Studio 6.5.0
Jasperreport 6.5.0
Springboot 1.5.x
一 用Jaspersoft Studio报表设计器设计一个报表test.jrxml
此处省略
二 整合springboot实现pdf预览报表数据 采用javabean数据方式
pom.xml增加
<!-- jasperreports--> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>6.5.0</version> </dependency> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports-fonts</artifactId> <version>6.0.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> <dependency> <groupId>cn.lesper</groupId> <artifactId>iTextAsian</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.4.11</version> </dependency> <!-- jasperreports end--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency>
在src/main/resources下增加jasperreport文件夹 并将test.jrxml文件放入此处
控制器部分代码
@Autowired private ApplicationContext appContext; public List<Product> getProductList() { List<Product> list = new ArrayList<>(); for (int i = 1; i <= 20; i++) { list.add(new Product(String.valueOf(i), "名称" + i)); } return list; } @RequestMapping(path = "/pdfPreview", method = RequestMethod.GET) public ModelAndView pdfPreview() { JasperReportsPdfView view = new JasperReportsPdfView(); view.setUrl("classpath:jasperreport/test.jrxml"); view.setApplicationContext(appContext); Map<String, Object> params = new HashMap<>(); //列表数据源 数据源字段名称和类型需要和报表设计的字段一致 params.put("datasource", getProductList()); //给参数赋值 params.put("Parameter1", "hello 你好"); return new ModelAndView(view, params); } //html预览 前端调用<iframe src="/htmlPreview" width="100%" height="800px"></iframe> @RequestMapping(path = "/htmlPreview", method = RequestMethod.GET) public void reportHtml(HttpServletRequest request, HttpServletResponse response) throws Exception { JRDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(getProductList()); Map params = new HashMap(); params.put("Parameter1", "hello 你好"); //编译jrxml文件,生成jasper文件 URL url = this.getClass().getClassLoader().getResource("jasperreport/test.jrxml"); JasperCompileManager.compileReportToFile(url.getPath()); File jasperFile = ResourceUtils.getFile("classpath:jasperreport/test.jasper"); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrBeanCollectionDataSource); JasperExportManager.exportReportToHtmlFile(jasperPrint, request.getServletContext().getRealPath("/") + "reportPreviewTemp.html"); response.sendRedirect("reportPreviewTemp.html"); } @RequestMapping(path = "/pdfExport", method = RequestMethod.GET) public String pdfExport(HttpServletRequest request, HttpServletResponse response) throws Exception { JRDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(getProductList()); Map params = new HashMap(); params.put("Parameter1", "hello 你好"); //编译jrxml文件,生成jasper文件 URL url = this.getClass().getClassLoader().getResource("jasperreport/test.jrxml"); JasperCompileManager.compileReportToFile(url.getPath()); File jasperFile = ResourceUtils.getFile("classpath:jasperreport/test.jasper"); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrBeanCollectionDataSource); JRPdfExporter pdf = new JRPdfExporter(); pdf.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); pdf.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream()); String fileName = new String("测试.pdf".getBytes("utf-8"), "ISO_8859_1"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.setContentType("application/pdf"); response.setCharacterEncoding("utf-8"); pdf.exportReport(); return null; } //预览并浏览器自动弹出打印 @RequestMapping(path = "/previewPrint", method = RequestMethod.GET) public void previewPrint(HttpServletRequest request, HttpServletResponse response) throws Exception { JRDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(getProductList()); Map params = new HashMap(); params.put("Parameter1", "hello 你好"); //编译jrxml文件,生成jasper文件 URL url = this.getClass().getClassLoader().getResource("jasperreport/test.jrxml"); JasperCompileManager.compileReportToFile(url.getPath()); File jasperFile = ResourceUtils.getFile("classpath:jasperreport/test.jasper"); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile); byte[] pdfStream = JasperRunManager.runReportToPdf(jasperReport, params, jrBeanCollectionDataSource); PdfReader reader = new PdfReader(pdfStream); ByteArrayOutputStream bos = new ByteArrayOutputStream(pdfStream.length); try { // 给pdf加上脚本实现自动打印 StringBuffer script = new StringBuffer(); script.append("this.print({bUI:false,bSilent:true,bShrinkToFit:false});"); PdfStamper stamp = new PdfStamper(reader, bos); stamp.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI); stamp.addJavaScript(script.toString()); stamp.close(); } catch (Exception e) { } // 输出pdf byte[] bytes = bos.toByteArray(); if (bytes != null && bytes.length > 0) { response.setContentType("application/pdf"); response.setContentLength(bytes.length); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); ServletOutputStream ouputStream = response.getOutputStream(); try { ouputStream.write(bytes, 0, bytes.length); ouputStream.flush(); } finally { if (ouputStream != null) { try { ouputStream.close(); } catch (IOException ex) { } } } } } //连接打印机打印 @RequestMapping(path = "/print1", method = RequestMethod.GET) public void print1(HttpServletRequest request, HttpServletResponse response) throws Exception { JRDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(getProductList()); Map params = new HashMap(); params.put("Parameter1", "hello 你好"); //编译jrxml文件,生成jasper文件 URL url = this.getClass().getClassLoader().getResource("jasperreport/test.jrxml"); JasperCompileManager.compileReportToFile(url.getPath()); File jasperFile = ResourceUtils.getFile("classpath:jasperreport/test.jasper"); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrBeanCollectionDataSource); //设置打印方向 LANDSCAPE横向 PORTRAIT竖向 jasperPrint.setOrientation(OrientationEnum.LANDSCAPE); //withPrintDialog表示在打印的时候是否显示打印机设置对话框 JasperPrintManager.printReport(jasperPrint, false); }
访问可以看到实现了pdf预览,但是中文没有显示
可以在报表设计器设置对应字段元素属性
pdfFontName设置成"STSong-Light"
pdfEncoding设置成"UniGB-UCS2-H"
isPdfEmbedded设置成"true"
字段元素太多一个个设置 太麻烦 可以在test.jrxml文件统一设置默认属性
在property节点后面增加一行自定义样式
<style name="myStyle" isDefault="true" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
再次拷贝该jrxml文件到项目中,重启应用再访问 可以看到显示了中文
附上test.jrxml内容
<?xml version="1.0" encoding="UTF-8"?> <!-- Created with Jaspersoft Studio version 6.5.0.final using JasperReports Library version 6.5.0 --> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test" pageWidth="683" pageHeight="397" columnWidth="643" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="5e3bdc2e-17e7-44d3-bf7e-c714ccba4acd"> <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/> <style name="myStyle" isDefault="true" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/> <subDataset name="Dataset1" uuid="117df1fc-65c8-4b6e-ac00-35ce27f2173f"> <queryString> <![CDATA[]]> </queryString> </subDataset> <parameter name="Parameter1" class="java.lang.String" isForPrompting="false"/> <queryString> <![CDATA[]]> </queryString> <field name="id" class="java.lang.String"/> <field name="name" class="java.lang.String"/> <background> <band splitType="Stretch"/> </background> <pageHeader> <band height="56" splitType="Stretch"> <staticText> <reportElement positionType="Float" x="240" y="10" width="100" height="30" uuid="4be77cf7-7531-4f83-8f55-f5c04ede9136"/> <textElement> <font size="18"/> </textElement> <text><![CDATA[单 据]]></text> </staticText> <textField> <reportElement x="340" y="10" width="110" height="30" uuid="fac9ba58-f08b-4010-b22b-da3e61c3935e"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA["Page " + $V{PAGE_NUMBER}]]></textFieldExpression> </textField> <textField evaluationTime="Report"> <reportElement x="450" y="10" width="100" height="30" uuid="825fa517-39e6-4618-a96d-a9b1b1a10ec6"/> <textElement textAlignment="Left"/> <textFieldExpression><![CDATA[" of " + $V{PAGE_NUMBER}]]></textFieldExpression> </textField> <textField isBlankWhenNull="true"> <reportElement x="73" y="25" width="100" height="30" uuid="b6308366-897f-4472-8ab8-19d2f8ca7424"/> <textFieldExpression><![CDATA[$P{Parameter1}]]></textFieldExpression> </textField> </band> </pageHeader> <columnHeader> <band height="30" splitType="Stretch"> <staticText> <reportElement x="162" y="10" width="70" height="20" backcolor="#FFFFFF" uuid="10e12ad7-e1c5-4008-be59-e69474063d8d"/> <box> <topPen lineWidth="1.0"/> <leftPen lineWidth="1.0"/> <bottomPen lineWidth="1.0"/> <rightPen lineWidth="1.0"/> </box> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[序号]]></text> </staticText> <staticText> <reportElement x="232" y="10" width="70" height="20" backcolor="#FFFFFF" uuid="c5a567e9-8fa1-4393-9bcf-c5764414813b"/> <box> <topPen lineWidth="1.0"/> <leftPen lineWidth="1.0"/> <bottomPen lineWidth="1.0"/> <rightPen lineWidth="1.0"/> </box> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> <paragraph lineSpacing="Single"/> </textElement> <text><![CDATA[编号]]></text> </staticText> <staticText> <reportElement stretchType="RelativeToBandHeight" x="302" y="10" width="70" height="20" backcolor="#FFFFFF" uuid="5c24a436-285f-45f6-bccb-d31cd40128f9"/> <box> <topPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <leftPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <bottomPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <rightPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> </box> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[名称]]></text> </staticText> </band> </columnHeader> <detail> <band height="20" splitType="Stretch"> <textField> <reportElement x="162" y="0" width="70" height="20" uuid="60afe658-137c-429e-9951-ce9cfdc7696d"> <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="61453adc-a515-4954-bc49-44fc1e3bb7af"/> <property name="com.jaspersoft.studio.unit.height" value="px"/> </reportElement> <box> <topPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <leftPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <bottomPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <rightPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> </box> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression> </textField> <textField isBlankWhenNull="true"> <reportElement x="232" y="0" width="70" height="20" uuid="f8367ae9-a695-45e3-bd1c-cb4392a44754"> <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="61453adc-a515-4954-bc49-44fc1e3bb7af"/> </reportElement> <box> <topPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <leftPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <bottomPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <rightPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> </box> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression> </textField> <textField isBlankWhenNull="true"> <reportElement x="302" y="0" width="70" height="20" uuid="fa59b15a-3e81-4354-b0cd-0240618fe99f"> <property name="com.jaspersoft.studio.spreadsheet.connectionID" value="77533d37-8f7a-46b5-b629-15f7cea898ca"/> </reportElement> <box> <topPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <leftPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <bottomPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> <rightPen lineWidth="1.0" lineStyle="Solid" lineColor="#000000"/> </box> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band height="56" splitType="Stretch"> <staticText> <reportElement positionType="Float" x="240" y="10" width="100" height="30" uuid="d9b9e6f5-2bb1-4c07-bda5-19c358c7d49f"/> <textElement> <font size="18"/> </textElement> <text><![CDATA[column foot]]></text> </staticText> </band> </columnFooter> <pageFooter> <band height="81" splitType="Stretch"> <staticText> <reportElement positionType="Float" x="240" y="10" width="100" height="30" uuid="1eb55c2c-320e-47bd-8373-23fe8bc4d07d"/> <textElement> <font size="18"/> </textElement> <text><![CDATA[page foot]]></text> </staticText> <line> <reportElement positionType="Float" x="177" y="64" width="200" height="1" uuid="ef26a332-3079-4745-9af1-232a24281bc9"> <property name="com.jaspersoft.studio.unit.width" value="px"/> </reportElement> <graphicElement> <pen lineWidth="5.0" lineStyle="Solid"/> </graphicElement> </line> </band> </pageFooter> </jasperReport>
导出excel 需要增加maven poi
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency>
//导出到excel文件 @RequestMapping(path = "/exportExcel", method = RequestMethod.GET) public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception { JRDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(getProductList()); Map params = new HashMap(); params.put("Parameter1", "hello 你好"); //编译jrxml文件,生成jasper文件 URL url = this.getClass().getClassLoader().getResource("jasperreport/test.jrxml"); JasperCompileManager.compileReportToFile(url.getPath()); File jasperFile = ResourceUtils.getFile("classpath:jasperreport/test.jasper"); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrBeanCollectionDataSource); ByteArrayOutputStream outPut=new ByteArrayOutputStream(); FileOutputStream outputStream=null; File file=new File("F:/temp/report.xls"); try { JRAbstractExporter exporter = new JRXlsExporter(); //创建jasperPrint exporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint); //生成输出流 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,outPut); //去除两行之前的空白 exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE); //设置所有页只打印到一个Sheet中 exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE); //设置Excel表格的背景颜色为默认的白色 exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE); String[] sheetNames = {"自定义1","自定义2","自定义3"}; //自定义sheet名称 exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, sheetNames); exporter.exportReport(); outputStream=new FileOutputStream(file); outputStream.write(outPut.toByteArray()); }catch (Exception e) { e.printStackTrace(); }finally{ try { outPut.flush(); outPut.close(); } catch (Exception e) { e.printStackTrace(); } } } //直接下载excel文件 @RequestMapping(path = "/exportDownload", method = RequestMethod.GET) public void exportDownload(HttpServletRequest request, HttpServletResponse response) throws Exception { JRDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(getProductList()); Map params = new HashMap(); params.put("Parameter1", "hello 你好"); //编译jrxml文件,生成jasper文件 URL url = this.getClass().getClassLoader().getResource("jasperreport/test.jrxml"); JasperCompileManager.compileReportToFile(url.getPath()); File jasperFile = ResourceUtils.getFile("classpath:jasperreport/test.jasper"); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrBeanCollectionDataSource); response.setContentType("application/vnd.ms-excel"); String fileName="导出文件.xlsx"; fileName = new String( fileName.getBytes("gb2312"), "ISO8859-1" ); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment; filename="+ fileName); ServletOutputStream ouputStream = response.getOutputStream(); try { JRXlsxExporter exporter = new JRXlsxExporter(); SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration(); configuration.setOnePagePerSheet(false); configuration.setWhitePageBackground(false); configuration.setIgnorePageMargins(true); String[] sheetNames = {"sheet1"}; configuration.setSheetNames(sheetNames); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(ouputStream)); exporter.setConfiguration(configuration); exporter.exportReport(); } catch (Exception e) { e.printStackTrace(); }finally{ try { ouputStream.flush(); ouputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
标签:jrxml,Springboot,jasperreport,Jasperreport,params,整合,test,new,response 来源: https://www.cnblogs.com/zengnansheng/p/10404737.html