RDLC报表打印一维码

时间:2022-05-25 08:35:35

            首先添加BarcodeLib.dll引用,设置图像属性如图所示:

RDLC报表打印一维码

关键代码:

byte[] imgBytes = GetBarcode(200, 1000, TYPE.CODE128, dt.Rows[0]["inner_pkg_no"].ToString(), out image);

方法如下:

        private static byte[] GetBarcode(int height, int width, TYPE type, string code, out Image image)
        {
            image = null;
            Barcode b = new Barcode();
            b.BackColor = Color.White;
            b.ForeColor = Color.Black;
            b.IncludeLabel = false;
            b.Alignment = AlignmentPositions.CENTER;
            b.LabelPosition = LabelPositions.BOTTOMCENTER;
            b.ImageFormat = ImageFormat.Jpeg;
            Font font = new Font("verdana", 10f);
            b.LabelFont = font;

            b.Height = height;
            b.Width = width;
            image = b.Encode(type, code);
            byte[] buffer = b.GetImageData(SaveTypes.JPG);
            return buffer;
        }

重点:数据集字段必需声明为System.Byte[]类型,如果数据库已经存储该image对象则可直接设置该字段表达式值为:

=System.Convert.ToBase64String(Fields!imagePkgNo.Value)

 也可以代码动态绑定:

DataTable dt=new DataTable();
dt.Columns.Add("imagePkgNo", Type.GetType("System.Byte[]"));
byte[] imgBytes = GetBarcode(200, 1000, TYPE.CODE128, dt.Rows[0]["inner_pkg_no"].ToString(), out image);
dt1.Rows[0]["imagePkgNo"] = imgBytes;

主要代码如下:

 private void ReportView_Load(object sender, EventArgs e)
        {
            Image image;

            #region 存储过程返回数据集
            ProcedureHelper procedure = new ProcedureHelper(strConn);
            SqlParameter[] parameters =
            {
                    new SqlParameter("@inner_pkgNo", SqlDbType.VarChar)
             };
            parameters[0].Value = barCode;
            DataTable dt = procedure.ExecuteDataTable("P_PRINT_PKG", parameters);
            #endregion

            DataTable dt1 = new DataTable();
            if (dt.Rows.Count > 0)
            {
                #region 只取第一行数据作为新的数据集
                dt1 = dt.Copy();
                dt1.Rows.Clear();
                dt1.ImportRow(dt.Rows[0]);
                dt1.Columns.Add("imagePkgNo", Type.GetType("System.Byte[]"));//添加新列
                byte[] imgBytes = GetBarcode(200, 1000, TYPE.CODE128, dt.Rows[0]["inner_pkg_no"].ToString(), out image);
                dt1.Rows[0]["imagePkgNo"] = imgBytes;
                #endregion

                #region 添加参数
                List<ReportParameter> Paras = new List<ReportParameter>();
                Paras.Add(new ReportParameter("packegeNum", dt.Rows.Count.ToString()));
                this.reportViewer1.LocalReport.SetParameters(Paras);
                #endregion
               
                #endregion 绑定数据源
                ReportDataSource rds = new ReportDataSource("DataSet", dt1);
                reportViewer1.LocalReport.DataSources.Add(rds);
                reportViewer1.RefreshReport();
                #endregion
            }