Printing a file from a form

ucp8

Active member
Joined
Feb 9, 2009
Messages
28
Programming Experience
3-5
Hi guys,

Does anybody know how to Print a .jpg file from withing a vb.net form? I spent a while looking over code example on google but it all seems really complex. I just want the ability to print a small picture out by opening the general print dialog window. Does anyone know how this can be achieved or do they know of any sites that would help? I am trying to avoid a seperate print class here.

Thanks for your help
 
Drag a PrintDocument to the form, doubleclick it and add code to the PrintPage event, for example this draws an image:
VB.NET:
e.Graphics.DrawImage(img, e.MarginBounds.Location)
img is an Image, for example a variable you have defined and assigned an image.
VB.NET:
Private img As Image
To print call the Print method. Perhaps you then also assigned the image here?
VB.NET:
img = Image.FromFile("filename.jpg")
PrintDocument1.Print()
ucp8 said:
I just want the ability to print a small picture out by opening the general print dialog window.
This is not clear to me, what is "the general print dialog window" ? Look in the Printing section of Toolbox to find several dialogs designed to work with the PrintDocument.

By the way, I moved this thread to Printing forum, please post in most appropriate forum regarding the topic of your request. Visual Studio General Discussion it was not.
 
Thanks for your help. I was able to print out the page. This lead to another problem though.

When I close the form, I have to delete the files that I have created. This occurs in the PupilMainResultsGraphForm_FormClosing method. When I try to delete the .jpg file, I get an exception telling me that the image is being used by another process.

I have looked at the currently running processes and have tried to switch off the ones that I belive is causing the problem but have had no luck as of yet.

The Exception I get is:

ImageShack - Image Hosting :: exceptiont.jpg

Would anyone know what process may still be open here and is causing the exception? If needs be I can take screen dumps to show the current processes that are running.

Here is my code:

VB.NET:
Imports Excel = Microsoft.Office.Interop.Excel


Public Class PupilMainResultsGraphForm
    ' Create Excel objects
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    ' Create Image object
    Dim img As Image

    Private Sub PupilMainResultsGraphForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Instantiate excel objects
        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")

        ' Create first cell blank
        xlWorkSheet.Cells(1, 1) = ""
        For i = 0 To ArrayListDates.Count - 1
            ' Add date headings
            xlWorkSheet.Cells(1, i + 2) = "" + ArrayListDates(i).ToString ' "Date" + i.ToString
        Next

        ' Add Results heading
        xlWorkSheet.Cells(2, 1) = "Results"
        For k = 0 To ArrayListResults.Count - 1
            ' Add results
            xlWorkSheet.Cells(2, k + 2) = "" + ArrayListResults(k).ToString
        Next

        ' Create chart
        Dim chartPage As Excel.Chart
        Dim xlCharts As Excel.ChartObjects
        Dim myChart As Excel.ChartObject
        Dim chartRange As Excel.Range

        ' Apply chart settings
        xlCharts = xlWorkSheet.ChartObjects
        myChart = xlCharts.Add(10, 80, 300, 250)
        chartPage = myChart.Chart
        chartRange = xlWorkSheet.Range("A1", "K2")
        chartPage.SetSourceData(Source:=chartRange)
        chartPage.ChartType = Excel.XlChartType.xlColumnStacked

        Try
            ' Save Excel Worlbook
            xlWorkSheet.SaveAs("C:\Users\andrew\Desktop\Software engineering project\SchoolTestProgram\images\" + pupilUser.ToString + "ResultsGraph.xlsx")

            ' Export chart as picture file
            xlWorkSheet.ChartObjects(1).chart.Export(FileName:="C:\Users\andrew\Desktop\Software engineering project\SchoolTestProgram\images\" + pupilUser.ToString + "ResultsGraph.jpg", FilterName:="JPG")

            ' Set PBoxGraph
            PBoxGraph.ImageLocation = "C:\Users\andrew\Desktop\Software engineering project\SchoolTestProgram\images\" + pupilUser.ToString + "ResultsGraph.jpg"

            ' Close Excel objects
            xlWorkBook.Close()
            xlApp.Quit()
        Catch ex As Exception
            MsgBox("Exception: " + ex.ToString)
        End Try

        ' Realese the excel objects
        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)
    End Sub

    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

    Private Sub PupilMainResultsGraphForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        ' Delete the files to avoid any problems that occur when the file already exists. This will also ensure that
        ' you are getting the most up-to-date files every time you open the graph
        Dim FileToDelete As String
        Dim PictureFileToDelete As String

        FileToDelete = "C:\Users\andrew\Desktop\Software engineering project\SchoolTestProgram\images\" + pupilUser.ToString + "ResultsGraph.xlsx"
        PictureFileToDelete = "C:\Users\andrew\Desktop\Software engineering project\SchoolTestProgram\images\" + pupilUser.ToString + "ResultsGraph.jpg"

        If System.IO.File.Exists(FileToDelete) = True Then  
            System.IO.File.Delete(FileToDelete)
        End If

        ' Kill EXCEL processes to try and avoid exceptions when closing
        Dim myProcesses() As Process
        Dim myProcess As Process
        ' Return array containing all instances of "EXCEL".
        myProcesses = Process.GetProcessesByName("EXCEL")
        For Each myProcess In myProcesses
            myProcess.Kill()
        Next
        ' Kill ONENOTE processes to try and avoid exceptions when closing
        Dim myProcesses2() As Process
        Dim myProcess2 As Process
        ' Return array containing all instances of "ONENOTEM".
        myProcesses2 = Process.GetProcessesByName("ONENOTEM")
        For Each myProcess2 In myProcesses
            myProcess2.Kill()
        Next

        Try
            If System.IO.File.Exists(PictureFileToDelete) = True Then
                System.IO.File.Delete(PictureFileToDelete)
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
            Exit Sub
        End Try
        
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        ' Set PrintDialog1 print settings
        PrintDialog1.Document = PrintDocument1
        PrintDialog1.PrinterSettings.Copies = 1
        PrintDialog1.PrinterSettings.DefaultPageSettings.Landscape = True

        ' Set Image
        img = Image.FromFile("C:\Users\andrew\Desktop\Software engineering project\SchoolTestProgram\images\" + pupilUser.ToString + "ResultsGraph.jpg")

        'OpenAccess PrintDialog1
        If PrintDialog1.ShowDialog = DialogResult.OK Then
            PrintDocument1.Print()
        End If
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        ' Inform the printer of the image that is to be prited
        e.Graphics.DrawImage(img, e.MarginBounds.Location)
        img = Nothing
    End Sub

    Private Sub btnReturnToMain_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReturnToMain.Click
        ' Close graph form and allow access to main pupil form
        Me.Close()
    End Sub
End Class
 
Last edited:
img = Nothing won't do you any good, img.Dispose() it is.
 
Thank you so much JohnH. I spent the past four hours playing around with that, and the solution was so simple in the end. I was on the right track, just went about it the wrong way. Cheers!
 
Back
Top