本文介绍了C# 预览打印对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个信息数据网格,当点击打印按钮时我想显示它的外观的打印预览屏幕,然后让用户打印文档.这是我目前得到的:

I have a datagrid of information and when the print button is clickedI want to show a print preview screen of what it will look like and thenlet 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!

推荐答案

需要添加PrintPage事件:

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..

  • 例如,您可以使用 Graphics.MeasureString() 方法找出文本块的大小以优化坐标,这些坐标是硬编码的,仅用于此处的测试.

  • 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.

您可以使用 cell.FormattedValue 而不是原始的 Value.

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

您可能想要准备一些您将使用的 Fonts,在 dgv 前面加上标题,也许是徽标..

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

另外值得考虑的是将 Unit 设置为与设备无关的东西,例如 mm:

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!

更新:由于您的 DGV 可能包含空单元格,我添加了对 null 的检查.

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

这篇关于C# 预览打印对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:16