vendredi 4 juillet 2008

Printing again and again

If you misplaced your ruler, here's an application that will create one for you on your printer! Unfortunately, you'll still need a ruler the first time using it so that you can calibrate the measurement for your particular printer, but once you know the calibration value, you are all set with a fairly accurate ruler.  Below is the simple design of our ruler.  The ruler itself is drawn in a Form.  The only other class used is the Calibration Dialog used to enter and retrieve a calibration value:

Figure 1 - Part of the ruler

This design was reverse engineered using the WithClass 2000 UML Design Tool for C#

The ruler is created by simply determining the resolution in pixels per inch.  This information can be retrieved from the graphics object itself:

void SizeFormToRuler()
// get resolution, most screens are 96 dpi, but you never know...
Graphics g = this.CreateGraphics();
this.HRes = g.DpiX; // Horizontal Resolution
this.VRes = g.DpiY; // Vertical Resolution
Width = (int)HRes;
Height = (
int)VRes * 11;
Left = 250;
Top = 5;

The actual tick marks and numbers are drawn
in the Form_Paint event handler method. This method establishes a Ruler Height in inches and then calls the method to draw the ruler:

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
Graphics g = e.Graphics;
RulerHeight = 11;

The DrawRuler method
is the heart of the application. It draws the tick marks and numbers and spaces them according to the number of pixels in an inch (+ a calibration value to make the inch measurement accurate). The Modulus Function is used to determine when its appropriate to draw a particular tick mark. For example when i modulus PixelsPerInch is equal to 0, then we've found an inch marker.

private void DrawRuler(Graphics g)
g.DrawRectangle(Pens.Black, ClientRectangle);
g.FillRectangle(Brushes.White , 0, 0, Width, Height);
float PixelsPerInch = VRes + (float)Calibration;
int count = 1;
//cycle through every pixel in the ruler at 1/16 pixel intervals
// Mark the appropriate tick values
for (float i = 1; i < (float)PixelsPerInch*RulerHeight + 10; i += 0.0625f)
// use the modulus function to determine what type of tick to use
if ((i % (PixelsPerInch)) == 0)
g.DrawLine(Pens.Black, 0, i, 25, i);
// Draw a Number at every inch mark
g.DrawString(count.ToString(), TheFont, Brushes.Black, 25, i, new StringFormat));count++;
else if (((i*2) % ((PixelsPerInch))) == 0)
g.DrawLine(Pens.Black, 0, i, 20, i);
else if (((i*4) % ((PixelsPerInch))) == 0)
g.DrawLine(Pens.Black, 0, i, 15, i);
else if (((i*8) % ((PixelsPerInch))) == 0)
g.DrawLine(Pens.Black, 0, i, 10, i);
else if (((i*16) % ((PixelsPerInch))) == 0)
g.DrawLine(Pens.Black, 0, i, 5, i);

The calibration value is retrieved by using the calibration dialog.  This dialog brings up a NumericUpDown control for choosing the number of pixels to offset the inch.  The offset can be a negative or positive number of pixels depending upon how your printer is off.  I found my printer was off by 4 pixels too small, so my calibration was +4.  Below is the calibration dialog:

Fig 3  - Ruler Calibration Dialog

The Calibration Dialog uses ShowDialog to display the form and retrieves the Calibration Value in the CalibrationValue property of the dialog:

private void CalibrationMenu_Click(object sender, System.EventArgs e)
// Create Calibration Dialog
CalibrationForm dlg = new CalibrationForm();
// Set the initial Calibration Value
dlg.CalibrationValue = Calibration;
// Show the dialog and retrieve the Calibration Value
if (dlg.ShowDialog() == DialogResult.OK)
Calibration = dlg.CalibrationValue;
// write the value out to a file to remember for next time

Printing the ruler
is accomplished using 3 different print controls: The PrintDocument, The PrintDialog, and the PrintPreviewDialog control. Once you've dropped these controls on your form and assigned the PrintDocument Instance to the corresponding Document properties in the PrintDialog and the PrintPreviewDialog, it's fairly easy to set up printing. Below is the routine for PrintPreview. As you can see there is not really much to it.

private void PrintPreviewMenu_Click(object sender, System.EventArgs e)

is not much more complicated. Simply open the PrintDialog and once the user has assigned properties, call the Print method on the PrintDocument:

private void PrintMenu_Click(object sender, System.EventArgs e)
if (printDialog1.ShowDialog() == DialogResult.OK)

The actual printing occurs
in the PrintDocument's PrintPage Event Handler. This is where you put all the GDI routines for drawing the ruler. You can actually use the same drawing routines in your print handler as you do for your Paint Handler. Your just passing in a Printer Graphics Object instead of a Screen Graphics object:

private void printDocument1_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
Graphics g = e.Graphics;
PageSettings ps = e.PageSettings;
// Set the ruler height based on the Page Settings of the printer
// That way you can have a larger ruler for a larger piece of paper
RulerHeight = (int)(ps.Bounds.Height/100.0);

We've also added persistence to this application to remember the calibration value. The two routines below read and write the calibration value using the StreamReader and StreamWriter classes:

void ReadCalibration()
// Determine the path of the file from the application itself
string calfile = Application.StartupPath + @"\cal.txt";
// If the calibration file exists, read in the initial calibration value
if (File.Exists(calfile))
StreamReader tr =
new StreamReader(calfile);
string num = tr.ReadLine();
Calibration = Convert.ToInt32(num);
void WriteCalibration()
string calfile = Application.StartupPath + @"\cal.txt";
treamWriter tw =
new StreamWriter(calfile);
// Write out the calibration value


This control could be improved by adding a metric ruler option.  This is easy enough to accomplish simply by figuring out the pixels per centimeter and then using modulus 10 to get the millimeters.  Also a large ruler can be created by printing to multiple pages.  I'm sure you can think of some other ideas with a little measured thought

Alain Lompo
Excelta - Conseils et services informatiques
MCSD For Microsoft .Net
MVP Windows Systems Server / Biztalk Server
Certifié ITIL et Microsoft Biztalk Server

Aucun commentaire: