John
John

Reputation: 35

C# Preview Print Dialog

I have a datagrid of information and when the print button is clicked I want to show a print preview screen of what it will look like and then let the user print the document. Heres what I got so far:

        PrintDocument myDocument = new PrintDocument();


        PrintPreviewDialog PrintPreviewDialog1 = new PrintPreviewDialog();
        PrintPreviewDialog1.Document = myDocument;
        PrintPreviewDialog1.ShowDialog();

My question is how to get the data onto the preview screen.. thanks!

Upvotes: 0

Views: 711

Answers (1)

TaW
TaW

Reputation: 54433

You need to add the PrintPage event:

myDocument.DocumentName = "Test2015";
myDocument.PrintPage += myDocument_PrintPage;

and you need to code it! In its very simplest form this will dump out the data:

void myDocument_PrintPage(object sender, PrintPageEventArgs e)
{
   foreach(DataGridViewRow row in dataGridView1.Rows)
      foreach(DataGridViewCell cell in row.Cells)
      {
          if (Cell.Value != null)
              e.Graphics.DrawString(cell.Value.ToString(), Font,  Brushes.Black, 
                          new Point(cell.ColumnIndex * 123, cell.RowIndex  * 12 ) );
      }
}

But of course you will want to add a lot more to get nice formatting etc..

  • For example you can use the Graphics.MeasureString() method to find out the size of a chunk of text to optimize the coodinates, which are hard coded just for testing here.

  • You may use the cell.FormattedValue instead of the raw Value.

  • You may want to prepare a few Fonts you will use, prefix the dgv with a header, maybe a logo..

Also worth considering is to set the Unit to something device independent like mm:

e.Graphics.PageUnit = GraphicsUnit.Millimeter;

And, if need be, you should keep track of the vertical positions so you can add page numbers and recognize when a Page is full!

Update: Since your DGV may contain empty cells I have added a check for null.

Upvotes: 1

Related Questions