将页眉和页脚添加到Printing.PrintDocument(.Net 2.0)的最简单方法?

时间:2020-03-05 18:52:17  来源:igfitidea点击:

实用或者在设计时向.Net PrintDocument对象添加页眉和页脚的最简单方法是什么?

具体来说,我正在尝试打印一个第三方网格控件(Infragistics GridEx v4.3),该控件需要一个PrintDocument对象并将其自身绘制到其中。

生成的页面仅包含网格及其内容,但是我想添加页眉或者标题以标识打印的报告,并可能添加页脚以显示打印的人,时间以及理想的页码和总页数。

我正在使用VB.Net 2.0。

谢谢你的帮助!

解决方案

回答

printdocument对象为每个要打印的页面触发printpage事件。我们可以使用printpageeventargs事件参数将文本/行/等绘制到打印队列中:

http://msdn.microsoft.com/zh-CN/library/system.drawing.printing.printdocument.aspx

将其传递到网格时,将其随事件一起变暗,以便我们可以处理事件。

回答

按照booji-boy的回答,这是我想出的内容(出于示例目的已将其简化):

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click

        Dim oDoc As New Printing.PrintDocument
        oDoc.DefaultPageSettings.Landscape = True
        AddHandler oDoc.PrintPage, AddressOf PrintPage

        oDoc.DocumentName = "Printout"

        InfragisticsWinGrid.PrintPreview(InfragisticsWinGrid.DisplayLayout, oDoc)

    End If
End Sub

Private Sub PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)

    ' Draw title
    e.Graphics.DrawString("Report Title"), New Font("Arial", 16), Brushes.Black, 95, 70)

    ' Draw footer
    e.Graphics.DrawImage(DirectCast(mResources.GetObject("footer_logo"), Drawing.Bitmap), 95, e.PageBounds.Height - 87)
    Dim drawFont As New Font("Arial", 8.75)

    e.Graphics.DrawString("Report Title", drawFont, Brushes.Gray, 190, e.PageBounds.Height - 90)
    e.Graphics.DrawString("Printed", drawFont, Brushes.Gray, 190, e.PageBounds.Height - 76)
    e.Graphics.DrawString("Printed By", drawFont, Brushes.Gray, 190, e.PageBounds.Height - 62)

    ' Draw some grid lines to add structure to the footer information
    e.Graphics.DrawLine(Pens.Gray, 246, e.PageBounds.Height - 90, 246, e.PageBounds.Height - 48)
    e.Graphics.DrawLine(Pens.Gray, 188, e.PageBounds.Height - 75, 550, e.PageBounds.Height - 75)
    e.Graphics.DrawLine(Pens.Gray, 188, e.PageBounds.Height - 61, 550, e.PageBounds.Height - 61)

    e.Graphics.DrawString("Report", drawFont, Brushes.Black, 250, e.PageBounds.Height - 90)
    e.Graphics.DrawString(Date.Now.ToShortDateString & " " & Date.Now.ToShortTimeString, drawFont, Brushes.Black, 250, e.PageBounds.Height - 76)
    e.Graphics.DrawString("Andrew", drawFont, Brushes.Black, 250, e.PageBounds.Height - 62)

End Sub

我必须使用e.PageBounds.Height x的值来使绘制的项目排成一行。

再次感谢Booji Boy到达ReportPage.Graphics()的指针正是我在:o)之后得到的