.NET WinForms ReportViewer:不可打印的报表背景(元素)






4.92/5 (6投票s)
如何:使 Microsoft .NET 报表 (.rdlc) 的背景(元素)不可打印
引言
我曾经遇到过一个任务 - 创建一个带有背景的报表,该背景将不会被打印。 在互联网上长时间且徒劳地搜索答案后,我开始自己解决这个问题 - 并想分享我的解决方案。
背景
主要思想是 .NET ReportViewer
使用相同的“机制”(渲染)来生成报表(预览)和打印报表(我想,也用于生成任何导出文件)。 而且没有属性可以定义元素**何时**应该可见。 但是你可以使用表达式来设置一些属性 - Hidden
或 BackgroundImage.Source
,在我的例子中,使用报表参数。 因此,如果你知道下一个渲染将执行的原因 - 你可以将一些参数设置为确定元素可见性的值,并且报表将以你想要的方式渲染。
Using the Code
我将仅描述我的情况 - 在打印时隐藏页面背景,但你可以以相同的方式在其他情况下显示|隐藏报表元素。
首先,我将图像和参数添加到我的报表中并使报表主体背景表达式如下
=IIf(Parameters!HideBg.Value=True, "", "ReportBackground")
其次,我将两个事件处理程序添加到 ReportViewer
并在代码中
private void Form1_Load(object sender, EventArgs e)
{
this.rv.LocalReport.ReportEmbeddedResource = "RerportViewer.NonPrintableBg.Report1.rdlc";
this.rv.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter("HideBg", "False", true));
this.rv.RefreshReport();
}
private bool printing = false;
private void rv_PrintingBegin(object sender, Microsoft.Reporting.WinForms.ReportPrintEventArgs e)
{
this.rv.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter("HideBg", "True", true));
this.printing = true;
}
private void rv_RenderingComplete(object sender, Microsoft.Reporting.WinForms.RenderingCompleteEventArgs e)
{
if (this.printing == true)
{
this.printing = false;
this.rv.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter("HideBg", "False", true));
}
}
通过在调用渲染**之前**设置参数,你可以管理报表的渲染方式。 由于 ReportViewer
在每个按钮按下时(以及导出时)都有事件,你可以定义一些变量并在事件处理程序中设置它们,并在渲染完成后重置以恢复默认(可见)报表状态。
所以,你可以看到这个应用程序
以及打印的报表
它的工作方式**完全**符合我的预期。