I am trying to find an reusable and elegant way to create bitmaps from a visuals in WPF and then print the bitmap to a TLP-2844 zebra printer. The bitmap image needs to be 203 DPI since this is what the Zebra printer supports. I have tried everything I can think and I have to be missing something either completely obvious or what I am trying to do is not as simple as I am making it.
When I print the bitmap that gets created to a normal printer it looks perfectly fine but when printed to the zebra printer the image is scaled down to a 1/3 of its original size.
When I step through the code and look at the final bitmap generated it is the correct DPI and the correct height and width.
Below I have provided the code I am using to create my bitmap.
public void PrintMyVisual()
{
BitmapSource bmpSource = Utilities.ImageHelper.GetBitmapSource(this.label); //label is grid with some controls
this.BmpImg = Utilities.ImageHelper.CreateBMPFromBitmapSource(bmpSource);
PrintDocument pdoc = new PrintDocument();
pdoc.PrintPage +=new PrintPageEventHandler(pdoc_PrintPage);
}
void pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.DrawImage(this.BmpImg, 0, 0);
}
public static Bitmap CreateBMPFromBitmapSource(BitmapSource bmpSource)
{
Bitmap newBitmap = null;
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmpSource));
using (MemoryStream imageStream = new MemoryStream())
{
encoder.Save(imageStream);
newBitmap = new Bitmap(imageStream);
}
return newBitmap;
}
public static BitmapSource GetBitmapSource(Visual vis)
{
DependencyObject dpObj = vis;
FrameworkElement fe = dpObj as FrameworkElement;
BitmapScalingMode xx = RenderOptions.GetBitmapScalingMode(dpObj);
RenderOptions.SetBitmapScalingMode(dpObj, BitmapScalingMode.HighQuality);
//96dpi is what wpf renders at but I am going to try 203
RenderTargetBitmap btmp = new RenderTargetBitmap(Convert.ToInt32(Math.Ceiling(fe.ActualWidth)),
Convert.ToInt32(Math.Ceiling(fe.ActualHeight)), 203, 203, PixelFormats.Pbgra32);
btmp.Render(fe);
return btmp;
}