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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With