Search code examples
c#migradocfilecontentresult

MigraDoc Images - When can I delete the images


I am using MigraDoc for PDF Exports and part of the application allows the user to Embed an image (MigraDoc.DocumentObjectModel.Shapes.Image) into a Document. The images exist in the database and I am not able to upgrade to the latest MigraDoc BETA that handles FileStream images from Memory. So, my solution is to read the images from the database and store them in a 'Temporary' folder in my Images folder and MigraDoc will reference the images there. Once the PDF has rendered then I will no longer need the image and will want to get rid of it.

The PDF Document is rendered as follows:

            PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
            renderer.Document = this.document;
            renderer.RenderDocument();

            byte[] pdfContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                renderer.PdfDocument.Save(stream, true);
                pdfContents = stream.ToArray();
            }

            return pdfContents;

and is eventually passed as a FileContentResult.

My problem is that I do not seem to be able to get rid of the files added to the PDF document at any stage of the process... They seem to be required up to and including the point I return the FileContentResult.

Is there a setting on the PdfDocumentRenderer (or anywhere else) that will embed the images instead of relying on them being in-situ until after the FileContentResult is rendered?


Solution

  • After the call to renderer.PdfDocument.Save the image files are no longer needed.

    Actually the images should no longer be needed after the call to renderer.RenderDocument();.

    Some background information
    The WPF build of MigraDoc uses class BitmapSource to open the image. By default this class caches the images and version 1.32 used the default options and thus the image files remain locked even after disposing the MigraDoc image.
    This unwanted side effect of caching was fixed in November 2014 - since then MigraDoc disables caching when opening images using class BitmapSource.
    The GDI+ build of MigraDoc never had this caching problem.
    If your company insists on using a version that was published four years ago then you will miss all the improvements and bug fixes that were applied since then.
    Maybe the GDI build is the solution to this locking issue (assuming this question is about image files that remain locked when they are no longer needed).