Introduction
This piece of code prepare an image from image box to a print by using an instance of
PrintDocument
. This snippet has been written after I try to find a solution to print pictures on Windows printer without distortion twice per year. So I position it as a memo sticker.
Background
You should be smart enough to:
- Create and design a Windows form with
PictureBox
- Place a
PrintDocument
and optional
PrintPreview
dialog on this form - Set an event handler that
intercepts
PrintPage
event of PrintDocument
Using the code
I need to print images on some legacy media. So I've got three issues:
- I've got only Windows driver for the printer
- I have to use print area precisely
- I've got two phase printing (because of the
colored ribbon)
This code has been written as a C# implementation. You can be smarter, of
course, and try to use this code in the other places.
So the printing code looks like this:
Graphics gPrn = e.Graphics;
PageSettings pageSettings = e.PageSettings;
float px = 0;
float py = 0;
float scaleFactorX, scaleFactorY;
RectangleF r;
RectangleF rs;
float dpi_div = 100.0F;
px = pageSettings.PrinterResolution.X / dpi_div;
scaleFactorX = pageSettings.PrinterResolution.X / pictureBox1.Image.HorizontalResolution;
py = pageSettings.PrinterResolution.Y / dpi_div;
scaleFactorY = pageSettings.PrinterResolution.Y / pictureBox1.Image.VerticalResolution;
r = new RectangleF(pageSettings.PrintableArea.Left * px,
pageSettings.PrintableArea.Top * py,
((float)pictureBox1.Width), ((float)pictureBox1.Height));
rs = new RectangleF(pageSettings.PrintableArea.Left * px,
pageSettings.PrintableArea.Top * py,
r.Width * scaleFactorX,
r.Height * scaleFactorY);
pageSettings.Margins.Top = 0;
pageSettings.Margins.Left = 0;
gPrn.DrawImage(pictureBox1.Image, r, rs, GraphicsUnit.Pixel);
After I can to win autosave I will try to mark variable names. For now it
prevents me to mark them (reset my weak attempts).
Points of Interest
The most important point from, that I've learned from this code: Screen's resolution for now is less detailed than printer's one.
And this must be remembered.
History
- The article created at 17:30 (MSK) October 7 in the year of 2013.