0

我已经设置了一个表单,其中有一个带有预订的 DataGridView,目前我可以打印 DataGridView,但只能打印显示的内容,因此不会打印任何只能通过向下滚动才能看到的数据。

如何更改我的代码,以便当我单击打印按钮时,所有内容(包括通过滚动查看的数据)都打印到页面上?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace project
{
    public partial class frmViewBookings : Form
    {
        public frmViewBookings()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Form3 mainpage = new Form3();
            mainpage.Show();
            this.Close();
        }

        private void frmViewBookings_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
            this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);    
        }

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

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

1 回答 1

2

您要做的是创建一个虚拟表单,该表单与您要打印的控件的大小相同,然后将控件添加到虚拟表单并显示表单并在虚拟表单上打印控件。

我是这样做的:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    //Create bitmap
    Bitmap image = new Bitmap(dataGridView1.Width, dataGridView1.Height);
    //Create form
    Form f = new Form();
    //add datagridview to the form
    f.Controls.Add(dataGridView1);
    //set the size of the form to the size of the datagridview
    f.Size = dataGridView1.Size;
    //draw the datagridview to the bitmap
    dataGridView1.DrawToBitmap(image, new Rectangle(0, 0, dataGridView1.Width, dataGridView1.Height));
    //dispose the form
    f.Dispose();
    //print
    e.Graphics.DrawImage(image, 0, 0);
}
于 2013-04-07T00:29:57.780 回答