65.9K
CodeProject 正在变化。 阅读更多。
Home

打印 WinForms 用户控件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (6投票s)

2009年4月21日

CPOL

2分钟阅读

viewsIcon

56956

这是如何在整页上打印您的自定义用户控件的方法。

引言

几周前,我遇到一个看似简单的问题。我的应用程序有一个复杂的用户控件,代表一个报告,我的客户决定他希望能够将其打印到一页上。我想,“这有多难?”

背景

在我自己努力了半天试图弄清楚之后,又向老同事咨询,然后在论坛和其他地方进行了一些徒劳的搜索后,我只找到了一些提示和代码片段。我可以打印控件 - 但它真的很小,并且位于页面的一个角落。显然,我需要弄清楚如何正确缩放它。所以,我卷起袖子,深入研究...然后我们就来到了这里。

在您发现这篇文章有用之前,一个基本的要求是拥有一个用户控件(或表单),可以打印到整页上。一些小的控件在扩展到整页时会显得荒谬;一些在屏幕外滚动的大的控件在缩小以适合单个纸张时很可能无法辨认。但是,我介绍的基本技术应该为您提供关于您可能如何处理这些情况的线索。

使用代码

打印缩放对象实际上是相当简单的...一旦您已经知道如何操作。

所有自定义打印的基本概念是使用来自 PrintDocumentPrintPage 事件,该事件可能由您的表单拥有。在您的事件处理程序中,您可以调用自定义控件类的某个方法,您可以在其中封装控件可能拥有的任何特殊需求。

在我的表单中,我有一个属性 CurrentReportControl,它指向当前查看的报告,因此我的 PrintPage 事件处理程序看起来像这样

/// <summary>
/// Print document wants to print a page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
  CurrentReportControl.PrintToGraphics(e.Graphics, e.MarginBounds);
}

PrintPageEventArgs 对象提供了一个 Graphics 对象,您可以在其上绘制任何您想要的内容,并且它还定义了页面边距。我将这些传递给自定义控件的 PrintToGraphics() 方法。

此方法将控件绘制到 Bitmap,然后使用适当的缩放将位图绘制到 Graphics 对象。注意要最大程度地使用打印页面,而不会更改控件在屏幕上查看的纵横比

/// <summary>
/// Print the control's view to a Graphics object.
/// </summary>
/// <param name="graphics">Graphics object to draw on.</param>
/// <param name="bounds">Rectangle to print in.</param>
public void PrintToGraphics(Graphics graphics, Rectangle bounds)
{
  Bitmap bitmap = new Bitmap(this.Width, this.Height);
  this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
  Rectangle target = new Rectangle(0, 0, bounds.Width, bounds.Height);
  double xScale = (double)bitmap.Width / bounds.Width;
  double yScale = (double)bitmap.Height / bounds.Height;
  if (xScale < yScale)
    target.Width = (int)(xScale * target.Width / yScale);
  else
    target.Height = (int)(yScale * target.Height / xScale);
  graphics.PageUnit = GraphicsUnit.Display;
  graphics.DrawImage(bitmap, target);
}

关注点

我发现自己被一个有趣的话题分散了注意力,那就是 Graphics.PageUnit 属性,它定义了不同图形对象的各种缩放,例如显示、打印机等。

历史

  • 1.0 - 第一个版本。
© . All rights reserved.