Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print in .NET - Conversion from millimeter to pixel

Tags:

c#

printing

How can I convert user input from millimeter to pixels so that it's printed on the right position of the page?

I use the following code:

private void document_PrintPage(object sender, PrintPageEventArgs e)
{
    float dpiX = e.Graphics.DpiX;
    float dpiY = e.Graphics.DpiY;
    Point p = new Point(mmToPixel(float.Parse(edtBorderLeft.Text), dpiX), 
            mmToPixel(float.Parse(edtBorderTop.Text), dpiY));
    e.Graphics.DrawImage(testImage, p);

}

private int mmToPixel(float mm, float dpi)
{
    return (int)Math.Round((mm / 25.4)  * dpi);
}

edtBorderLeft.Text got the value of "9.5" and edtBorderTop.Text the value of "21,5". These values are millimeters. If I check the output with this code:

    private void printPage()
    {
        PrintDialog dialog = new PrintDialog();
        dialog.Document = document;
        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            PrintPreviewDialog preview = new PrintPreviewDialog();
            preview.Document = document;
            preview.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            preview.Show();
            //document.Print();
        }            
    }

It displays the image nearly in the center of the page. A calculation example:

mmToPixel(float.Parse(edtBorderLeft.Text), dpiX) edtBorderLeft.Text = "9.5" dpiX = 600; returns: 224

How can I calculate the right point for the printed image?

like image 601
hitzi Avatar asked Oct 11 '11 07:10

hitzi


2 Answers

I found a solution. You can change the page unit with the following code. So I don't need a conversion:

 e.Graphics.PageUnit = GraphicsUnit.Millimeter;

or

e.Graphics.PageUnit = GraphicsUnit.Pixel;

and I can use the code above.

like image 179
hitzi Avatar answered Nov 15 '22 00:11

hitzi


Just to add a little explanation. By default Graphics.PageUhit is set to "Display". For a screen display this usually means 96 pixels per inch, for a printer it is 100 dots per inch. This info is buried in MSDN somehwere but is hard to find.

Therefore for a printer, instead of using dpiX/dpiY you could assume a value of 100, but it is probably safer to set the units to millimeters.

like image 31
bobc Avatar answered Nov 15 '22 00:11

bobc