How to dispose PdfSharp XpsDocument object while saving WPF window as Pdf?

544 Views Asked by At

I'm using PdfSharp to save a WPF Window into a PDF. I'm getting System.OutOfMemoryException when executing the following code:-

using (MemoryStream lMemoryStream = new MemoryStream())
{
    Package package = Package.Open(lMemoryStream, FileMode.Create);
    var doc = new System.Windows.Xps.Packaging.XpsDocument(package);
    XpsDocumentWriter writer = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(doc);

    double dpiScale = 600.0 / 96.0;
    var renderBitmap = new RenderTargetBitmap(Convert.ToInt32(this.Width * dpiScale),
                           Convert.ToInt32(this.Height * dpiScale),
                           600.0,
                           600.0,
                           PixelFormats.Pbgra32);
    renderBitmap.Render(this);
    var visual = new DrawingVisual();
    using (var dc = visual.RenderOpen())
    {
        dc.DrawImage(renderBitmap, new Rect(0, 0, this.Width, this.Height));
    }                

    writer.Write(visual);
    doc.Close();
    package.Close();

    var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream);
    XpsConverter.Convert(pdfXpsDoc, _pdfFileName, 0);
}

In the above snippet, if I change the 600.0 value to 300.0 in dpiScale while creating RenderTargetBitmap, I don't get the OutOfMemoryException but the quality of the saved PDF is not good.

How to dispose the PdfSharp XpsDocument? I believe it is causing some memory leak.

0

There are 0 best solutions below