zoukankan      html  css  js  c++  java
  • C# winform 使用rdlc打印小票其中包含动态显示多条形码的解决方法

    前言

    最近做一个项目就是winform程序去控制设备,通过modbus-rtu协议去通讯。做的过程中上位机还牵扯到与其他系统对接的问题,当对接好其他系统数据后将数据打印出一个小票,上位机端用serialport来发送和接收下位机指令,下位机接收到上位机的发送的指令设备就做某个动作,设备动作完成将状态发送给上位机,然后在winform界面呈现设备的状态,整体的工作原理大概就是这样子,具体业务就不方便写入到博客中,打印的需求是随着打印的内容长短决定打印纸的出纸长度,于是乎在winform中使用rdlc的想法就冒出来了,且看下面步骤

    winform 使用rdlc打印小票其中包含动态显示多条形码步骤如下

    1、 去nuget中download引用一个Microsoft.ReportingServices.ReportViewerControl.Winforms,通过nuget引入进来时会自动添加Microsoft.ReportViewer.WinForms、Microsoft.ReportViewer.Common.dll、Microsoft.ReportViewer.DataVisualization.dll、Microsoft.ReportViewer.Design.dll、Microsoft.ReportViewer.ProcessingObjectModel.dll,一共就是5个dll库才能用LocalReport

    https://www.nuget.org/packages/Microsoft.ReportingServices.ReportViewerControl.Winforms/150.1404.0?_src=template

    2、添加rdlc文件,且设计rdlc参数和对象数据集,通过 “表” 组件来循环输出数据,其中包括条码,项目名称等等内容,rdlc打印条码,这里后台将数据传输到rdlc时需要将条码图片转成条码字节数组byte[],然后在rdlc中放一个图片组件,将数据集中条码字节数组给到表达式中即可rdlc循环打印条码输出

     rdlc数据的组装,条码生成图片要用到BarcodeLib.dll

    rdlc自动打印条码的结果

     

     rdlc打印小票其中包含动态显示多条形码具体实现代码请看以下代码 

     private void button1_Click(object sender, EventArgs e)
            {
                #region test method
                var fileurl = Application.StartupPath + @"data.txt";//数据源
                if (!File.Exists(fileurl))
                {
                    MessageBox.Show("路径不存在");
                    return;
                }
                var resultStr = File.ReadAllText(fileurl);
                #endregion
    
                var XmlString = Utils.SoapReplace(Utils.ToTxt(resultStr));//解析数据源
                Utils.WriteCommandLog("LIS返回信息:" + XmlString);
                var result = Utils.DeserializeXmlToObject<Response>(XmlString);//xml数据源转换Response对象
                if (result.Code == -1)            
                    return;            
                var data = result.LabInfos;//Lis返回的数据结果   
    #region 回执单打印 LocalReport report = new LocalReport(); //设置需要打印的报表的文件名称。 report.ReportPath = AppDomain.CurrentDomain.BaseDirectory + @" eceipt.rdlc"; /*自动打印*/ var list = new List<reportData>(); for (int i = 0; i < data.Count; i++) { var item = data[i]; var barcodearr = Utils.ImageToBytes(CreateBarcodePicture(item.LabNum, 418, 50)); list.Add(new reportData() { BarCode = item.LabNum, BarCodeImageArr = barcodearr, PatNo = item.HospNum, Priority = item.Priority, Source = item.Source, TakeReportAddress = item.TakeReportAddress, TakeReportDesc = item.TakeReportDesc, TestItemDesc = item.TestItemDesc }); } ReportDataSource reportDataSource = new ReportDataSource(); reportDataSource.Name = "DataSet1"; reportDataSource.Value = list;//要输出的数据集 ReportParameter DropPricePrint_rp1 = new ReportParameter("cnname", "李欧"); ReportParameter DropPricePrint_rp2 = new ReportParameter("sex", "男"); ReportParameter DropPricePrint_rp3 = new ReportParameter("age", "30岁"); ReportParameter DropPricePrint_rp4 = new ReportParameter("PrintTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); ReportParameter DropPricePrint_rp5 = new ReportParameter("hospnum", "0001062975"); report.SetParameters(new ReportParameter[] { DropPricePrint_rp1, DropPricePrint_rp2, DropPricePrint_rp3, DropPricePrint_rp4, DropPricePrint_rp5 }); report.DataSources.Add(reportDataSource); report.Refresh(); RDLCPrinter.Run(report, "Microsoft XPS Document Writer"); #endregion }

    根据字符串生成条码图片对象( 需添加引用:BarcodeLib.dll )

          /// <summary>
            /// 根据字符串生成条码图片( 需添加引用:BarcodeLib.dll )
            /// </summary>
            /// <param name="BarcodeString">条码字符串</param>
            /// <param name="ImgWidth">图片宽带</param>
            /// <param name="ImgHeight">图片高度</param>
            /// <returns></returns>
            public System.Drawing.Image CreateBarcodePicture(string BarcodeString, int ImgWidth, int ImgHeight)
            {
                BarcodeLib.Barcode b = new BarcodeLib.Barcode();//实例化一个条码对象
                BarcodeLib.TYPE type = BarcodeLib.TYPE.CODE128;//编码类型
                //获取条码图片
                System.Drawing.Image BarcodePicture = b.Encode(type, BarcodeString, System.Drawing.Color.Black, System.Drawing.Color.White, ImgWidth, ImgHeight);
                b.Dispose();
                return BarcodePicture;
            }

    RDLCPrinter  通过RDLC向默认打印机输出打印报表

    using System;
    using System.Collections.Generic; 
    using System.Drawing.Imaging;
    using System.Drawing.Printing;
    using System.IO; 
    using System.Text;
    using Microsoft.Reporting.WinForms;
    
    namespace System
    {
        /// <summary>
        /// 通过RDLC向默认打印机输出打印报表
        /// </summary>
        public class RDLCPrinter : IDisposable
        {
            /// <summary>
            /// 当前打印页号
            /// </summary>
            static int m_currentPageIndex;
    
            /// <summary>
            /// RDCL转换stream一页对应一个stream
            /// </summary>
            static List<Stream> m_streams;
    
            /// <summary>
            /// 把report输出成stream
            /// </summary>
            /// <param name="report">传入需要Export的report</param>
            private void Export(LocalReport report)
            {
                string deviceInfo =
                  "<DeviceInfo>" +
                  "  <OutputFormat>EMF</OutputFormat>" +
                    //"  <PageWidth>8cm</PageWidth>" +
                    //"  <PageHeight>20in</PageHeight>" +
                    "  <MarginTop>0in</MarginTop>" +
                    "  <MarginLeft>0in</MarginLeft>" +
                    "  <MarginRight>0in</MarginRight>" +
                    "  <MarginBottom>0in</MarginBottom>" +
                  "</DeviceInfo>";
                Warning[] warnings;
                m_streams = new List<Stream>();
                report.Render("Image", deviceInfo, CreateStream, out warnings);
                foreach (Stream stream in m_streams)
                    stream.Position = 0;
            }
    
            /// <summary>
            /// 创建具有指定的名称和格式的流。
            /// </summary>
            private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
            {
                Stream stream = new FileStream(name + "." + fileNameExtension,
                  FileMode.Create);
                m_streams.Add(stream);
                return stream;
            }
    
            /// <summary>
            /// 打印输出
            /// </summary>
            private void PrintPage(object sender, PrintPageEventArgs ev)
            {
                Metafile pageImage =
                  new Metafile(m_streams[m_currentPageIndex]);
                ev.Graphics.DrawImage(pageImage, ev.PageBounds);
                m_currentPageIndex++;
                ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
            }
    
            /// <summary>
            /// 打印预处理
            /// 打印机名称: Microsoft XPS Document Writer
            /// </summary>
            private void Print(string printerName)
            {
                PrintDocument printDoc = new PrintDocument();
                if (m_streams == null || m_streams.Count == 0)
                    return;
                printDoc.PrinterSettings.PrinterName = printerName;
                if (!printDoc.PrinterSettings.IsValid)
                {
                    string msg = String.Format("Can't find printer "{0}".", printerName);
                    throw new Exception(msg);
                }
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                StandardPrintController spc = new StandardPrintController();//指定打印控制器
                printDoc.PrintController = spc;
                printDoc.Print();
            }
    
            public void Dispose()
            {
                if (m_streams != null)
                {
                    foreach (Stream stream in m_streams)
                        stream.Close();
                    m_streams = null;
                }
            }
    
            /// <summary>
            /// 对外接口,启动打印
            /// </summary>
            /// <param name="report">打印报表组件</param>
            /// <param name="printerName">打印机名称</param>
            public static void Run(LocalReport report, string printerName)
            {
                m_currentPageIndex = 0;
                RDLCPrinter billPrint = new RDLCPrinter();
                billPrint.Export(report);
                billPrint.Print(printerName);
                billPrint.Dispose();
            } 
        }
    
    }

    当然这里也提供了源码给您下载,如您需要请点击 【rdlc动态打印多条形码源码例子】  提取码: 6p5v

    对于rdlc如何打印小票其中包含动态显示多条形码的解决方法对你有用,那就拿去不用谢

  • 相关阅读:
    (转)三款Json查看小工具
    开源数据源
    关于异常
    java 线程池
    百度android面试及一些问题的讲解
    linux常用命令
    android activityManager
    Android ListView及其属性
    android listView与adapter
    android 反编译
  • 原文地址:https://www.cnblogs.com/axinno1/p/13265011.html
Copyright © 2011-2022 走看看