WinForm中的簡單打印

最近工作很是鬱悶,有做WEB又要改桌面程序,要求之前基於DevExpress報表打印改成 DataGridView呈現數據 ,配置30分鐘提醒用戶打印,我發現我是越來越懶了,主要是情緒不好,什麼問題 第一反應肯定谷歌之然後自己封裝下,無暇思考,萬能的谷歌啊

    public class Printer
    {

        private DataGridView dataview;
        private PrintDocument printDoc;
        //打印有效區域的寬度
        int width;
        int height;
        int columns;
        double Rate;
        bool hasMorePage = false;
        int currRow = 0;
        int rowHeight = 20;
        //打印頁數
        int PageNumber;
        //當前打印頁的行數
        int pageSize = 20;
        //當前打印的頁碼
        int PageIndex;

        int AreaHeight;

        private int PageWidth; //打印紙的寬度
        private int PageHeight; //打印紙的高度
        private int LeftMargin; //有效打印區距離打印紙的左邊大小
        private int TopMargin;//有效打印區距離打印紙的上面大小
        private int RightMargin;//有效打印區距離打印紙的右邊大小
        private int BottomMargin;//有效打印區距離打印紙的下邊大小

        int rows;


        private string[] footer;

        /**/
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="dataview">要打印的DateGridView</param>
        /// <param name="printDoc">PrintDocument用於獲取打印機的設置</param>
        public Printer(DataGridView dataview, PrintDocument printDoc, string[] footer)
        {
            this.footer = footer;

            this.dataview = dataview;
            this.printDoc = printDoc;
            PageIndex = 0;
            //獲取打印數據的具體行數
            this.rows = dataview.RowCount;

            this.columns = dataview.ColumnCount;
            //判斷打印設置是否是橫向打印
            if (!printDoc.DefaultPageSettings.Landscape)
            {

                PageWidth = printDoc.DefaultPageSettings.PaperSize.Width;
                PageHeight = printDoc.DefaultPageSettings.PaperSize.Height;
            }
            else
            {
                PageHeight = printDoc.DefaultPageSettings.PaperSize.Width;
                PageWidth = printDoc.DefaultPageSettings.PaperSize.Height;
            }
            LeftMargin = printDoc.DefaultPageSettings.Margins.Left - 50;
            TopMargin = printDoc.DefaultPageSettings.Margins.Top + 60;
            RightMargin = printDoc.DefaultPageSettings.Margins.Right;
            BottomMargin = printDoc.DefaultPageSettings.Margins.Bottom - 100;


            height = PageHeight - TopMargin - BottomMargin - 2;
            width = PageWidth - LeftMargin - RightMargin - 2;

            double tempheight = height;
            double temprowHeight = rowHeight;
            while (true)
            {
                string temp = Convert.ToString(tempheight / Math.Round(temprowHeight, 3));
                int i = temp.IndexOf('.');
                double tt = 100;
                if (i != -1)
                {
                    tt = Math.Round(Convert.ToDouble(temp.Substring(temp.IndexOf('.'))), 3);
                }
                if (tt <= 0.01)
                {
                    rowHeight = Convert.ToInt32(temprowHeight);
                    break;
                }
                else
                {
                    temprowHeight = temprowHeight + 0.01;
                }
            }
            pageSize = height / rowHeight;
            if ((rows + 1) <= pageSize)
            {
                pageSize = rows + 1;
                PageNumber = 1;
            }
            else
            {
                PageNumber = rows / (pageSize - 1);
                if (rows % (pageSize - 1) != 0)
                {
                    PageNumber = PageNumber + 1;
                }

            }

        }

        /**/
        /// <summary>
        /// 初始化打印
        /// </summary>
        private void InitPrint()
        {
            PageIndex = PageIndex + 1;
            if (PageIndex == PageNumber)
            {
                hasMorePage = false;
                if (PageIndex != 1)
                {
                    pageSize = rows % (pageSize - 1) + 1;
                }
            }
            else
            {
                hasMorePage = true;
            }

        }
        //打印頭
        private void DrawHeader(Graphics g)
        {
            Font font = new Font("宋體", 11, FontStyle.Regular);
            int temptop = (rowHeight / 2) + TopMargin + 1;
            int templeft = LeftMargin + 1;

            for (int i = 0; i < this.columns; i++)
            {
                string headString = this.dataview.Columns[i].HeaderText;
                float fontHeight = g.MeasureString(headString, font).Height;
                float fontwidth = g.MeasureString(headString, font).Width;
                float temp = temptop - (fontHeight) / 3;
                g.DrawString(headString, font, Brushes.Black, new PointF(templeft, temp));
                templeft = templeft + (int)(this.dataview.Columns[i].Width / Rate) + 1;
            }

        }
        //畫表格
        private void DrawTable(Graphics g)
        {
            Rectangle border = new Rectangle(LeftMargin, TopMargin, width, (pageSize) * rowHeight);
            g.DrawRectangle(new Pen(Brushes.Black, 1), border);
            for (int i = 1; i < pageSize; i++)
            {
                if (i != 1)
                {
                    g.DrawLine(new Pen(Brushes.Black, 1), new Point(LeftMargin + 1, (rowHeight * i) + TopMargin + 1), new Point(width + LeftMargin, (rowHeight * i) + TopMargin + 1));
                }
                else
                {
                    g.DrawLine(new Pen(Brushes.Black, 1), new Point(LeftMargin + 1, (rowHeight * i) + TopMargin + 1), new Point(width + LeftMargin, (rowHeight * i) + TopMargin + 1));
                }
            }

            //計算出列的總寬度和打印紙比率
            Rate = Convert.ToDouble(GetDateViewWidth()) / Convert.ToDouble(width);
            int tempLeft = LeftMargin + 1;
            int endY = (pageSize) * rowHeight + TopMargin;
            for (int i = 1; i < columns; i++)
            {
                tempLeft = tempLeft + 1 + (int)(this.dataview.Columns[i - 1].Width / Rate);
                g.DrawLine(new Pen(Brushes.Black, 1), new Point(tempLeft, TopMargin), new Point(tempLeft, endY));
            }

        }
        /**/
        /// <summary>
        /// 獲取打印的列的總寬度
        /// </summary>
        /// <returns></returns>
        private int GetDateViewWidth()
        {
            int total = 0;
            for (int i = 0; i < this.columns; i++)
            {
                total = total + this.dataview.Columns[i].Width;
            }
            return total;
        }

        //打印行數據
        private void DrawRows(Graphics g)
        {

            Font font = new Font("宋體", 11, FontStyle.Regular);
            int temptop = (rowHeight / 2) + TopMargin + 1 + rowHeight;


            for (int i = currRow; i < pageSize + currRow - 1; i++)
            {
                int templeft = LeftMargin + 1;
                for (int j = 0; j < columns; j++)
                {
                    string headString = this.dataview.Rows[i].Cells[j].Value.ToString();
                    float fontHeight = g.MeasureString(headString, font).Height;
                    float fontwidth = g.MeasureString(headString, font).Width;
                    float temp = temptop - (fontHeight) / 3;
                    while (true)
                    {
                        if (fontwidth <= (int)(this.dataview.Columns[j].Width / Rate))
                        {
                            break;
                        }
                        else
                        {
                            headString = headString.Substring(0, headString.Length - 1);
                            fontwidth = g.MeasureString(headString, font).Width;
                        }
                    }
                    g.DrawString(headString, font, Brushes.Black, new PointF(templeft, temp));

                    templeft = templeft + (int)(this.dataview.Columns[j].Width / Rate) + 1;
                }

                temptop = temptop + rowHeight;
            }
            currRow = pageSize + currRow - 1;

            AreaHeight = temptop;

        }

        /**/
        /// <summary>
        /// 在PrintDocument中的PrintPage方法中調用
        /// </summary>
        /// <param name="g">傳入PrintPage中PrintPageEventArgs中的Graphics</param>
        /// <returns>是否還有打印頁 有返回true,無則返回false</returns>
        public bool Print(Graphics g)
        {
            InitPrint();
            DrawTable(g);
            DrawHeader(g);
            DrawRows(g);
            //打印頁碼
            string pagestr = PageIndex + " / " + PageNumber;
            Font font = new Font("宋體", 11, FontStyle.Regular);
            g.DrawString(pagestr, font, Brushes.Black, new PointF((PageWidth / 2) - g.MeasureString(pagestr, font).Width, PageHeight - (BottomMargin / 2) - g.MeasureString(pagestr, font).Height));
            // 打印查詢的功能項名稱

            return hasMorePage;
        }
    }

調用即可

  private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            string[] foot = {  };
            Printer p = new Printer(this.dgvWarehouseView, printDocument1, foot);
            p.Print(e.Graphics);
        }
            if (DialogResult.OK == MessageBox.Show("請確認需要打印嗎?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
              
                    if (this.printDialog1.ShowDialog() == DialogResult.OK)
                    {
                        this.printDocument1.Print();
                    }
                
            }

訂閱提醒打印事件,時間我用Web的緩存做了

public delegate void SettingTimeNotifyDelegateHandler(string time);
        public event SettingTimeNotifyDelegateHandler EventSettingTimeNotifyDelegateHandler;
     
            if (!string.IsNullOrEmpty(this.numTime.Value.ToString()))
            {
                if (EventSettingTimeNotifyDelegateHandler != null)
                {
                    EventSettingTimeNotifyDelegateHandler(this.numTime.Value.ToString());
                    this.Close();
                }
            }
         
            SetTime st = new SetTime();
            st.EventSettingTimeNotifyDelegateHandler += (time) =>
            {
                _time = Convert.ToInt32(time) * 60;
                CacheHelper.SetCacheData("SetTimeNoify", "SetTimeNoify", _time);

                //this.axWindowsMediaPlayer1.URL = Application.StartupPath + "\\流水.wav";
                //this.axWindowsMediaPlayer1.Ctlcontrols.play();
            };
            st.ShowDialog();

           if (!CacheHelper.IsCacheExist("SetTimeNoify"))
            {
                CacheHelper.SetCacheData("SetTimeNoify", "SetTimeNoify", _time);
                this.axWindowsMediaPlayer1.URL = Application.StartupPath + "\\流水.wav";
                this.axWindowsMediaPlayer1.Ctlcontrols.play();

                //if (MessageBox.Show("系統提醒您打印數據?", "提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                //{
                //    this.axWindowsMediaPlayer1.Ctlcontrols.stop();
                //}
            }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章