C# Preview Print Dialog

此生再无相见时 提交于 2019-12-19 12:22:27

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/28368453/c-sharp-preview-print-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!