程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C# 實現簡單打印的實例代碼

C# 實現簡單打印的實例代碼

編輯:C#基礎知識

主窗體代碼如下:

代碼如下:

public partial class PrintFileForm : Form
    {
        public PrintFileForm()
        {
            InitializeComponent();
            PrintFile prinFile = new PrintFile();
            prinFile.Print();
        }
    }

打印文件類如下:

代碼如下:

class PrintFile
    {
        StreamReader sr = null;
        Font printFont = new Font("宋體", 12);
        public void Print()
        {
            try
            {
                sr = new StreamReader(@"F:\Temp.txt");
                try
                {
                    PrintDocument printDoc = new PrintDocument();
                    printDoc.PrintPage += printDoc_PrintPage;
                    printDoc.Print();
                }
                finally
                {
                    sr.Close();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            string line = null;
            //設置一頁的行數=打印區域的高度除以字體高度.
            float pageLine = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);
            //循環打印每一行
            for (int count = 0; count < pageLine && ((line=sr.ReadLine())!=null); count++)
            {
                float singleLine=e.MarginBounds.Top+(count*printFont.GetHeight(e.Graphics));
                e.Graphics.DrawString(line, printFont, Brushes.Black, e.MarginBounds.Left, singleLine);
            }
            //判斷是否繼續打印
            if (line != null)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;

        }
    }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved