Reputation: 2428
I'm trying to figure out how to draw shapes onto a PrintDocument
and a form that are a specific size in inches. I'm confused about the DPI of the PrintDocument
This is what I started with:
private void DrawShapes(Graphics graphics)
{
graphics.DrawRectangle(new Pen(Color.HotPink), new Rectangle(0, 0, (int)Math.Round(1 * graphics.DpiX), (int)Math.Round(1 * graphics.DpiY)));
graphics.DrawRectangle(new Pen(Color.HotPink), new Rectangle(0, 0, (int)Math.Round(1.5 * graphics.DpiX), (int)Math.Round(1.5 * graphics.DpiY)));
graphics.DrawRectangle(new Pen(Color.HotPink), new Rectangle(0, 0, (int)Math.Round(2 * graphics.DpiX), (int)Math.Round(2 * graphics.DpiY)));
graphics.DrawRectangle(new Pen(Color.HotPink), new Rectangle(0, 0, (int)Math.Round(2.5 * graphics.DpiX), (int)Math.Round(2.5 * graphics.DpiY)));
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawShapes(e.Graphics);
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
DrawShapes(e.Graphics);
}
This worked well for the Graphics
object from the OnPaint
function but the print out was wrong. I did some debugging and found that the DPI of the Graphics
object from the PrintPage
event is large (600 when I ran the code) but the bounds of the page are 850 by 1100. So I tried using a DPI of 100 when printing and used the graphics' DPI when drawing to the form. This worked perfectly.
What I don't get is how the PrintDocument
deals with DPI. Does the PrintDocument
always have a true DPI of 100 even though the Graphics
object from the PrintPage
event says it has a different DPI? Would I run into problems if I assume 96dpi when drawing to a form and 100dpi when printing?
Upvotes: 1
Views: 2718
Reputation: 942408
The Graphics object you get in your PrintPage event handler was initialized with the Graphics.PageUnit property set to GraphicsUnit.Display
. That ensures your output is scaled to whatever the printer resolution might be, a line you draw 100 'pixels' long will be one inch on paper. It doesn't matter if you use a 300 or 600 dpi printer. Note how your paper size of 850 x 1100 was 8.5 x 11 inches, standard in the USA.
This choice wasn't accidental, it is close to the default dpi of the monitor. So code that draws to the screen can also be used to draw to the printer. And will be about the same size on paper, even though a printer has a much higher resolution. There is rarely a reason to change this setting.
Upvotes: 1