用printDocumnet打印 文本控件都是直接e.Graphics.DrawString();我现在需要打印一个DataGridView  则么打印啊?

解决方案 »

  1.   

    1. 把DataGridView中的数据转化成string集合:
            List<string> strPrint = new List<string>();
            private void button3_Click(object sender, EventArgs e)
            {
                string line = string.Empty;
                foreach (DataGridViewColumn col in this.dataGridView1.Columns)
                {
                    if (col.Index == 0)
                        line += col.Name.PadRight(22, ' ');
                    else
                        line += col.Name.PadRight(8, ' ');
                }
                line += "\n";
                strPrint.Add(line);            foreach (DataGridViewRow dr in this.dataGridView1.Rows)
                {
                    line = string.Empty;
                    foreach (DataGridViewCell cell in dr.Cells)
                    {
                        if (cell.ColumnIndex == 0)
                            line += cell.Value == null ? ".".PadRight(22, ' ') : cell.Value.ToString().PadRight(22, ' ');
                        else
                            line += cell.Value == null ? ".".PadRight(8, ' ') : cell.Value.ToString().PadRight(8, ' ');
                    }
                    line += "\n";
                    strPrint.Add(line);
                }
                strPrint.AddRange(new string[] { "\n", new string('*', 48) });
            }
    2. 打印时:
            private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
            {
                rowCount = 0;
                Graphics g = e.Graphics;                                    // 获得绘图对象
                float leftMargin = 10;                                      // 左边距
                float topMargin = 15;                                       // 上边距
                float yPosition = 0;                                        // 绘制字符串的纵向位置
                SolidBrush myBrush = new SolidBrush(Color.Black);           // 刷子            Font printFont = new Font(new FontFamily("宋体"), 7);           // 打印正文
                // 逐行地打印数据
                while (rowCount < strPrint.Count)
                {
                    yPosition += printFont.GetHeight(g);                    // 垂直位置
                    g.DrawString(strPrint[rowCount++], printFont, myBrush, leftMargin, yPosition, new StringFormat());
                }
            }
      

  2.   

    我是使用PadRight和PadLeft来控制对齐的, 如果要和表格一起打印,你可能要自己画线。
      

  3.   

    有代码没,发给参考参考,我不知道应该在哪里使用PadRight和PadLeft啊,怎么画线呢?