在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預覽窗口了。