Printing the Chart As-Is
Let's take the simplest case and print the chart that the user can see on the screen (but which we know consists of two PictureBoxes side by side). The obvious way of approaching this is to merge the images of the two PictureBoxes into one single image and then Draw this image to the printer.
The following procedure will merge two images that are passed in as parameters:
Public Function MergeImages(ByVal Pic1 As Image, ByVal pic2 As Image) As Image
Dim MergedImage As Image ' This will be the finished merged image
Dim Wide, High As Integer ' The Size of the merged image
' Calculate Width and Height needed for composite image Width:
Wide = Pic1.Width + pic2.Width
' Height: Ensure that the new image is high enough for both images
' that we plan to place inside it.
' Not necessary in this case, but useful if you use the merge technique
' in future where the images are different heights.
If Pic1.Height >= pic2.Height Then
High = Pic1.Height
High = pic2.Height
' Create an empty Bitmap the correct size to hold both images side by side
Dim bm As New Bitmap(Wide, High)
' Get the Graphics object for this bitmap
Dim gr As Graphics = Graphics.FromImage(bm)
' Draw a black line round the outside (looks better when printed)
gr.DrawRectangle(Pens.Black, 0, 0, Wide - 1, High - 1)
' Draw the first source image at left side of new image
gr.DrawImage(Pic1, 0, 0)
' Draw second source image, offset to the right edge of first source image
gr.DrawImage(pic2, Pic1.Width, 0)
' Assign the merged bitmap you have just created as the image you are going
' to return for printing
MergedImage = bm
' Finished with the Graphics object
' You now have an Image named MergedImage which you can print.
Now that you have the means to create a merged image, you simply use the same approach as we did for the bar chart printout. That is, we use the PrintPage event of a PrintDocument control, get an image, create a rectangle of a suitable size and Draw the image within that rectangle on to the printer page.
Drag a PrintDocument control on to the form, name it "PrintImageDocument" and put this code in its PrintPage event. The code is very similar to the previous chart's example:
PrivateSub PrintImageDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintImageDocument.PrintPage
' First create the image using the function prepared above:
Dim ImageToPrint As Image = MergeImages(picValues.Image, picGraph.Image)
' Now Print it - change "20, 20" to whatever X and Y position values
' you want as your start point for printing on the page
Dim R As New Rectangle(20, 20, ImageToPrint.Width, ImageToPrint.Height)
If you place a button named BtnPrint on the form, you can use the following code in the Click event:
Private Sub BtnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPrint.Click