net.sf.jasperreports.engine.JasperExportManager.exportReportToPdfStream(InputStream arg0, OutputStream arg1) 能够实现导出pdf到输出流,但是因为JasperExportManager的exportReportToPdfStream没有设计字体,导致有时候实现不了粗体的功能。
查看JasperExportManager.exportReportToPdfStream的源码就明白了:
public static void exportReportToPdfStream(JasperPrint jasperPrint, OutputStream outputStream)
throws JRException
{
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();
}
因此我们可以自己写一段代码代替JasperExportManager.exportReportToPdfStream,如下
JRPdfExporter exporter = new JRPdfExporter();
Map fontsMap = new HashMap();
fontsMap.put(new FontKey("宋体", true, false), new PdfFont("STSong-Light", "UniGB-UCS2-H", true, true, false));
exporter.setParameter(JRExporterParameter.FONT_MAP, fontsMap);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.exportReport();
整个实现页面嵌套pdf预览的代码如下:
Map ireportMap = new HashMap();
ireportMap.put("clientNo", "D000000925");
ireportMap.put("clientName", "测试客户");
ireportMap.put("barCode", "CS0100000002333");
ireportMap.put("barCodeStr", "C S 0 1 0 0 0 0 0 0 0 2 3 3 3");
ireportMap.put("ImagePath", request.getRealPath("images/logo_print.jpg"));
ClassLoader classLoader = RiskConfirmController.class.getClassLoader();
OutputStream out = null;
try {
out = response.getOutputStream(); // 获取页面输出流
response.setContentType("application/pdf; charset=utf-8"); // 设置页面类型及编码
response.setDateHeader("Expires", 0); // 清除页面缓存
//risk_controler_confirm.jasper riskcontrolerconfirm
response.setHeader("Content-Disposition", "inline;filename="+ URLEncoder.encode("risk_controler_confirm.pdf", "utf-8")); // 设置文件名
JasperPrint jPrint = JasperFillManager.fillReport(classLoader.getResourceAsStream("risk_controler_confirm.jasper"),ireportMap, new JREmptyDataSource()); // 模板填充数据
JRDesignReportFont jrfont = new JRDesignReportFont();
//JasperExportManager.exportReportToPdfStream(jPrint, out); // 生成PDF输出流
JRPdfExporter exporter = new JRPdfExporter();
Map fontsMap = new HashMap();
fontsMap.put(new FontKey("宋体", true, false), new PdfFont("STSong-Light", "UniGB-UCS2-H", true, true, false));
exporter.setParameter(JRExporterParameter.FONT_MAP, fontsMap);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.exportReport();
if (out != null){
out.flush();
}