C#预览打印对话框
我有一个信息的数据网格,当点击打印按钮时,我想显示一个打印预览屏幕,它会是什么样子,然后让用户打印文档。 这是我到目前为止得到的:
PrintDocument myDocument = new PrintDocument(); PrintPreviewDialog PrintPreviewDialog1 = new PrintPreviewDialog(); PrintPreviewDialog1.Document = myDocument; PrintPreviewDialog1.ShowDialog();
我的问题是如何将数据放到预览屏幕上..谢谢!
您需要添加PrintPage
事件:
myDocument.DocumentName = "Test2015"; myDocument.PrintPage += myDocument_PrintPage;
你需要编码! 以最简单的forms,这将转储数据:
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 ) ); } }
但是当然你会想要添加更多以获得更好的格式化等。
-
例如,您可以使用
Graphics.MeasureString()
方法找出一大块文本的大小来优化coodinates,这些coodinates仅用于此处的测试。 -
您可以使用
cell.FormattedValue
而不是原始Value
。 -
您可能想要准备一些您将使用的
Fonts
,在dgv前面加上标题,也许是徽标..
另外值得考虑的是将Unit
设置为与mm
无关的设备:
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
并且,如果需要,您应该跟踪垂直位置,以便您可以添加页码并识别页面已满!
更新:由于您的DGV
可能包含空单元格,因此我添加了一个null
检查。