[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Print images in C#

[Print images in C#]

This example shows a simple way to print images. When you print, the PrintDocument object's PrintPage event handler provides a Graphics object named e.Graphics. That object's DrawImage method can draw a picture on the printed surface.

To print an image, simply use DrawImage to print it. The following code shows how this example prints images.

// Print an image. private void pdocImage_PrintPage(object sender, PrintPageEventArgs e) { // Print in the upper left corner at its full size. e.Graphics.DrawImage(picImage.Image, e.MarginBounds.X, e.MarginBounds.Y, picImage.Image.Width, picImage.Image.Height); // Print in the upper right corner, // sized to fit beside the other image. int left = e.MarginBounds.Left + picImage.Image.Width; int width = e.MarginBounds.Width - picImage.Image.Width; float scale = width / (float)picImage.Image.Width; int height = (int)(picImage.Image.Height * scale); e.Graphics.DrawImage(picImage.Image, left, e.MarginBounds.Y, width, height); // Print the same size in the lower right corner. int top = e.MarginBounds.Bottom - height; e.Graphics.DrawImage(picImage.Image, left, top, width, height); }

This code uses DrawImage three times to print the image in three places at different sizes.

This code specifies the X and Y coordinate for the upper left corner where you want the image drawn and the image's width and height. You can get more explicit control if you use Rectangle structures to specify the part of the image to draw and the location where you want it drawn. If the source and destination Rectangle structures have different aspect ratios (width-to-height ratios), DrawImage stretches the image to fit the destination area.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.