欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-14 08:44:34
主窗体代码如下: 复制代码 代码如下:public partial class printfileform : form    { ...

主窗体代码如下:

复制代码 代码如下:

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;

        }
    }

上一篇:

下一篇: