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.