PDFsharp & MigraDoc Forum
https://forum.pdfsharp.net/

Working without getting an OutOfMemoryException
https://forum.pdfsharp.net/viewtopic.php?f=2&t=3320
Page 1 of 1

Author:  JoeTHeRock [ Sat Mar 12, 2016 10:30 am ]
Post subject:  Working without getting an OutOfMemoryException

Hi,

wrote code which works, but the bigger the files the more problems I get, how can I optimise my code without running in outofmomory

Code:
` private static void ConvertImagetoPDF(String[] ImageFilenames, string[] directories, string insertName = "", string prefix = "Result", string usersChoise = "1", bool tempLabel = false, double tempHeight = 6000, double tempWidth = 8000)
        {
            try
            {
                PdfDocument document = new PdfDocument();
                string temp = "";

                try
                {
                    Console.WriteLine(globalUsersChoise(ref usersChoise, ref prefix, ref tempHeight, ref tempWidth, ref tempLabel));
                    //todo: calculate how many pages it can add in one rush
                    Image[] img = new Image[ImageFilenames.Length];

                    for (int i = 0; i < ImageFilenames.Length; i++)
                    //for (int i = 0; i < 4; i++)
                    {
                        img[i] = Image.FromFile(ImageFilenames[i]);


                        // Create an empty page or load existing
                        PdfPage page = document.AddPage();


                        // Get an XGraphics object for drawing
                        XGraphics gfx = XGraphics.FromPdfPage(page);
                        XImage image = XImage.FromFile(ImageFilenames[i]);

                        page.Width = tempWidth;
                        page.Height = tempHeight;

                        float width = image.PixelWidth * 0.3f;
                        float height = image.PixelHeight * 0.3f;

                        #region create Label

                        // Create a font
                        XFont font = new XFont("Times New Roman", 10, XFontStyle.Bold);

                        // Draw the text
                        if (tempLabel)
                        {
                            gfx.DrawString(Path.GetFileNameWithoutExtension(ImageFilenames[i]), font, XBrushes.Black,
                             new XRect(120, -30, (page.Width - width), (page.Height - height)),
                             XStringFormats.Center);
                        }

                        #endregion


                        gfx.DrawImage(image, (page.Width / 2) - (width / 2), (page.Height / 2) - (height / 2), width, height);//put it in the middle

                        Console.WriteLine((i + 1) + ": " + Path.GetFileName(ImageFilenames[i]));
                        GC.Collect();//hoped this would do the job
                        //document.Save(@"..\..\sample" + Path.GetFileNameWithoutExtension(ImageFilenames[i]) + ".pdf");                             
                    }



                    //var temp = @"!" + prefix + DateTime.Now.Ticks.ToString() + ".pdf";
                }
                finally   //will execute this as it is the first exception statement
                { //save the pdf pagedocument
                    temp = @"!" + prefix + "_" + (insertName.Equals("") ? DateTime.Now.Ticks.ToString() : insertName.ToString().Replace(":", "")) + ".pdf";

                    document.Save(temp);
                    document.Close();
                    Process.Start(temp);

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();

            }

        }


I hoped cleaning the GarbageCollector would help....

Thank you for supporting :)

Author:  TH-Soft [ Sat Mar 12, 2016 3:52 pm ]
Post subject:  Re: Working without getting an OutOfMemoryException

Hi!

Use "using" for disposable objects like XImage.

Run the program in 64 bit mode to break the 2 GiB barrier.

Save and close the file from time to time, then open it to add more images.

Author:  JoeTHeRock [ Sun Mar 13, 2016 10:17 am ]
Post subject:  Re: Working without getting an OutOfMemoryException

Thank you,

but how exactly can I calculate that moment for "Save and close the file from time to time, then open it to add more images." ?

Author:  TH-Soft [ Sun Mar 13, 2016 6:02 pm ]
Post subject:  Re: Working without getting an OutOfMemoryException

JoeTHeRock wrote:
but how exactly can I calculate that moment for [...]
Trial and error.

With .NET 4.5.1 you can try a complete garbage collection:
https://msdn.microsoft.com/en-us/librar ... e(v=vs.110).aspx


Test how many MB of images you can process without error - and then maybe use 25% as trigger for production code.

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/