views:

20

answers:

1

I'm trying to print an image sized 2x2 inches. Created a conversion function (inches to pixels) based on the resolution. However, the result is far from 2x2 inch, printing produces image that barely fits the whole sheet! Am I'm doing something wrong?

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

    Dim graph = e.Graphics
    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
    e.Graphics.CompositingQuality = Drawing2D.CompositingQuality.HighQuality


    Dim photo = Image.FromFile("C:\Users\Public\Pictures\Sample Pictures\Koala.jpg")
    graph.DrawImage(photo, New RectangleF(0, 0, InchToPx(graph.DpiX, 2), InchToPx(graph.DpiY, 2)))

End Sub


Private Function InchToPx(ByVal dpi As Single, ByVal inches As Single) As Single

    Return (inches * dpi)

End Function
+2  A: 

Yes, that's not the right way to do it. Graphics.Dpix will return the resolution of the printer, commonly 600 dots per inch. But what you draw is resolution independent. So that you don't have to do anything special when the user selects another printer with, say, a 300 dpi resolution. Important because otherwise your document would be twice as large and no longer fit the paper.

The resolution independent mapping is determined by Graphics.PageUnit. The default is Display which makes one pixel 0.01 inches. In other words, to get a 2 by 2 inch printout, you simply use a rectangle of 200 x 200. You can change the PageUnit if you really want to, Inches is one of the settings. You'd then use a 2x2 rectangle. You of course then have to use the Graphics method overloads that take a PointF and a RectangleF, the integer versions won't work well.

The default (Display) is convenient because it makes what you draw on the screen about the same size as what you draw on the printer. Because a common resolution for the display is 96 dpi, close enough to 1 pix == 0.01". Allowing you to re-use code that draws stuff to the screen to draw to the printer as well.

Hans Passant
*a common resolution for the display is 96 dpi* >> note that this is indeed *common*, but that many people (esp with sight-problems) have set this to 120 dpi or higher and that the Mac (not a likely candidate for .NET perhaps, but still, Silverlight runs on Mac) uses 72 dpi by default. Also, *"same size"* is relative only, pixel sizes on screens vary widely. PS: +1 good answer!
Abel