Loading

C#打印字符串内容,例如打印Textbox内容

    /// <summary>
    /// 打印txt文档
    /// </summary>
    class PrintTxt
    {
        System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();

        int linesText = 0;//内容行数
        int linesPerPage = 0;//一页的行数
        int currentPage = 0;//当前页
        int pageCount = 0;//多少页
        string[] lines;//存储内容
        int icount = 0;//行数
        string textString = "";
        public PrintTxt(string txt)
        {
            textString = txt;//给内容进行赋值
            printDocument.PrintPage += PrintDocument_PrintPage;
            printDocument.BeginPrint += PrintDocument_BeginPrint;
        }
        private void PrintDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            StringReader s1 = new StringReader(textString);
            string s = s1.ReadToEnd();
            lines = s.Split(new string[] { "\n" }, StringSplitOptions.None);
        }

        private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            System.Drawing.Graphics g = e.Graphics; //获得绘图对象
            float yPosition = 0; //绘制字符串的纵向位置
            float xPosition = 0;
            float leftMargin = e.MarginBounds.Left; //左边距
            float topMargin = e.MarginBounds.Top; //上边距
            linesText = lines.Count();
            System.Drawing.Font printFont = new System.Drawing.Font("宋体", 10); //当前的打印字体
            System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);//刷子
            linesPerPage = (int)(e.MarginBounds.Height / printFont.GetHeight(g));//每页可打印的行数
            pageCount = linesText % linesPerPage == 0 ? (linesText / linesPerPage) : (linesText / linesPerPage + 1);

            for (int i = 0; i < linesPerPage; i++)
            {
                yPosition = topMargin + (i * printFont.GetHeight(g)) - 30;
                xPosition = leftMargin + (printFont.GetHeight(g)) + 5;
                if (icount == linesText)
                {
                    return;
                }
                g.DrawString(lines[icount], printFont, myBrush, xPosition, yPosition, new System.Drawing.StringFormat());
                icount++;
            }
            currentPage++;

            if (currentPage < pageCount)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
            }
        }

        public void StartPrintTxt()
        {
            printDocument.Print();
        }
    }

打印的过程大致就是将Textbox里的内容获取行数,然后计算一页打印多少行,然后总共打印多少页

posted @ 2018-09-21 14:32  眾尋  阅读(4645)  评论(0编辑  收藏  举报