wuhuacong

在Vue&Element前端项目中,使用FastReport + pdf.js生成并展示自定义报表

在我的《FastReport报表随笔》介绍过各种FastReport的报表设计和使用,FastReport报表可以弹性的独立设计格式,并可以在Asp.net网站上、Winform端上使用,由于其主要是使用.net后端生成的报表方式,如果不考虑其在线设计处理,那么可以在在Vue&Element前端项目中使用,通过后端生成报表PDF文件,然后通过前端使用pdf.js来呈现报表最终效果即可。

1、使用FastReport生成自定义报表

我们通过定义自己FastReport报表格式,然后在后端生成PDF文件存储在指定目录中,并返回路径给前端,前端就可以通过pdf.js进行预览了。

关于FastReport报表的设计,这里不再赘述,主要就是通过几个简单的案例展示生成的报表逻辑。

 

 

 

 

 我们来看看其中的报表生成代码,主要分为几个步骤:初始化报表、准备数据、运行并导出报表。

 

其中从初始化报表如下代码所示。

    #region 初始化报表
    //报表文件路径
    string reportPath = "/Report/Pres.frx";
    //转换为物理路径
    reportPath = System.Web.Hosting.HostingEnvironment.MapPath(reportPath);

    //导出PDF/jpg的文件路径
    string exportPdfPath = $"/GenerateFiles/Pres/Report_{id}" + (pdf ? ".pdf":".jpg");

    //转换为物理路径
    string realPath = System.Web.Hosting.HostingEnvironment.MapPath(exportPdfPath);
    //确保目录生成
    string parentPath = Directory.GetParent(realPath).FullName;
    DirectoryUtil.AssertDirExist(parentPath);

    //生成PDF报表文档到具体文件
    Report report = new Report();
    report.Load(reportPath);

    #endregion

而初始化报表后,就需要准备相应的参数和数据等信息了,下面是测试数据代替

    dict.Add("Name", "张三");
    dict.Add("Gender", "");
    dict.Add("Age", 32);
    dict.Add("Telephone", "18620292076");
    dict.Add("CreateTime", "2019-10-13 22:30:15");
    dict.Add("CheckDoctor", "张医生");
    dict.Add("CheckPharmacist", "李药师");
    dict.Add("SendUser", "王小姐");
    dict.Add("QrCode", "http:www.iqidi.com");
    dict.Add("BarCode", "1234567890");

    for (int i = 0; i < 5; i++)
    {
        var dr = dt.NewRow();
        dr["ProductName"] = "阿莫西林" + i;
        dr["Quantity"] = i;
        dr["Unit"] = "";
        dr["Specification"] = "一盒24粒" + i;
        dr["HowTo"] = "口服";
        dr["Frequency"] = "一次三次,一次一片";
        dt.Rows.Add(dr);
    } 

准备好数据后,更新相关参数和数据源即可。

    //刷新数据源
    report.RegisterData(dt, "Detail");
    foreach (string key in dict.Keys)
    {
        report.SetParameterValue(key, dict[key]);
    }

然后我们根据是否PDF格式(否则为图片格式)的标志生成文件,如下所示。

    #region 运行并导出报表

    report.Prepare();                   
    if(pdf)
    { 
        //导出PDF报表
        var export = new PDFExport();
        report.Export(export, realPath);
    }
    else
    {
        //导出JPG报表
        var export = new ImageExport();
        //export.JpegQuality = 392;
        //export.ResolutionY = 226;
        report.Export(export, realPath);
    }
    report.Dispose();

    #endregion

最后返回路径给前端即可。

 

 

2、前端调用pdf.js插件生成并展示自定义报表

后端生成PDF文件后,返回路径给前端,由于是PDF文件,我们可以利用 pdf.js生成并展示自定义报表文件。

首先在前端的API调用类中构建对应的调用函数,如下所示。

 

 然后在页面中增加对应的处理方式即可。

 

 页面中通过按钮的触发调用这个函数,就可以呈现对应的PDF预览窗口了。

 

 

相关文章: