C# 實現簡單列印的執行個體代碼

來源:互聯網
上載者:User

主表單代碼如下:

複製代碼 代碼如下: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;

}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.