四、输出
定义完JFreeReport对象,就可以进行输出了。下面介绍几种输出方法。
1、通过预览窗口对象输出
该方式只能在Application环境中使用。通过预览窗口,用户可以自行选择打印、排版或生成各种格式的文件,这也是我们在Application中常用的方式。代码示例如下:
PreviewDialog preview = null; //预览窗口对象
try ...{
// 将生成的报表放到预览窗口中
preview = new PreviewDialog(report);
} catch (ReportProcessingException e) ...{
e.printStackTrace();
}
if (preview != null) ...{
preview.pack();
preview.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// 设置报表起始点及长宽
preview.setLocation(new Point(0, 0));
Dimension screen = getToolkit().getScreenSize();
int width = (int) (screen.getWidth() - 2 * preview.getLocation().x);
int height = (int) (screen.getHeight());
preview.setSize(new Dimension(width, height));
// 显示报表预览窗口
preview.setVisible(true);
preview.requestFocus();
// preview.addWindowListener(new CloseHandler());
}
2、输出HTML文本。
这种方法可以将报表输出为HTML语言形成的文本,这种方式适用于在浏览器中显示报表内容。示例代码如下:
ByteArrayOutputStream bo = null;
StreamHtmlFilesystem filesystem = null;
try ...{
// 生成Html
bo = new ByteArrayOutputStream();
final HtmlProcessor processor = new HtmlProcessor(report);
processor.setGenerateBodyFragment(true);
processor.setEncoding ("UTF-8");
filesystem = new StreamHtmlFilesystem(bo);
processor.setFilesystem(filesystem);
processor.processReport();
String htmlCode = new String(bo.toByteArray(), "UTF-8");
bo.close();
bo = null;
filesystem.close();
filesystem = null;
} catch(FileNotFoundException e) ...{
e.printStackTrace();
} catch(SecurityException e) ...{
e.printStackTrace();
} catch (ReportProcessingException e) ...{
e.printStackTrace();
} catch (IOException e) ...{
e.printStackTrace();
}
3、输出PDF文件
PDF的输出方式跟HTML的差不多,但有一点,JFreeReport本身无法输出中文字符,如果想要输出中文,我没有找到更好的方法,所以更改了JFreeReport包中org.jfree.report.modules.output.support.itext.BaseFontSupport类的源码,将
final BaseFont f = BaseFont.createFont(BaseFont.HELVETICA, stringEncoding, embedded,
false, null, null)中的BaseFont.HELVETICA改为“STSong-Light”,另外需要到www.lowagie.com/iText网站下载iText.jar包以支持STSong-Light字体编码,这样,就可以输出中文了。示例代码如下所示:
这里注意,必须将target的字体编码设为“UniGB-UCS2-H”而且使用Java1.5进行编译
PDFOutputTarget target = null;
try ...{
//生成pdf
FileOutputStream fos = new FileOutputStream("PDF.pdf");
target = new PDFOutputTarget(fos);
target.configure(report.getReportConfiguration());
target.setFontEncoding("UniGB-UCS2-H");
target.open();
final PageableReportProcessor proc = new PageableReportProcessor(report);
proc.setOutputTarget(target);
proc.processReport();
target.close();
target = null;
} catch(FileNotFoundException e) ...{
e.printStackTrace();
} catch(SecurityException e) ...{
e.printStackTrace();
} catch (OutputTargetException e) ...{
e.printStackTrace();
} catch (ReportProcessingException e) ...{
e.printStackTrace();
}