如何在页眉和页脚中打印带有文本的DataGridView?

时间:2015-02-05 09:47:22

标签: c# windows winforms

我编写了以下代码,用于在Windows c#中从DataGridView打印数据。 但我想在页眉和页脚中打印一个图像,文本。

    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        Bitmap bm = new Bitmap(this.SalesGridView.Width, this.SalesGridView.Height);
        SalesGridView.DrawToBitmap(bm, new Rectangle(0, 0, this.SalesGridView.Width, this.SalesGridView.Height));
        e.Graphics.DrawImage(bm, 0, 0);            
    }

    private void btnPrint_Click(object sender, EventArgs e)
    {
        printDocument1.Print();
    } 

1 个答案:

答案 0 :(得分:0)

您的代码当前正在将您的DataGridView与Bitmap对话,然后打印该Bitmap。除了DataGridView之外,要打印文本页眉和页脚,还需要Graphics.DrawString()方法:

// Create string to draw.
String drawString = "Sample Text";

// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);

// Create point for upper-left corner of drawing.
PointF drawPoint = new PointF(150.0F, 150.0F);

// Draw string to screen.
e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint);
}

您必须调整每个图形定位的浮点值。例如。您的代码e.Graphics.DrawImage(bm, 0, 0);在位置(0,0)处打印位图bm。因此,需要根据页面大小来更改页眉,页脚和DataGridView对象位置的位置。

如果您想在多个页面上打印you will need to create a loop并以编程方式将页眉和页脚添加到每个页面。