学习018-01-12-12 How to: Print a Report Without Displaying a Preview(如何:不显示预览直接打印报表)

How to: Print a Report Without Displaying a Preview(如何:不显示预览直接打印报表)

This topic describes how to implement the PrintContacts Action, which prints the “Contacts Report” report without displaying its preview. Note that this Action is not designed for reports with end-user-specified parameters (reports that use ReportParametersObjectBase parameters or native XtraReport parameters).
本主题介绍如何实现“打印联系人”操作,该操作可在不显示预览的情况下打印“联系人报告”报表。请注意,此操作并非为具有最终用户指定参数的报表(使用ReportParametersObjectBase参数或原生XtraReport参数的报表)而设计。

You can also use the code from this example to access an XtraReport object and then export or email the report content as illustrated in the tutorials listed in the Exporting Reports document.
你还可以使用此示例中的代码来访问XtraReport对象,然后按照“导出报表”文档中列出的教程所述,导出报表内容或将其通过电子邮件发送。

We recommend that you review the following XtraReports help topics and examples before you proceed:
我们建议您在继续操作之前查看以下 XtraReports 帮助主题和示例:

  • Printing a Report(打印一份报告)
  • Printing and Export in Reporting Tools for Web(Web报表工具中的打印与导出)
  • How to print a report without displaying it in a web application(如何在不将报告显示在Web应用程序中的情况下打印报告)

Tip
A complete sample project is available in the DevExpress Code Examples database at https://supportcenter.devexpress.com/ticket/details/e5146/xaf-how-to-print-a-report-without-displaying-a-preview.

在 DevExpress 代码示例数据库中,可通过以下链接获取完整的示例项目:https://supportcenter.devexpress.com/ticket/details/e5146/xaf-how-to-print-a-report-without-displaying-a-preview 。

In this topic, it is assumed that you have an XAF application that uses the Reports V2 Module, and you have created one or more reports (see Reports V2 Module Overview).
在本主题中,假设您有一个使用报表V2模块的XAF应用程序,并且您已经创建了一个或多个报表(请参阅报表V2模块概述)。

Create the PrintContacts Action in an Abstract Platform-Agnostic Controller(在抽象的跨平台控制器中创建“打印联系人”操作)

In the application’s main module project, implement the following abstract Controller class.
在应用程序的主模块项目中,实现以下抽象控制器类。

File: MySolution.Module/Controllers/PrintContactsController.cs

C# 
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
using MySolution.Module.BusinessObjects;
// ...
public abstract class PrintContactsController : ObjectViewController<ListView, Contact> {
    public PrintContactsController() {
        SimpleAction printAction = new SimpleAction(this, "PrintContacts", PredefinedCategory.Reports);
        printAction.ImageName = "Action_Printing_Print";
        printAction.Execute += delegate (object sender, SimpleActionExecuteEventArgs e) {
            PrintReport("ContactReport", e.SelectedObjects);
        };
        }
    protected abstract void PrintReport(string reportDisplayName, System.Collections.IList selectedObjects);
}

As you can see, the PrintContactsController targets Contact objects, so it will be activated when a user selects Contact in the navigation. The Controller introduces the PrintContacts SimpleAction. The abstract PrintReport method is called when the Action is executed (see SimpleAction.Execute). This method takes two parameters:
如你所见,PrintContactsController 以 Contact 对象为目标,因此当用户在导航中选择 Contact 时,它将被激活。该控制器引入了 PrintContacts SimpleAction。当执行该操作时,将调用抽象的 PrintReport 方法(请参阅 SimpleAction.Execute)。此方法接受两个参数:

reportDisplayName
The display name of a report to print. Implementations will use this value to find the specified report in the report storage.

要打印的报告的显示名称。实现将使用此值在报告存储中查找指定的报告。

selectedObjects
The list of objects selected in the List View. Implementations will use this information to filter printed reports.

在列表视图中选择的对象列表。实现方式将使用此信息来筛选打印报告。

The next two sections explain how to implement the PrintReport method in WinForms and ASP.NET Core Blazor projects.
接下来的两个部分将解释如何在WinForms和ASP.NET Core Blazor项目中实现PrintReport方法。

Implement Report Printing for WinForms(为WinForms实现报表打印功能)

In the WinForms module project, inherit the PrintContactsController. If your solution does not contain this project, add the Controller to the WinForms application project. In the Controller, implement the PrintReport method in the following manner:
在Windows窗体模块项目中,继承PrintContactsController。如果您的解决方案中不包含此项目,请将该控制器添加到Windows窗体应用程序项目中。在控制器中,按以下方式实现PrintReport方法:

File: MySolution.Win/Controllers/WinInstantPrintReportController.cs

C# 
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.ReportsV2;
using DevExpress.Persistent.BaseImpl.EF;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.XtraReports.UI;
using InstantPrintReportsV2Example.Module.Controllers;
using Microsoft.Extensions.DependencyInjection;
// ...
public class WinInstantPrintReportController : PrintContactsController {
    readonly IReportExportService reportExportService;
    public WinInstantPrintReportController() : base() { }




    [ActivatorUtilitiesConstructor]
    public WinInstantPrintReportController(IServiceProvider serviceProvider) : base() {
        reportExportService = serviceProvider.GetRequiredService<IReportExportService>();
    }




    protected override void PrintReport(string reportDisplayName, System.Collections.IList selectedObjects) {
        using XtraReport report = reportExportService.LoadReport<ReportDataV2>(r => r.DisplayName == reportDisplayName);
        // Filter and sort report data.
        CriteriaOperator objectsCriteria = ((BaseObjectSpace)ObjectSpace).GetObjectsCriteria(((ObjectView)View).ObjectTypeInfo, selectedObjects);
        SortProperty[] sortProperties = { new SortProperty("Age", SortingDirection.Descending) };
        reportExportService.SetupReport(report, objectsCriteria.ToString(), sortProperties);
        report.PrintDialog();
    }
}

The Controller implementation injects the IReportExportService. The following API available through this service is used:
控制器实现注入了IReportExportService。通过此服务可使用以下API:

IReportExportService.LoadReport
Searches for a report in the report storage based on the specified criteria and loads the found report’s data from the storage.

根据指定条件在报告存储中搜索报告,并从存储中加载找到的报告数据。

IReportExportService.SetupReport
Initializes the specified report. The above code sample uses an overload of this method that also filters and sorts report data.

初始化指定的报告。上述代码示例使用了此方法的一个重载,该重载还会对报告数据进行筛选和排序。

The XtraReport’s PrintDialog extension method is then called to invoke a print dialog. An end user can specify a printer and other print options before the document is printed.
然后调用XtraReport的PrintDialog扩展方法来调用打印对话框。在打印文档之前,最终用户可以指定打印机和其他打印选项。

Important
Ensure that the DevExpress.XtraPrinting.v24.1.dll assembly is referenced. The PrintDialog extension method is implemented in this assembly.

确保已引用DevExpress.XtraPrinting.v24.1.dll程序集。PrintDialog扩展方法在此程序集中实现。

The result is demonstrated in the image below.
结果在下面的图片中展示。

在这里插入图片描述

Implement Report Printing for ASP.NET Core Blazor (Export a Report to a PDF File)(在ASP.NET Core Blazor中实现报表打印(将报表导出为PDF文件))

In the ASP.NET Core Blazor project, add the following JavaScript code to Pages/_Host.cshtm:
在ASP.NET Core Blazor项目中,将以下JavaScript代码添加到Pages/_Host.cshtml中:

File: MySolution.Blazor.Server/Pages/_Host.cshtml

Razor
<!DOCTYPE html>
<html lang="en">
...
<body>
    ...
    <script>
        window.downloadFileFromStream = async (fileName, contentStreamReference) => {
            const arrayBuffer = await contentStreamReference.arrayBuffer();
            const blob = new Blob([arrayBuffer]);
            const url = URL.createObjectURL(blob);
            const anchorElement = document.createElement('a');
            anchorElement.href = url;
            anchorElement.download = fileName ?? '';
            anchorElement.click();
            anchorElement.remove();
            URL.revokeObjectURL(url);
        }
    </script>
</body>

The downloadFileFromStream function forces a user’s browser to download an exported report file from the specified stream.
downloadFileFromStream函数会强制用户的浏览器从指定的流中下载导出的报告文件。

Inherit the PrintContactsController. In the Controller, implement the PrintReport method in the following manner:
继承PrintContactsController。在控制器中,按以下方式实现PrintReport方法:

File: MySolution.Blazor.Server/Controllers/BlazorPrintContactsController.cs

C# 
using DevExpress.Data.Filtering;
using DevExpress.Data.Helpers;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.ReportsV2;
using DevExpress.Persistent.BaseImpl.EF;
using DevExpress.Xpo;
using DevExpress.XtraReports.UI;
using InstantPrintReportsV2Example.Module.Controllers;
using Microsoft.JSInterop;
using DevExpress.Xpo.DB;
using DevExpress.ReportServer.ServiceModel.DataContracts;
using Microsoft.Extensions.DependencyInjection;
// ...
public class BlazorPrintContactsController : PrintContactsController {
    readonly IReportExportService reportExportService;
    readonly IJSRuntime jsRuntime;
    public BlazorPrintContactsController() : base() { }




    [ActivatorUtilitiesConstructor]
    public BlazorPrintContactsController(IServiceProvider serviceProvider) : base() {
        reportExportService = serviceProvider.GetRequiredService<IReportExportService>();
        jsRuntime = serviceProvider.GetRequiredService<IJSRuntime>();
    }




    protected override async void PrintReport(string reportDisplayName, System.Collections.IList selectedObjects) {
        using XtraReport report = reportExportService.LoadReport<ReportDataV2>(r => r.DisplayName == reportDisplayName);
        // Filter and sort report data
        CriteriaOperator objectsCriteria = ((BaseObjectSpace)ObjectSpace).GetObjectsCriteria(((ObjectView)View).ObjectTypeInfo, selectedObjects);
        SortProperty[] sortProperties = { new SortProperty("Age", SortingDirection.Descending) };
        reportExportService.SetupReport(report, objectsCriteria.ToString(), sortProperties);




        using Stream s = reportExportService.ExportReport(report, DevExpress.XtraPrinting.ExportTarget.Pdf);
        using var streamRef = new DotNetStreamReference(s);
        var fileName = reportDisplayName + ".pdf";
        await jsRuntime.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
    }
}

The controller’s PrintReport method implementation injects the IReportExportService and uses the same API of this service as the WinForms controller implementation with the addition of the following method:
控制器的PrintReport方法实现注入了IReportExportService,并且使用了与WinForms控制器实现相同的该服务API,另外还增加了以下方法:

IReportExportService.ExportReport
Exports the specified report to the specified format and returns a Stream that can be used to read the exported report data.
将指定的报告导出为指定格式,并返回一个流,可用于读取导出的报告数据。

A reference to the stream returned by the ExportReport method is passed to the downloadFileFromStream JavaScript function to force the browser to download an exported .pdf file from this stream.
将ExportReport方法返回的流的引用传递给downloadFileFromStream JavaScript函数,以强制浏览器从此流下载导出的.pdf文件。

The result is demonstrated in the image below.
结果如下图所示。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汤姆•猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值