Search code examples
wpfprinting.emf

Sending an EMF file to a specific printer / tray in WPF application


I've got a WPF application that needs to send pre-generated EMF files to a specified printer/tray.

I don't want to show the PrintDialog; the actual printer/tray is configured before hand. I also don't need to actually view the EMF file either; but rather just send it to the printer.

So far, all my R&D into this has led to is a bunch of posts that are 5 years old dealing with EMF and WPF and how it isn't supported.

Has anybody had any luck with this before? Can someone point me in the right direction?


Solution

  • Turns out this was easier than I thought. You can do this via a Image control, and use of a converter. This example takes the file location of the emf file, and puts it into a WPF usercontrol that I then send to a printer.

    In XAML:

    <Grid Margin="12">
        <Image Source="{Binding Path=FileName, Converter={StaticResource emfImageConverter}, Mode=OneWay}"></Image>
    </Grid>
    

    and your converter class:

    [ValueConversion(typeof(string), typeof(BitmapImage))]
    public class EmfImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var fileName = (string)value;
            if (fileName == null || !File.Exists(fileName))
                return new BitmapImage();
            using (var stream = File.Open(fileName, FileMode.Open))
            {
                return GetImage(stream);
            }
        }
    
        internal BitmapImage GetImage(Stream fileStream)
        {
            var img = Image.FromStream(fileStream);
            var imgBrush = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad, CreateOptions = BitmapCreateOptions.PreservePixelFormat };
            imgBrush.BeginInit();
            imgBrush.StreamSource = ConvertImageToMemoryStream(img);
            imgBrush.EndInit();
            return imgBrush;
        }
    
        public MemoryStream ConvertImageToMemoryStream(Image img)
        {
            var ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }