Search code examples
wpfprintdialog

Set image position to page center


I'm trying to print an image in the center of the page but I can't come up with any idea.

System.Windows.Point printLocation = new System.Windows.Point(50,50);
printLocation.X = pageWidth - 50 / 2; 50 is the margin
imageViewer = ImagePrintAdapter.CreateImageFromBitmapImage(img,printLocation);
printerDialog.PrintVisual(imageViewer, "Identification");

This is the CreateImageFromBitmapImagemethod

public static System.Windows.Controls.Image CreateImageFromBitmapImage(BitmapImage imgSource, System.Windows.Point imgLocation)
 {
   System.Windows.Controls.Image imageViewer = new System.Windows.Controls.Image();
   imageViewer.BeginInit();
   imageViewer.Source = imgSource;

   imageViewer.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));
   imageViewer.Arrange(new System.Windows.Rect(imgLocation, imageViewer.DesiredSize));

   imageViewer.EndInit();
   imageViewer.UpdateLayout();

   return imageViewer;
}

If I set the printLocation.X to be the half of the pageWidth, shouldn't it start at the center ?


Solution

  • You may simply draw the image into a DrawingVisual and print it. The following simplified example assumes that the bitmap size is smaller than the printable area size:

    ImageSource image = ...
    
    var rect = new Rect(
        (printDialog.PrintableAreaWidth - image.Width) / 2,
        (printDialog.PrintableAreaHeight - image.Height) / 2,
        image.Width, image.Height);
    
    var visual = new DrawingVisual();
    using (var dc = visual.RenderOpen())
    {
        dc.DrawImage(bitmap, rect);
    }
    
    printDialog.PrintVisual(visual, "");
    

    Note that you may as well use any other size for the Rectangle, i.e. scale the printed image accordingly.