Line height measured using MeasureString in PrintPreviewDialog is different than the height in real print

I am trying to measure the height of some text for printing purposes. A.

Here is the code. In my case, it prints different numbers in the preview and on the actual page. I cannot try on any printers except Microsoft Office Document Image Writer, but I am sure that this is not a problem with the printer.

Perhaps someone 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);
    }
+3
source share
4 answers

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

You can replace the call to MeasureString with a GDI-based method:

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

System.Windows.Forms.TextRenderer Windows Forms , Windows . TextRenderer API- GDI, Windows Unicode Script (Uniscribe). [ MSDN]

. MSDN :

: World-Ready Windows Forms

+1

PageUnit, Graphics.Pixel, PrintPage. , ( ) Preview . Pixel, , .

0

PageUnits, . 1,029336, .

PS. . MeasureString , , Font, . .

0

, ... , , .

The problem is the distance between the characters. If you use, for example, the word "VA" when printing it (or when you use "Graphics.FromImage"), the letter "A" begins immediately after the letter "V" ... In "PrintPreview", the letter "A" begins only inside the letter " V "... If you add individual letters to" PrintPreview ", you will achieve the same print result!

0
source

All Articles