Using FastReport report report tool to generate Report PDF document

Posted by pikebro2002 on Thu, 17 Oct 2019 05:42:28 +0200

When we develop a system, customers always put forward some specific report requirements. The fixed report format meets their business processing needs and also fits their work scenarios. Therefore, we try to make reports that meet their actual needs, so our system will get a better sense of identity. This essay introduces how to generate Report PDF document based on FastReport report tool to show the content of hospital prescription note.

Before in the essay< Using FastReport to create report in Winform development >This paper introduces FastReport, a powerful report tool. Although it introduces the processing codes of various reports, the main case is still the official case. This essay introduces the processing of the format report based on the prescription paper of a hospital.

FastReport.Net is a full-featured report analysis solution for Windows Forms, ASP.NET and MVC framework. FastReport.Net is written in C and contains only managed code. It is compatible with. NET Framework 2.0 and later. It supports adding text, image, line, shape, statement, barcode, matrix, table, RTF, selection box, etc. to the report. List report, grouping report, master-slave report, multi column report and sub report can be processed. General can provide a report designer for end users, so that users can easily modify existing reports and create custom reports.

1. Define report template

Like other general report tools, FastReport.Net report tools also need to define report template files, and then present content based on this report template. Report template generally defines information such as title, report header, details and footer.

Let's take a look at the general demand effect. This is the regular format of prescription paper.

I need to get a similar format of prescription paper report, in which prescription drugs need to be generated dynamically, and patient information, where doctors need to review and sign, of course, QR code, barcode and other contents also need to be generated dynamically according to the information. Because I mainly want to display through PDF, I use the report tool to generate PDF documents, which have been previewed or downloaded. It can be carried.

Let's take a look at the final designed report template. The effect in FastReport designer is as follows.

Among them, the title part, mainly in the header, needs to show the prescription list in the data area, put some contact information in the footer, etc., so as to build a complete report template.

To create a report template, we first need to define the report page format, the width and height of the report, whether they are user-defined or standard, and also set its page margin and other information, as shown below.

Page margins are set as follows.

 

Because this report contains the information of the main table and the details, the dynamic information of our main table can be bound by parameter binding, and the details can be dynamically processed by binding the DataTable.

With parameter binding, we need to define the parameters we need in the report designer, as shown below.

We usually predefine the relevant parameters, bind them to the template, and set the format of the content.

As shown in the report page, we have placed a table. After defining the row, column and width of the table, double-click the table cell to set the text content of the table cell as the corresponding parameter, as shown in the following interface.

 

In order to display the sequence number of each item, we also need to use the system variables, such as the following.

Then you need to define the serial number of each item and the data field name.

For the detailed list part of dynamic display, we need to define a data source method so that the report template can bind the corresponding field name.

I generate a data source for binding the detailed list based on the information of the data table, as shown below.

In this way, when binding code, we only need to specify the name of Detail and the corresponding field name. With these definitions, we can use field binding in report design.

Drag the corresponding field definition in the data area, adjust the text size and bind it, then you can design the detailed part of the field binding.

For QR codes and barcodes, we can drag the corresponding controls from the report toolbar, and set the corresponding binding parameters and display content (these can also be dynamically bound when running through parameters).

The final designed report is a complete report template as introduced at the beginning.

 

When previewing, we can see that the content binding place is blank, because we have not bound the data source, but the format of the whole report has come out, which is probably the result we need.

 

2. Generate Report PDF content

Through the above report template design, our basic preliminary work is ready. What we need is to dynamically present data according to the actual business needs.

When binding data and generating PDF report, we need to build a report object first, as shown in the following code.

//generate PDF Report documents to specific documents
Report report = new Report();
report.Load(reportPath);

Since the data is built dynamically, we need to prepare two parts: parameter data source and field data source. We use dictionary to carry the parameters, and use DataTable to carry the field data, as shown below.

//Defining parameters and data formats
var dict = new Dictionary<string, object>();
var dt = DataTableHelper.CreateTable("ProductName,Quantity|int,Unit,Specification,HowTo,Frequency");

Then we fill in the dynamic data according to the system needs, as shown in the following code.

//Preparation data
dict.Add("Name", info.PatientName);
dict.Add("Gender", info.Gender);
var age = info.BirthDate.GetAge();
dict.Add("Age", age);
dict.Add("Telephone", info.Telephone);
dict.Add("CreateTime", info.CreateTime);

var checkDoctor = BLLFactory<User>.Instance.GetFullNameByOpenID(info.CheckDoctor);
dict.Add("CheckDoctor", !string.IsNullOrEmpty(checkDoctor) ? checkDoctor : "Unknown");

var CheckPharmacist = BLLFactory<User>.Instance.GetFullNameByOpenID(info.CheckPharmacist);
dict.Add("CheckPharmacist", !string.IsNullOrEmpty(CheckPharmacist) ? CheckPharmacist : "Unknown");

var SendUser = BLLFactory<User>.Instance.GetFullNameByOpenID(info.SendUser);
dict.Add("SendUser", !string.IsNullOrEmpty(SendUser) ? SendUser : "Unknown");

var qrcode = string.Format("{0}/h5/PrescriptionDetail?id={1}", ConfigData.WebsiteDomain, info.ID);
dict.Add("QrCode", qrcode);
dict.Add("BarCode", info.PrescriptionNo);

if(detailList != null)
{
    foreach(var item in detailList)
    {
        var dr = dt.NewRow();
        dr["ProductName"] = item.ProductName;
        dr["Quantity"] = item.Quantity;
        dr["Unit"] = item.Unit;
        dr["Specification"] = "";
        dr["HowTo"] = item.HowTo;
        dr["Frequency"] = item.Frequency;
        dt.Rows.Add(dr);
    }
}

Finally, according to the above data, bind and generate PDF report, as shown in the following code.

//Refresh data source
report.RegisterData(dt, "Detail");
foreach (string key in dict.Keys)
{
    report.SetParameterValue(key, dict[key]);
}

//Running Report
report.Prepare();

//export PDF Report form
PDFExport export = new PDFExport();
report.Export(export, realPath);
report.Dispose();

Because this function is a report presentation integrated in wechat public account, we can preview it by PDF or open it directly. ,

If PDF Online preview is adopted, please refer to my essay< Several solutions for online Preview PDF >As introduced, the online preview scheme of PDFJS is finally adopted, which has a good effect both on wechat and Web.

If PDFJS preview is used, the JS code is as follows.

    var baseUrl = "@ViewBag.WebsiteDomain/Content/JQueryTools/pdfjs/web/viewer.html";
    var url = baseUrl + "?file=" + filePath;//Actual address
    location.href = url;

If we open PDF directly, we will pass it directly to the browser with a PDF file path.

location.href = filePath

The preview effect on wechat is as follows.

Using FastReport report, generally speaking, the workload is mainly in the design of report template. The work of data binding through code is very simple. Only the corresponding parameters and field data table need to be specified. The design of report is a delicate work. We need to adjust the format and presentation effect repeatedly according to the actual situation to achieve perfection. No. As a whole, FastReport provides a very powerful report design and processing process, which enables us to design some complex reports more efficiently.

3. Other report design - sharp wave report design presentation

When using FastReport report for presentation, I have also tried the processing method of sharp wave report. The overall presentation effect of sharp wave report is also very good. By the way, this paper introduces the design of sharp wave report, the step code of binding data source at runtime, etc. for reference.

First of all, we need to define the template information of a report, which is similar to FastReport report template. The report template design is as follows.

 

As we can see above, it also has two ways: parameter binding and field binding.

The code to implement the data binding is shown below.

//generate PDF Report documents to specific documents
GridExportHelper helper = new GridExportHelper(reportPath);
var json = FileUtil.FileToString(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Report/Pres.json"), Encoding.UTF8);
bool success = helper.ExportPdf(json, realPath, HttpContext);
if (success)
{
    result = Content(exportPdfPath);//Return Web Relative path
}
helper.Dispose();//Destroy objects

Where ExportPdf receives a JSON string, the implementation code is as follows.

        /// <summary>
        /// export PDF
        /// </summary>
        /// <typeparam name="T">List object type</typeparam>
        /// <param name="list">List object</param>
        /// <param name="filePath">Storage path</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool ExportPdf(string json, string filePath, HttpContextBase context)
        {
            //Load report template data from corresponding file
            Report.LoadFromFile(this.ReportPath);

            //Load JSON object
            Report.LoadDataFromXML(json);

            IGRExportOption ExportOption = Report.PrepareExport(GRExportType.gretPDF);
            var exportPdf = Report.ExportToBinaryObject();
            Report.UnprepareExport();

            var succeeded = exportPdf.SaveToFile(filePath);
            return succeeded;
        }

The general effect of the final presentation is as follows.

Topics: C# JSON QRCode Windows encoding