jasperport+studio+vue+springboot 实现pdf预览
思路:使用studio生成模板,将模板导入java代码,读取模板并设值,返回二进制流或者地址给前端使用blob存储流,然后打开文件。
模板生成工具可以用ireport或者studio
主要的坑ireport只支持jdk1.7一下,建议使用studio,我使用的是ireport,高于jdk1.7的会出现一些题:比如工具闪退,工具无法加入驱动包,导致无法连接到数据库。
ireport是基于jdk开发的,这里也可以直接安装jdk1.7后直接配置irepor的conf 文件 jdkhome=“D:\software\jdk”
连接数据库方式:javabean,jdbc连接 这里介绍javabean的方式连接
详细资料请参考
https://blog.csdn.net/u013516966/article/details/43502593
https://wenku.baidu.com/view/449dfa31a517866fb84ae45c3b3567ec102ddca4.html
https://blog.csdn.net/u012369153/article/details/54598473/
studio使用方法同ireport相似
这是jrxml的生成对比
可以看见是结果是一样的。
(一)用ireport5.6模板工具生成pdf报表模板,并保存得到.jasper与.jrxml两个文件
(二)将这两个文件拷贝到springboot项目的resources目录下
(三)maven依赖
<!-- jasperreports-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.0.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>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.11</version>
</dependency>
<!-- jasperreports end-->
(四)创建JasperHelper工具类
package com.yccj.modules.query.common;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.export.*;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.sql.Connection;
import java.util.Map;
@SuppressWarnings("deprecation")
public class JasperHelper
{
public static final String PRINT_TYPE = "print";
public static final String PDF_TYPE = "pdf";
public static final String EXCEL_TYPE = "excel";
public static final String HTML_TYPE = "html";
public static final String WORD_TYPE = "word";
public static void prepareReport(JasperReport jasperReport, String type)
{
/*
* 如果导出的是excel,则需要去掉周围的margin
*/
if ("excel".equals(type)) try
{
Field margin = JRBaseReport.class.getDeclaredField("leftMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
margin = JRBaseReport.class.getDeclaredField("topMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
margin = JRBaseReport.class.getDeclaredField("bottomMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
Field pageHeight = JRBaseReport.class.getDeclaredField("pageHeight");
pageHeight.setAccessible(true);
pageHeight.setInt(jasperReport, 2147483647);
}
catch (Exception exception)
{
}
}
/**
* 导出excel
*/
public static void exportExcel(JasperPrint jasperPrint, String defaultFilename, HttpServletRequest request, HttpServletResponse response) throws IOException, JRException
{
/*
* 设置头信息
*/
response.setContentType("application/vnd.ms-excel");
String defaultname = null;
if (defaultFilename.trim() != null && defaultFilename != null)
{
defaultname = defaultFilename + ".xls";
}
else
{
defaultname = "export.xls";
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(defaultname, "UTF-8") + "\"");
ServletOutputStream ouputStream = response.getOutputStream();
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); // 删除记录最下面的空行
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);// 删除多余的ColumnHeader
//
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);// 显示边框
exporter.exportReport();
ouputStream.flush();
ouputStream.close();
}
public static enum DocType
{
PDF, HTML, XLS, XML, RTF
}
@SuppressWarnings("rawtypes")
public static JRAbstractExporter getJRExporter(DocType docType)
{
JRAbstractExporter exporter = null;
switch (docType)
{
case PDF:
exporter = new JRPdfExporter();
break;
case HTML:
exporter = new JRHtmlExporter();
break;
case XLS:
exporter = new JExcelApiExporter();
break;
case XML:
exporter = new JRXmlExporter();
break;
case RTF:
exporter = new JRRtfExporter();
break;
}
return exporter;
}
/**
* 导出pdf,注意此处中文问题,
* <p>
* 这里应该详细说:主要在ireport里变下就行了。看图
* <p>
* 1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏。
* <p>
* 下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H
*/
private static void exportPdf(JasperPrint jasperPrint, String defaultFilename, HttpServletRequest request, HttpServletResponse response) throws IOException, JRException
{
response.setContentType("application/pdf");
String defaultname = null;
if (defaultFilename.trim() != null && defaultFilename != null)
{
defaultname = defaultFilename + ".pdf";
}
else
{
defaultname = "export.pdf";
}
String fileName = new String(defaultname.getBytes("GBK"), "ISO8859_1");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
ServletOutputStream ouputStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
ouputStream.flush();
ouputStream.close();
}
/**
* 导出html
*/
private static void exportHtml(JasperPrint jasperPrint, String defaultFilename, HttpServletRequest request, HttpServletResponse response) throws IOException, JRException
{
response.setContentType("text/html");
ServletOutputStream ouputStream = response.getOutputStream();
JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
//设置图片文件存放路径,此路径为服务器上的绝对路径
String imageDIR = request.getSession().getServletContext().getRealPath("/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);
//设置图片请求URI
String imageURI = request.getContextPath() + "/";
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);
//设置导出图片到图片存放路径
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.exportReport();
ouputStream.flush();
ouputStream.close();
}
/**
* 导出word
*/
@SuppressWarnings("rawtypes")
private static void exportWord(JasperPrint jasperPrint, String defaultFilename, HttpServletRequest request, HttpServletResponse response) throws JRException, IOException
{
response.setContentType("application/msword;charset=utf-8");
String defaultname = null;
if (defaultFilename.trim() != null && defaultFilename != null)
{
defaultname = defaultFilename + ".doc";
}
else
{
defaultname = "export.doc";
}
String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
JRExporter exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
exporter.exportReport();
}
public static void export(String type, String defaultFilename, File is, HttpServletRequest request, HttpServletResponse response, Map parameters, Connection conn)
{
try
{
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
prepareReport(jasperReport, type);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
if (EXCEL_TYPE.equals(type))
{
exportExcel(jasperPrint, defaultFilename, request, response);
}
else if (PDF_TYPE.equals(type))
{
exportPdf(jasperPrint, defaultFilename, request, response);
}
else if (HTML_TYPE.equals(type))
{
exportHtml(jasperPrint, defaultFilename, request, response);
}
else if (WORD_TYPE.equals(type))
{
exportWord(jasperPrint, defaultFilename, request, response);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void export(String type, String defaultFilename, File is, HttpServletRequest request, HttpServletResponse response, Map parameters, JRDataSource conn)
{
try
{
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
prepareReport(jasperReport, type);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
if (EXCEL_TYPE.equals(type))
{
exportExcel(jasperPrint, defaultFilename, request, response);
}
else if (PDF_TYPE.equals(type))
{
exportPdf(jasperPrint, defaultFilename, request, response);
}
else if (HTML_TYPE.equals(type))
{
exportHtml(jasperPrint, defaultFilename, request, response);
}
else if (WORD_TYPE.equals(type))
{
exportWord(jasperPrint, defaultFilename, request, response);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void showHtml(String defaultFilename, String reportfile, HttpServletRequest request, HttpServletResponse response, Map parameters, JRDataSource conn) throws JRException, IOException
{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
JRAbstractExporter exporter = getJRExporter(DocType.HTML);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, parameters, conn);
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
PrintWriter out = response.getWriter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
//设置图片文件存放路径,此路径为服务器上的绝对路径
String imageDIR = request.getSession().getServletContext().getRealPath("/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);
//设置图片请求URI
String imageURI = request.getContextPath() + "/";
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);
//设置导出图片到图片存放路径
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.exportReport();
out.flush();
}
public static void showHtml(String defaultFilename, String reportfile, HttpServletRequest request, HttpServletResponse response, Map parameters, Connection conn) throws JRException, IOException
{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
JRAbstractExporter exporter = getJRExporter(DocType.HTML);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, parameters, conn);
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
PrintWriter out = response.getWriter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
//设置图片文件存放路径,此路径为服务器上的绝对路径
String imageDIR = request.getSession().getServletContext().getRealPath("/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);
//设置图片请求URI
String imageURI = request.getContextPath() + "/";
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);
//设置导出图片到图片存放路径
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.exportReport();
out.flush();
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static void showPdf(String defaultFilename, String reportfile, HttpServletRequest request, HttpServletResponse response, Map parameters, JRDataSource conn) throws JRException, IOException
{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
response.setContentType("application/pdf");
JRAbstractExporter exporter = getJRExporter(DocType.PDF);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, parameters, conn);
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
OutputStream out = response.getOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.exportReport();
out.flush();
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static void showPdf(String defaultFilename, String reportfile, HttpServletRequest request, HttpServletResponse response, Map parameters, Connection conn) throws JRException, IOException
{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
response.setContentType("application/pdf");
JRAbstractExporter exporter = getJRExporter(DocType.PDF);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, parameters, conn);
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
OutputStream out = response.getOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.exportReport();
out.flush();
}
}
六 controller层`
List<NdEntity> listData = NdService.getBmAf10List(id);
JRDataSource jrDataSource = new JRBeanCollectionDataSource(listData);
//构建参数map
Map<String, Object> map=new HashMap<String, Object>();
map.put("query", "其他参数测试");
//子数据源测试
map.put("chart1", listData);
//指定模板文件
// ServletContext context = request.getSession().getServletContext();
File reportFile = null;
reportFile = new File("E:\\yccj-land-si\\back\\land-si-module-system\\src\\main\\resources\\jaspers\\NdTeplate.jasper");
//调用工具类
JasperHelper.showPdf(exportFilePath, reportFile.getPath(), request, response, map,jrDataSource);
前端:vue
下载pdf.js资源包导入到前端public下的static目录下
下载地址http://mozilla.github.io/pdf.js/getting_started/#download
提供百度云网址 https://pan.baidu.com/s/1FfxagdtbJIdO5ZsZwv1rSw
下载后
前端vue部分代码
preview(params)
{
var data={
aaz042:params.aaz042
}
this.getpdf(this.url.preview,data).then((res)=>
{
var binaryData = [];
binaryData.push(res);
let url=window.URL.createObjectURL(new Blob(binaryData, {type:"application/pdf"}));
window.open("/static/pdf/web/viewer.html?file="+encodeURIComponent(url));
});
},getpdf(url,data)
{
return axios({
url:url,
method:'get',
params:data,
responseType:'blob'
})
}
其他问题:若使用list作为数据源:.jrxml文件设置传参如下:代码中需要把listy源传入:
这里是你传入的参数 包含你的参数
右边子表需要传入你的源datasource expression 这个就是你的源
在子表中list 可以输出你的源并且你需要设置接收参数paremer 需要传入的参数需要同父表中的
父表接收:
这里的值是list 源对象中存在的值,写在detile 中就可以重复输出你需要的list对象了,如下:
这就是传入list; 网上有
代码如下:
SiIc12 siIc12 = new SiIc12();
siIc12.setAaz030(aaz030);
siIc12 = siIc12Service.get(siIc12);
siIc12.setGroupid(DictUtils.getDictLabels("groupid",siIc12.getGroupid(),"1"));
List<SiIc12> list= new ArrayList<SiIc12>();
list.add(siIc12);
//这里是list作为数据源在子表循环输出
SiIc15 siIc15 = new SiIc15();
siIc15.setAaz030(aaz030);
List<SiIc15> siIc15List = siIc15Service.findList(siIc15);
Resource classPathResource = new ClassPathResource("jaspers/75_02.jasper");
Map<String, Object> parameters = new HashMap<String, Object>();
JRDataSource jrDataSource = new JRBeanCollectionDataSource(list);
File file=classPathResource.getFile();
String s =file.getPath();
String y = s.substring(0,s.lastIndexOf("\\")+1);
// String y = "/data/app/land_si/userfiles/subreport";
//导出的文件名字
String exportFilePath="75_02";
parameters.put("SUBREPORT_DIR",y);
parameters.put("data", siIc15List);
parameters.put("title", "生活补贴支付通知单");
//合计金额
BigDecimal total = new BigDecimal("0.00");
parameters.put("total",total);
java.io.InputStream in =classPathResource.getInputStream();
JasperHelper.showPdf(exportFilePath,in,request,response,parameters,jrDataSource);
}
最后附带maven 下载后编译生成的
当项目中加载这个jasperreports-chart-themes-5.2.0.jar包时,会默认加载olap4j-0.9.7.309-JS-3.jar包,maven中央库中没有些包,只需下载些包,执行mvn install:install-file -Dfile=D:\olap4j-0.9.7.309-JS-3.jar -DgroupId=org.olap4j -DartifactId=olap4j -Dversion=0.9.7.309-JS-3 -Dpackaging=jar命令加载到本地库就行了
这里就解决了字体不变黑的问题;要想字体加粗需要使用SansSerif这个包并且注意包是否导入完全
csdn地址(可以意思2积分):
https://download.csdn.net/download/qq_44014971/13613170
百度云网盘地址:
https://pan.baidu.com/s/1sdqLhoc2khwNGO8rYtNlNA
更多推荐
所有评论(0)