实现简单打印 C# 实现简单打印的实例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

实现简单打印 C# 实现简单打印的实例代码

  2021-03-18 我要评论
想了解C# 实现简单打印的实例代码的相关内容吗,在本文为您仔细讲解实现简单打印的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:简单,打印,下面大家一起来学习吧。

主窗体代码如下:

复制代码 代码如下:

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;

        }
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们