Print in .NET - Conversion from millimeter to pixel

ぐ巨炮叔叔 提交于 2019-12-10 05:53:24

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7722809/print-in-net-conversion-from-millimeter-to-pixel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!