C# 直接打印指定路径文件 + 可选择指定打印机

        public void PrinteTicketWithPath(string path)
        {
                try 
            {
                streamToPrint = new StreamReader (path);
                try 
                {
                    printFont = new Font("Arial", 10);
                    PrintDocument pd = new PrintDocument();
                    if (core.PrinterTicket != null)
                    {
                        pd.PrinterSettings.PrinterName = core.PrinterTicket;
                    }
                    pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                    // Print the document.
                    pd.Print();
                } 
                finally 
                {
                    streamToPrint.Close() ;
                }
            } 
            catch(Exception ex) 
            { 
                MessageBox.Show(ex.Message);
            }
        }

        // The PrintPage event is raised for each page to be printed.
        private void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = ev.MarginBounds.Left;
            float topMargin = ev.MarginBounds.Top;
            String line = null;

            // Calculate the number of lines per page.
            linesPerPage = ev.MarginBounds.Height /
                printFont.GetHeight(ev.Graphics);

            // Iterate over the file, printing each line.
            while (count < linesPerPage &&
                ((line = streamToPrint.ReadLine()) != null))
            {
                yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                ev.Graphics.DrawString(line, printFont, Brushes.Black,
                    leftMargin, yPos, new StringFormat());
                count++;
            }

            // If more lines exist, print another page.
            if (line != null)
            {
                ev.HasMorePages = true;
            }
            else
            {
                ev.HasMorePages = false;
            } 
        }


core 是个获取本地属性的类, 包括可以读取可用打印机的名字


       
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页