0

I have a page that has two UIElements that need to be printed, one is a StackPanel and the other is a custom graph control for displaying test scores. The graph control could be any length based on the number of tests to display, so sometimes I will be able to fit both on one page and other times will need separate pages.

Printing them on separate pages works fine as I just set the UIElement to the pagevisual, the problem I am having is that I can't figure out how to combine them for printing on a single page. I tried creating a StackPanel in the codebehind and adding the elements to it, but since an element can only have one parent I have to create temporary objects to hold each one while I remove from the original parent and then give the temp to the new StackPanel. The problem is that after I do that all the bound data goes missing

Any ideas would be awesome! Thanks.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Josh
  • 1,648
  • 8
  • 27
  • 58

2 Answers2

0

Instead of adding actual elements to the StackPanel for printing, you can create snapshots of those elements and add only images to the StackPanel. You can use the following method to created an Image from a UIElement:

public static Image CreateElementImage(UIElement element) 
{
    var bitmap = new WriteableBitmap((int)element.RenderSize.Width, (int)element.RenderSize.Height);

    Array.Clear(bitmap.Pixels, 0, bitmap.Pixels.Length);
    bitmap.Render(element, element.RenderTransform);
    bitmap.Invalidate();

    var result = new Image {Source = bitmap};

    return result;
}
Pavlo Glazkov
  • 20,498
  • 3
  • 58
  • 71
  • In WPF, an easier way to accomplish this would be with a VisualBrush. Not available for SL though – Robert Levy Aug 17 '11 at 19:01
  • Okay, so my next question would be is there any way to take a picture of only a certain part of the UIElement? Say I want to use the entire page as the element, calculate how many pages I will need, and then take a picture of it from the top to -1024, then -1024 to -2048, and so on until I have a picture of every page.Is this possible? – Josh Aug 17 '11 at 19:09
  • @Josh - You can try to play around with that WriteableBitmap. It could be that you can render a specific part of the UIElement to it. Unfortunately, I don't have a complete solution for you. – Pavlo Glazkov Aug 17 '11 at 19:33
  • Or maybe is there a way to split the bitmap into pieces after it's created? I could take an image of the entire page, then somehow divide it up into images that will fit on a printed page. – Josh Aug 17 '11 at 19:36
0

Or just put the image in a Canvas and then compare Canvas's height and image height to calculate number of pages.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
aata
  • 1