Home  >  Article  >  Web Front-end  >  A brief discussion on how to use Grid++ reports in Bootstrap

A brief discussion on how to use Grid++ reports in Bootstrap

青灯夜游
青灯夜游forward
2021-06-15 11:23:123481browse

This article will introduce to you how to use Grid report in Bootstrap. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on how to use Grid++ reports in Bootstrap

This essay introduces the use of Grid reports in the Bootstrap development framework, that is, the use of Grid reports in the Web environment. For the QR code barcode assets I mentioned in the previous article The information table is presented by our system through the Web, or the PDF of the report can also be displayed. This essay will introduce step by step how to display the Web report.

1. Grid report processing on the Web side

Grid provides plug-in display on the Web side. However, since the plug-in is processed in COM, this The mode is limited by the browsers it supports.

Through the above table, it means that basically the latest versions of Chrome and FireFox, which are widely used by us, are not supported. Due to my project needs, I hope that customers can If the report is displayed on a browser, this plug-in display method is not suitable.

[Related recommendation: "bootstrap tutorial"]

However, the Grid report still provides another way, which is the HTML5 way of display. The HTML5 report runs on all Browsers that support HTML5 (currently newer versions of various browsers support HTML5).

For example, when displaying an HTML report in the Chrome browser, the effect is as follows.

This method is quite good, but when I was printing the QR code, I found that it was different from the report I designed. The report style effect I designed As follows.

The effect of the HTML report to me is as follows.

That is to say, it cannot be displayed in the arrangement I need, so I hope to generate a PDF format display on the server side, because the effect of PDF is still the best, and it will not Transformation, and I can achieve the online preview effect through the PDFJS plug-in. When needed, just download the PDF print content.

2. The implementation process of Grid report on the Web side

I have introduced the report effect and specific selection process I need before. Before getting the final result, let’s Let’s take a look at the specific implementation results step by step.

For some simple two-dimensional tables, it would be great to use direct report presentation. Let’s first introduce the implementation process of direct presentation through HTML reports.

Since my Bootstrap development framework is developed using MVC, I want to place the display of the report in the Report.cshtml view, then I need to create a view Action, as shown below.

        public ActionResult Report()
        {
            return View("Report");
        }

In this way, we create another Report.cshtml view page, as shown below. First introduce the JS we need. Generally speaking, just import the grhtml5-6.6-min.js file. Since we need to use some processing methods of Jquery, JQueryJS also needs to be introduced.

@*此处添加一些Jquery相关的脚本,方便开发时刻自定义脚本的智能提示*@
    <script src="~/Content/metronic/assets/global/plugins/jquery.min.js" type="text/javascript"></script>
    <script src="~/Content/metronic/assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script>
    <script src="~/Content/metronic/assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>

    <!--Grid++报表需要的JS文件-->
    <script src="~/Content/JQueryTools/GridReport/grhtml5-6.6-min.js"></script>

In this way, we can call the report object to process the data. For example, below we test the report content processing of a case.

<script language="javascript" type="text/javascript">
        function loadReport() {

            rubylong.grhtml5.barcodeURL = "/Barcode.ashx";
            //创建报表显示器,参数指定其在网页中的占位标签的ID,报表模板URL与报表数据URL不指定,而是在后面的AJAX操作中提供相关数据
            var reportViewer = window.rubylong.grhtml5.insertReportViewer("report_holder");
            reportViewer.reportPrepared = false; //指定报表生成需要加载报表模板
            reportViewer.dataPrepared = false;   //指定报表生成需要加载报表数据

            //报表在模板与数据都载入后会自动生成

            //测试报表
            $.ajax({
                type: "GET",
                url: "/Report/1a.SimpleList.grf",
                data: "",
                success: function (msg) {
                    reportViewer.loadReport(msg);
                }
            });
            $.ajax({
                type: "GET",
                //url: "/Report/xmlCustomer.txt", //xml格式
                url: "/Report/jsonCustomer.txt",//json格式
                data: "",
                success: function (msg) {
                    reportViewer.loadData(msg);
                }
            });

        //页面初始化
        $(function () {
            loadReport();
        });
    </script>

The report content is presented in HTML elements, as shown in the following code.

<body>
    <div id="report_holder">
    </div>
</body>

Through the above, we learned about the assignment processing of its report content. We first need to determine the report template file and dynamically generate the data presented in the report to replace the content of the jsonCustomer.txt file.

Let’s take a look at the format of this file as follows.

#That is, if we need to dynamically generate data, we can construct this JSON format output. The effect of the test report interface is as follows, and the two-dimensional table display effect is still very good.

#During the actual report processing, since I need to dynamically display the data, I just need to receive a parameter in JS and dynamically construct the data based on the parameter.

The following is my actual project report data display.

function loadReport(ids) {

            rubylong.grhtml5.barcodeURL = "/Barcode.ashx";
            //创建报表显示器,参数指定其在网页中的占位标签的ID,报表模板URL与报表数据URL不指定,而是在后面的AJAX操作中提供相关数据
            var reportViewer = window.rubylong.grhtml5.insertReportViewer("report_holder");
            reportViewer.reportPrepared = false; //指定报表生成需要加载报表模板
            reportViewer.dataPrepared = false;   //指定报表生成需要加载报表数据

            //报表在模板与数据都载入后会自动生成
            //正式报表
            $.ajax({
                type: "GET",
                url: "/Report/barcode.grf",
                data: "",
                success: function (msg) {
                    reportViewer.loadReport(msg);
                }
            });
            $.ajax({
                type: "GET",
                //url: "/Report/jsonbarcode.txt", //json文件格式
                url: "/Asset/GetRepotData?ids=" + ids,//动态json格式
                data: "",
                success: function (msg) {
                    reportViewer.loadData(msg);
                }
            });
        };

I achieve dynamic generation of data through the Asset/GetRepotData method.

/// <summary>
        /// 获取Grid++的JSON格式报表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRepotData(string ids)
        {
            ActionResult result = Content("");
            if (!string.IsNullOrEmpty(ids))
            {
                var list = BLLFactory<Asset>.Instance.FindByIDs(ids);
                //构建一个合法格式的对象,进行序列号
                var table = new
                {
                    Table = list
                };
                result = ToJsonContent(table);
            }
            return result;
        }

In fact, it is to build a Table object of the top node and then serialize it into JSON.

In this way we can output the required report, as shown below.

However, this report is not arranged according to the two columns I need (it is probably a bug in the report), and it does not meet my expectations, so I hope to display the PDF way to achieve strict format output reports.

3、Grid++报表在Web端的PDF处理

报表控件,后台通过PDF的生成方式,如果在Winform下直接导出PDF方式,具体如下所示。

private void btnExportPdf_Click(object sender, EventArgs e)
        {
            List<ProductInfo> list = BLLFactory<Product>.Instance.GetAll();

            //从对应文件中载入报表模板数据
            string reportPath = Path.Combine(Application.StartupPath, "Reports\\testList.grf");
            GridExportHelper helper = new GridExportHelper(reportPath);

            string fileName = "d:\\my.pdf";
            var succeeded = helper.ExportPdf(list, fileName);
            if(succeeded)
            {
                Process.Start(fileName);
            }
        }

而其中辅助类的ExportPdf方法就是直接利用报表客户端控件对象导出PDF的,如下代码所示。

/// <summary>
        /// 导出PDF,并返回路径
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool ExportPdf<T>(List<T> list, string filePath)
        {
            //从对应文件中载入报表模板数据
            Report.LoadFromFile(this.ReportPath);
            Report.FetchRecord += () =>
            {
                FillRecordToReport<T>(Report, list);
            };
            Report.ExportBegin += (IGRExportOption option) =>
            {
                option.AbortOpenFile = true;  //导出后不用关联程序打开导出文件,如导出Excel文件之后不用Excel打开
                option.FileName = filePath;
                switch (option.ExportType)
                {
                    case GRExportType.gretPDF:
                        option.AsE2PDFOption.Author = "My Author";
                        option.AsE2PDFOption.Subject = "My Subject";
                        break;
                }
            };

            var succeeded = Report.ExportDirect(GRExportType.gretPDF, filePath, false, false);
            return succeeded;
        }

报表导出的效果和报表预览效果一致

不过我使用前面报表客户端的对象处理报表导出,在测试后台生成PDF的时候,提示内存损坏,应该就是COM处理的问题,不支持这样的方式,咨询作者后说需要使用 WEB报表服务器 方式来生成PDF。

改变一下处理过程,实际使用的是GridppReportServer对象来处理,实际代码如下所示。

/// <summary>
        /// 导出PDF
        /// </summary>
        /// <typeparam name="T">列表对象类型</typeparam>
        /// <param name="list">列表对象</param>
        /// <param name="filePath">存储路径</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool ExportPdf<T>(List<T> list, string filePath, HttpContextBase context)
        {
            //从对应文件中载入报表模板数据
            Report.LoadFromFile(this.ReportPath);

            //构建一个合法格式的对象,进行序列化
            var table = new
            {
                Table = list
            };
            var json = JsonConvert.SerializeObject(table, Formatting.Indented);
            Report.LoadDataFromXML(json);

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

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

有了这个辅助方法,我们就可以封装一下处理获得数据,并导出PDF文件的操作了

/// <summary>
        /// 根据选中的ID记录,生成对应的PDF报表,返回路径
        /// </summary>
        /// <param name="ids">选中的ID记录,逗号分开</param>
        /// <returns></returns>
        public ActionResult ExportPdf(string ids)
        {
            ActionResult result = Content("");
            if (!string.IsNullOrEmpty(ids))
            {
                //利用接口获取列表数据
                var list = BLLFactory<Asset>.Instance.FindByIDs(ids);
                //报表文件路径
                string reportPath ="/Report/barcode.grf";
                //转换为物理路径
                reportPath = Server.MapPath(reportPath);

                //导出PDF的文件路径
                string exportPdfPath = string.Format("/GenerateFiles/{0}/AssetReport.pdf", CurrentUser.Name);
                //转换为物理路径
                string realPath = Server.MapPath(exportPdfPath);
                //确保目录生成
                string parentPath = Directory.GetParent(realPath).FullName;
                DirectoryUtil.AssertDirExist(parentPath);

                //生成PDF报表文档到具体文件
                GridExportHelper helper = new GridExportHelper(reportPath);
                bool success = helper.ExportPdf(list, realPath, HttpContext);
                if(success)
                {
                    result = Content(exportPdfPath);//返回Web相对路径
                }
                helper.Dispose();//销毁对象
            }
            return result;
        }

这些是后端的代码,要想在前端里面处理并预览PDF文件,需要加入前端的HTML代码

如下我们加入两个JS函数

//查看明细信息
        function ViewPDF(ids) {
            $.ajax({
                type: "GET",
                url: "/Asset/ExportPdf?ids=" + ids,
                data: "",
                success: function (filePath) {
                    var baseUrl = "/Content/JQueryTools/pdfjs/web/viewer.html";
                    var url = baseUrl + "?file=" + filePath;//实际地址
                    window.open(url);
                }
            });
        };

        function AssetPrint() {
            var rows = $table.bootstrapTable(&#39;getSelections&#39;);
            if (rows.length == 0) {
                showTips("请选择你要打印编码的记录");
                return;
            }

            //使用Grid++报表,构建数据显示
            var ids = &#39;&#39;;
            for (var i = 0; i < rows.length; i++) {
                ids += rows[i].ID + &#39;,&#39;;
            }
            ids = ids.substring(0, ids.length - 1);

            //loadReport(ids);
            ViewPDF(ids);
        }

这里利用了PDFJS的插件来在线展示生成的PDF,需要了解具体可以参考我之前的随笔《实现在线预览PDF的几种解决方案》

然后在HTML页面里面加入对应的处理按钮即可。

<button type="button" onclick="AssetPrint()" class="btn btn-circle btn-sm red">
    <i class="fa fa-plus"></i>
    资产编码打印
</button>

如下页面的界面效果所示

单击【资产编码打印】,首先在后台动态生成一个PDF文件,成功后前端弹出一个新的预览PDF界面,预览我们的二维码报表,效果比HTML5界面效果标准,和我们原来的设计报表初衷一直,两列排列。

 以上就是我在实际项目中,在Bootstrap开发框架中使用Grid++报表的几个处理过程,希望对你使用有帮助,报表确实具有很好的应用场景,使用起来还是很方便的。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of A brief discussion on how to use Grid++ reports in Bootstrap. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete