C# 调用打印机

来源:互联网 发布:淘宝前1000名付款几秒 编辑:程序博客网 时间:2024/05/21 10:33

在这里只占源码供日后所用

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;namespace PrinterDemo {    class PrinterTest {        private DataTable theDGV;           //用于接收包含打印内容的数据表        private string printTitle;          //打印标题内容        private List<int> ColumnsWidth;    //存储列宽        private List<int> ColumnsLeft;        private int totalWidth;           //计算打印区域的总宽度;        private int RowHeaderHeight;      //列标题的宽度        private int RowsHeight;             //存储行高        private int pageNO;                 //当前打印页的序号        private int rowPoint;               //当前打印行的序号        private bool newPage;               //是否打印新页的标识        private int PageWidth;        private int PageHeight;        private int LeftMargin;        private int TopMargin;        private int RightMargin;        private int BottomMargin;        private StringFormat TitleFormat;   //标题打印对齐格式        private StringFormat CellFormat;    //表格打印对齐格式        private PrintDocument myDocument;   //向打印机发送的输出对象        private Font theTitleFont;      //标题字体        private Font printFont;         //表格字体        public PrinterTest(PrintDocument document, DataTable DGV, string title, Font titleFont, Font printFont)        {            this.theDGV = DGV;            this.printTitle = title;            this.theTitleFont = titleFont;            this.printFont = printFont;            this.myDocument = document;            myDocument.OriginAtMargins = true;//指定绘图操作从页边距内开始算起            ColumnsWidth = new List<int>();            ColumnsLeft = new List<int>();        }        //计算打印参数。包括预打印表格的原始宽度,打印高度宽度        public void print_Calculate(Graphics g)        {            totalWidth =0;            SizeF tmpSize = new SizeF();            float tmpWidth;            //MessageBox.Show(printFont.ToString());            for (int i = 0; i < theDGV.Columns.Count; i++)            {                tmpSize = g.MeasureString(theDGV.Columns[i].ColumnName, printFont);                tmpWidth = tmpSize.Width;                RowHeaderHeight = (int)tmpSize.Height + 12;                for (int j = 0; j < theDGV.Rows.Count; j++)                {                    tmpSize = g.MeasureString("所有", printFont);                    RowsHeight = (int)tmpSize.Height + 8;             //获取行的高度                    tmpSize = g.MeasureString(theDGV.Rows[j][i].ToString(), printFont);                    if (tmpSize.Width > tmpWidth)                    {                        tmpWidth = tmpSize.Width;                    }                }                ColumnsWidth.Add((int)tmpWidth);                totalWidth += (int)tmpWidth;            }        }        public void dataGridView_print()        {            PrintPreviewDialog ppvw = new PrintPreviewDialog();            ppvw.Document = myDocument;            ppvw.ShowDialog();            myDocument.BeginPrint += new PrintEventHandler(myDocument_BeginPrint);            myDocument.PrintPage += new PrintPageEventHandler(myDocument_PrintPage);            if (ppvw.ShowDialog() == DialogResult.OK)            {                myDocument.Print();            }            else            {                myDocument.BeginPrint -= new PrintEventHandler(myDocument_BeginPrint);                myDocument.PrintPage -= new PrintPageEventHandler(myDocument_PrintPage);                ppvw.Dispose();                return;            }            myDocument.BeginPrint -= new PrintEventHandler(myDocument_BeginPrint);            myDocument.PrintPage -= new PrintPageEventHandler(myDocument_PrintPage);        }        private void drawRoot(PrintPageEventArgs e)             //打印页脚        {            string rowStr = "第" + pageNO.ToString() + "页";            e.Graphics.DrawString(rowStr, printFont, Brushes.Black, new RectangleF(0, PageHeight-TopMargin-BottomMargin, PageWidth - RightMargin - LeftMargin, e.Graphics.MeasureString(printTitle, theTitleFont).Height),TitleFormat);        }        private void myDocument_BeginPrint(object sender, PrintEventArgs e)        {            pageNO = 1;            rowPoint = 0;            newPage = true;            RowsHeight = 0;            RowHeaderHeight = 0;            totalWidth = 0;            ColumnsWidth.Clear();            ColumnsLeft.Clear();            TitleFormat = new StringFormat();           //初始化“标题打印对齐格式”            TitleFormat.Trimming = StringTrimming.Word;            TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;            TitleFormat.Alignment = StringAlignment.Center;            CellFormat = new StringFormat();            //初始化“表格打印对齐格式”            CellFormat.Trimming = StringTrimming.Word;            CellFormat.FormatFlags = StringFormatFlags.NoWrap| StringFormatFlags.LineLimit;            CellFormat.Alignment=StringAlignment.Center;            Graphics g = Graphics.FromImage(new Bitmap(100, 100));            this.print_Calculate(g);            g.Dispose();            if (myDocument.DefaultPageSettings.Landscape)            {                PageWidth = myDocument.DefaultPageSettings.PaperSize.Height;                PageHeight = myDocument.DefaultPageSettings.PaperSize.Width;            }            else            {                PageWidth = myDocument.DefaultPageSettings.PaperSize.Width;                PageHeight = myDocument.DefaultPageSettings.PaperSize.Height;            }            LeftMargin = myDocument.DefaultPageSettings.Margins.Left;            RightMargin = myDocument.DefaultPageSettings.Margins.Right;            TopMargin = myDocument.DefaultPageSettings.Margins.Top;            BottomMargin = myDocument.DefaultPageSettings.Margins.Bottom;            if ((!myDocument.DefaultPageSettings.Landscape) && (totalWidth > (PageWidth - LeftMargin - RightMargin)))            {                DialogResult result = MessageBox.Show("打印内容超出了打印可见区域,程序将自动调整打印列宽以适应打印区大小,/n但是这样做会使部分打印列的内容无法完全显示,(建议将打印方向设置为横向以后再进行打印)/n继续打印操作选择“是”,取消选择“否”", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);                if (result == DialogResult.Yes)                {                    myDocument.DefaultPageSettings.Landscape = true;                    int temp = PageWidth;                    PageWidth = PageHeight;                    PageHeight = temp;                }                else                {                                        myDocument.DefaultPageSettings.Landscape = false;                }            }            int tmpLeft = 0;            for (int i = 0; i < ColumnsWidth.Count; i++)     //列宽自动适应打印区域大小            {                ColumnsWidth[i] = ColumnsWidth[i] * (PageWidth - LeftMargin - RightMargin) / totalWidth;                ColumnsLeft.Add(tmpLeft);                tmpLeft += ColumnsWidth[i];            }        }        private void myDocument_PrintPage(object sender, PrintPageEventArgs e)        {            e.Graphics.Clear(Color.White);            int i;            int tmpTop = 0;            if (pageNO == 1&&printTitle!="")  //如果是第一页,则打印标题            {                RectangleF TitleRectangle = new RectangleF(0, 0, PageWidth - RightMargin - LeftMargin, e.Graphics.MeasureString(printTitle, theTitleFont).Height);                e.Graphics.DrawString(printTitle, theTitleFont, new SolidBrush(Color.Black), TitleRectangle, TitleFormat);                tmpTop += (int)e.Graphics.MeasureString(printTitle, theTitleFont).Height+10;            }                        while (rowPoint < theDGV.Rows.Count)            {                DataRow row = theDGV.Rows[rowPoint];                if (tmpTop +RowsHeight >= PageHeight - TopMargin - BottomMargin)                {                    drawRoot(e);                    newPage = true;                    pageNO++;                    e.HasMorePages = true;                    return;                }                else                {                    if (newPage)            //如果是新页,打印列标题                    {                        for(i=0;i<theDGV.Columns.Count;i++)                        {                            DataColumn column = theDGV.Columns[i];                            e.Graphics.FillRectangle(new SolidBrush(Color.LightGray), new Rectangle(ColumnsLeft[i], tmpTop, ColumnsWidth[i], RowHeaderHeight));                            e.Graphics.DrawRectangle(Pens.Black, new Rectangle(ColumnsLeft[i], tmpTop, ColumnsWidth[i], RowHeaderHeight));                            e.Graphics.DrawString(column.ColumnName, printFont, new SolidBrush(Color.Black), new RectangleF(ColumnsLeft[i], tmpTop + 7, ColumnsWidth[i], RowHeaderHeight), CellFormat);                        }                        newPage = false;                        tmpTop += RowHeaderHeight;                    }                                        for(i=0;i<theDGV.Columns.Count;i++)                    {                        e.Graphics.DrawRectangle(Pens.Black, new Rectangle(ColumnsLeft[i], tmpTop, ColumnsWidth[i], RowsHeight));                        e.Graphics.DrawString(row[i].ToString(), printFont, new SolidBrush(Color.Black), new RectangleF(ColumnsLeft[i], tmpTop + 5, ColumnsWidth[i], RowsHeight), CellFormat);                    }                    tmpTop += RowsHeight;                }                rowPoint++;            }            drawRoot(e);            e.HasMorePages = false;        }        public void Dispose()        {            theDGV.Dispose();            myDocument.Dispose();        }    }}


调用该类的代码:

   Font printFont = new Font("Arial", 10);            Font titleFont = new Font("Arial", 15);            System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();            DataTable dt = new DataTable("Table_AX");            dt.Columns.Add("column0", System.Type.GetType("System.String"));            dt.Columns.Add("column1", System.Type.GetType("System.String"));            DataRow dr = dt.NewRow();            dr["column0"] = "打印机";            dr["column1"] = "1份";            dt.Rows.Add(dr);            DataRow dr1 = dt.NewRow();            dr1["column0"] = "扫描仪";            dr1["column1"] = "2份";            dt.Rows.Add(dr1);            Graphics g = Graphics.FromImage(new Bitmap(100, 100));            PrinterTest pt = new PrinterTest(pd, dt, "I Love You", titleFont, printFont);            pt.print_Calculate(g);            pt.dataGridView_print();            pt.Dispose();


 

原创粉丝点击