将Windows.Forms.WebBrowser内容传递给PrintDocument

时间:2014-04-25 11:45:05

标签: vb.net visual-studio-2010 .net-4.0

Visual Studio 2010,Visual Basic.NET

我在表单上有一个WebBrowser控件(wbImages),我需要允许用户打印该WebBrowser控件的内容。如果我使用wbImages.Print(),它将打印文档,但只使用默认打印机。所以我想打开打印对话框以允许用户更改打印机。不幸的是我不知道如何将wbImages的内容转换为PrintDocument。

这是我现在拥有的。

Private Sub PrintToolStripMenuItem_Click(sender As System.Object, _ 
        e As System.EventArgs) Handles PrintToolStripMenuItem.Click

    'I need to get the wbImages into pdocImages
    'pdocImages = ConvertPrintDoc(wbImages)

    pdImages.Document = pdocImages
    pdImages.PrinterSettings = pdocImages.PrinterSettings
    pdImages.AllowSomePages = True
    If pdImages.ShowDialog = DialogResult.OK Then
        pdocImages.PrinterSettings = pdImages.PrinterSettings

        If imageUrl.IndexOf(".jpg") <> -1 Or imageUrl.IndexOf(".gif") <> -1 Then
            MessageBox.Show("Image has been sent to the printer.")
            wbImages.Print()
        Else
            MessageBox.Show("Table has been sent to the printer.")
            wbImages.Print()
        End If

    End If

End Sub

1 个答案:

答案 0 :(得分:2)

此方法会将Web浏览器中当前可见的内容绘制到位图中,然后打印:

Private Sub PrintToolStripMenuItem_Click(sender As System.Object, _ e As System.EventArgs)  Handles PrintToolStripMenuItem.Click
    PrintDocument1.Print()
End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    e.Graphics.DrawImage(TakeSreenShot(WebBrowser1), 0, 0)
End Sub

Private Function TakeScreenShot(ByVal Control As Control) As Bitmap
    Dim tmpImg As New Bitmap(Control.Width, Control.Height)
    Using g As Graphics = Graphics.FromImage(tmpImg)
        g.CopyFromScreen(Control.PointToScreen(New Point(0, 0)), New Point(0, 0), New Size(Control.Width, Control.Height))
    End Using
    Return tmpImg
End Function

显然它只会打印当前可见的内容,这是一个缺点,但我不知道其他任何方式。

希望这会有所帮助。