Printing the Picture
Printing the Picture
Language: VB.NET
Author: Aamir Mustafa
E-Mail: aamir_mustafa2007@msn.com
Introduction:
I was looking different methods how to print a picture, so I have one way.
This article will show simple method to print the picture
How to Print:
Create an empty project
On the form, add a menu bar and change its name to File
Below File menu, add these menus
mnuOpen
mnuPageSetup
mnuPrint
So we have following shape
Fileà Open, Page Setup, Print
After adding the menus
Go to Toolbox and go to Printing section and add following controls
PageSetupDialog1
We are using for setting page set up
PrintDocument1
We are using for printing document
PrintPreviewDialog1
We are using for take preview of our print
After adding all these controls, add a picture box to the form
Now we are going to add code
First of all add following code to Open menu
We will use it for opening a picture from disk
Code:
Private Sub mnuOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuOpen.Click
Try
Dim openFileDlg As New OpenFileDialog
openFileDlg.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"
With openFileDlg
.CheckFileExists = True
.ShowReadOnly = False
.Filter = "All Files|*.*|Bitmap Files (*)|*.bmp;*.gif;*.jpg"
.FilterIndex = 2
If .ShowDialog = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(.FileName)
End If
End With
Catch ex As Exception
MessageBox.Show("Can not open file")
End Try
End Sub
After adding above code , add following code in Page setup menu
We are using it for setting page setup
Code:
Private Sub mnuPageSetup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PageSetupToolStripMenuItem.Click
PageSetupDialog1.Document = PrintDocument1
PageSetupDialog1.ShowDialog()
End Sub
Now we will add code in Print event click
Code:
Private Sub mnuPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintToolStripMenuItem.Click
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub
At the end we will add code behind PrintPage event of PrintDocument1
So double click on it on the form or access its PageEvent in code editor and add following code
Code:
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
e.Graphics.DrawImage(Me.PictureBox1.Image, 0, 0, Me.PictureBox1.Width, Me.PictureBox1.Height)
End Sub
In the above code we are using DrawImage method of Graphics
DrawImage has five arguments
First argument which we pass is image, so here we are passing here our picture
Next argument is the x location of image and next location is y
Third is width of image, we are setting our picture width and so next is height of our image.