Álvaro García
Álvaro García

Reputation: 19356

How to convert a view into a PNG?

I want to create a PNG from a view. I am using this code:

//I instance the user control
            ucFormToPrintView miViewToPrint = new ucFormToPrintView();
            miViewToPrint.DataContext = ((ucFormToPrintView)CCForm).DataContext;

            //I use a RenderTargetBitmap to render the user control
            System.Windows.Media.Imaging.RenderTargetBitmap rtb = new System.Windows.Media.Imaging.RenderTargetBitmap(794, 1122, 72, 72, System.Windows.Media.PixelFormats.Pbgra32);
            rtb.Render(miViewToPrint);

            //I use an encoder to create the png
            System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));


            //I use a dialog to select the path where to save the png file
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();

            saveFileDialog.FilterIndex = 1;

            if (saveFileDialog.ShowDialog() == true)
            {

                using (System.IO.Stream stream = saveFileDialog.OpenFile())
                {

                    encoder.Save(stream);

                    stream.Close();

                    System.Diagnostics.Process.Start(saveFileDialog.FileName);
                }
            }

The result is an empty png.

How can I create a png file from a user control?

Thank so much.

Upvotes: 0

Views: 71

Answers (1)

Clemens
Clemens

Reputation: 128060

The UserControl has to be laid out at least once to be visible. You can achieve that by calling its Measure and Arrange methods.

var miViewToPrint = new ucFormToPrintView();
miViewToPrint.DataContext = ((ucFormToPrintView)CCForm).DataContext;

// layout, i.e. measure and arrange
miViewToPrint.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
miViewToPrint.Arrange(new Rect(miViewToPrint.DesiredSize));

...

if (saveFileDialog.ShowDialog() == true)
{
    using (var stream = saveFileDialog.OpenFile())
    {
        encoder.Save(stream);
    }

    System.Diagnostics.Process.Start(saveFileDialog.FileName);
}

Upvotes: 1

Related Questions