VB.NET: Printing Image with PrintDocument Control

Is it possible to print an image using  PrintDocument Control? Yes, it is.

Basic formula:

How does it work? I'll give you some samples. First sample will use an image from a file that its path is c:\logo.png. Let's set UI design. I added a button and a PrintDocument into a Form as below.


Code:
Imports System.Drawing.Printing
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PrintDocument1.Print()
    End Sub

    Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) _
                Handles PrintDocument1.PrintPage
        Dim newImage As Image = Image.FromFile("c:\logo.png")
        e.Graphics.DrawImage(newImage, 50, 50)
    End Sub
End Class

Run and click the button to print.


Result: (I'm using pdf printer)


What if the image is from a PictureBox control image?


You can simply change the image object with PictureBox Image property as below.

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) _
            Handles PrintDocument1.PrintPage
    e.Graphics.DrawImage(PictureBox1.Image, 50, 50)
End Sub

Run and result will similar:



The default setting will print the original size of the image. However, we can set manually the width and height of the image by syntax below.


Now, let's try to set image width = 100 and height = 50.

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) _
            Handles PrintDocument1.PrintPage
    e.Graphics.DrawImage(PictureBox1.Image, 50, 50, 100, 50)
End Sub

Run and result will be:


Read also other related articles:
Printing tutorial with PrintDocument Control


Post a Comment

0 Comments