After struggling in a couple of days, I find the best solution for it without having to call P/Invoke (to obtain hard margin) as other people did. PageSettings exposes HardMargin to ease our life.
Since e.MarginBounds is measured relative from upper left corner of printable area (rather than the edge of actual page), we must move e.MarginBounds using HardMargin point as an offset.
Note that: both MarginBounds and HardMargin are measured in hundredths of an inch.
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.PageUnit = GraphicsUnit.Inch;
Image img = new Bitmap(@"c:\Sunset.jpg");
Graphics gg=Graphics.FromImage(img);
RectangleF marginBounds = e.MarginBounds;
if(!pd.PrintController.IsPreview)
marginBounds.Offset(-e.PageSettings.HardMarginX,
-e.PageSettings.HardMarginY);
float x = marginBounds.X / 100f +
(marginBounds.Width / 100f -
(float)img.Width / gg.DpiX) / 2f;
float y = marginBounds.Y/ 100f +
(marginBounds.Height / 100f -
(float)img.Height / gg.DpiY) / 2f;
g.DrawImage(img,x,y);
//Don't call g.Dispose(). Operating System will do this job.
gg.Dispose();//You should call it to release graphics object immediately.
}
Andi Setiawan
visual_cpp@programmer.net