简体   繁体   中英

How to generate a print preview in winforms c#

I am trying to generate a print preview from the form in c# Winforms. Already added PrintPreviewDialog and PrintDocument and some code:

using System.Drawing.Printing;

private Bitmap myImage;

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
     e.Graphics.DrawImage(myImage, 0, 0);
}
private void Button_Click(object sender, EventArgs e)
{
     Graphics g = this.CreateGraphics();
     myImage = new Bitmap(this.Size.Width, this.Size.Height, g);
     Graphics mg = Graphics.FromImage(myImage);
     mg.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, this.Size);
     printPreviewDialog1.ShowDialog();
}

After I click the button I get the Print Preview and this "Document does not contains any pages". Anyone have any idea why is this happening? Am I missing something?

You need to attach your PrintDocument to the Print Preview Dialog prior to showing the dialog.

In your example, before this line in Button_Click() :

printPreviewDialog1.ShowDialog();

You need to add (assuming printDocument1 is the name of your PrintDocument ):

printPreviewDialog1.Document = printDocument1;

Refer to the example given in the documentation for PrintPreviewDialog (.NET 4.8) and PrintDocument (.NET 4.8) for other adjustments that you may need to make to get the preview you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM