views:

865

answers:

3

Hello!

I'm trying to measure height of some text for table printing purpose.

Here's the code. In my case it prints different numbers in preview and on actual page. I can't try on any printers other than Microsoft Office Document Image Writer right now, but I'm pretty sure it isn't a printer issue.

Perhaps somebody have found a workaround for this problem?

    private void button1_Click(object sender, EventArgs e)
    {
        Print();
    }

    public void Print()
    {
        PrintDocument my_doc = new PrintDocument();
        my_doc.PrintPage += new PrintPageEventHandler(this.PrintPage);

        PrintPreviewDialog my_preview = new PrintPreviewDialog();
        my_preview.Document = my_doc;

        my_preview.ShowDialog();

        my_doc.Dispose();
        my_preview.Dispose();
    }

    private void PrintPage(object sender, 
       System.Drawing.Printing.PrintPageEventArgs e)
    {
        e.Graphics.PageUnit = GraphicsUnit.Pixel;

        string s = "String height is ";

        SizeF h = e.Graphics.MeasureString(s, new Font("Arial", 24));

        e.Graphics.DrawString(s + Convert.ToString(h.Height), 
           new Font("Arial", 24), new SolidBrush(Color.Black), 1, 1);
    }
A: 

Try a PageUnit other than Graphics.Pixel in your PrintPage event. Inch, Millimeter or Point (among others) should give you the same result in Preview or printed out. Pixel I would expect not to, since the preview screen and the printer have different pixel resolutions.

MusiGenesis
A: 

Thanks for you answer.

I've tried all PageUnits available but it made no difference. Preview height to print height ratio is about 1.029336 and it is constant.

With best regards, idn.

PS. Actually I've found workaround. I use MeasureString to count number of lines and then multiply it by character height, derived from Font class, to count height of the text chunk. It works nicely with some tweaking.

Just curious: does the preview-height-to-print-height ratio stay exactly at 1.029336 if you try font sizes other than 24?
MusiGenesis
Actually it changes slightly, in seventh digit after decimal point. Perhaps it's rounding errors.
+1  A: 

I guess that the problem is that System.Drawing.Graphics is based on GDI+ where as the actual printing is based on GDI.

You could replace the call to MeasureString to use a GDI based method:

SizeF hT = TextRenderer.MeasureText(s, new Font("Arial", 24));

The System.Windows.Forms.TextRenderer class was developed to provide the same level of support for complex scripts in Windows Forms controls that we expect from the Windows operating system. This TextRenderer is based on the GDI text-rendering API, which uses the Windows Unicode Script Processor (Uniscribe). [from MSDN]

For further details see this good article from MSDN magazine on text rendering:

Text Rendering: Build World-Ready Apps Using Complex Scripts In Windows Forms Controls

0xA3