vrwim
vrwim

Reputation: 14310

Print preview does not render images

I am trying to print a page from my Universal Windows Store app.

I currently have it set up that I get a list of tuples, (contains the data to be put on the printed pages: string and ImageSource), and when the user wants to print, a new PrintPage (custom subclass of Page, styled using XAML) is instantiated, and I set the elements on my PrintPage using this code:

public PrintPage(Tuple<string, ImageSource> tuple) {
    Title.Text = tuple.Item1;
    Image.Source = tuple.Item2;
}

where my XAML is this:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="10*"/>
    </Grid.RowDefinitions>
    <TextBlock Name="Title"/>
    <Image Grid.Row="1" Name="Image" Stretch="Uniform"/>
</Grid>

The ImageSource is rendered using the following code (and displayed on a page to have the user choose what to print):

RenderTargetBitmap Bitmap = new RenderTargetBitmap();
await Bitmap.RenderAsync(DrawingArea); // DrawingArea is a `Grid` containing my elements

Now when I print my page, on the preview and on the printed page, I cannot see my image. What am I doing wrong?

Upvotes: 2

Views: 420

Answers (1)

BrunoVT
BrunoVT

Reputation: 723

It wont show because it is a RenderTargetBitmap, you need to convert it to a BitmapImage like this:

private async void PrintButton_Click(object sender, RoutedEventArgs e) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(MyControl); var bitmapImage = await ConvertToBitmapImage(renderTargetBitmap); var grid = new Grid { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch }; var image = new Image { Source = bitmapImage, Stretch = Windows.UI.Xaml.Media.Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch }; grid.Children.Add(image); _printHelper.AddFrameworkElementToPrint(grid); await _printHelper.ShowPrintUIAsync("", new PrintHelperOptions { Orientation = Windows.Graphics.Printing.PrintOrientation.Landscape }); } private async Task<BitmapImage> ConvertToBitmapImage(RenderTargetBitmap renderTargetBitmap) { var pixels = await renderTargetBitmap.GetPixelsAsync(); var stream = pixels.AsStream(); var outStream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outStream); var displayInformation = DisplayInformation.GetForCurrentView(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels.ToArray()); await encoder.FlushAsync(); outStream.Seek(0); var bitmap = new BitmapImage(); await bitmap.SetSourceAsync(outStream); return bitmap; }

Upvotes: 1

Related Questions