65.9K
CodeProject 正在变化。 阅读更多。
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (6投票s)

2014 年 3 月 14 日

CPOL

1分钟阅读

viewsIcon

18640

downloadIcon

374

如何:使 Microsoft .NET 报表 (.rdlc) 的背景(元素)不可打印

引言

我曾经遇到过一个任务 - 创建一个带有背景的报表,该背景将不会被打印。 在互联网上长时间且徒劳地搜索答案后,我开始自己解决这个问题 - 并想分享我的解决方案。

背景

主要思想是 .NET ReportViewer 使用相同的“机制”(渲染)来生成报表(预览)和打印报表(我想,也用于生成任何导出文件)。 而且没有属性可以定义元素**何时**应该可见。 但是你可以使用表达式来设置一些属性 - HiddenBackgroundImage.Source,在我的例子中,使用报表参数。 因此,如果你知道下一个渲染将执行的原因 - 你可以将一些参数设置为确定元素可见性的值,并且报表将以你想要的方式渲染。

Using the Code

我将仅描述我的情况 - 在打印时隐藏页面背景,但你可以以相同的方式在其他情况下显示|隐藏报表元素。

首先,我将图像和参数添加到我的报表中

add parameter

add background image

并使报表主体背景表达式如下

=IIf(Parameters!HideBg.Value=True, "", "ReportBackground")

set expression

set expression

其次,我将两个事件处理程序添加到 ReportViewer

event handlers

并在代码中

        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 在每个按钮按下时(以及导出时)都有事件,你可以定义一些变量并在事件处理程序中设置它们,并在渲染完成后重置以恢复默认(可见)报表状态。

所以,你可以看到这个应用程序

report in app

以及打印的报表

printed to Adobe Acrobat report

它的工作方式**完全**符合我的预期。

© . All rights reserved.