C# Preview Print Dialog

前端 未结 1 1944
遥遥无期
遥遥无期 2021-01-17 03:15

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 documen

1条回答
  •  隐瞒了意图╮
    2021-01-17 04:02

    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.

    0 讨论(0)
提交回复
热议问题