Memory Exception Fix

Memory Exception Fix

Forum member · Aug 15, 2017
For those that are having problems loading large PDF files and having Memory issues. Below is code that will load one page at a time from the pdf file and create thumbnail list. This is a low memory usage method. Enjoy!! public static ImageList PdfToImageList(string fileName, string tag = "") { ImageList imgList = new ImageList(); int i = 0; try { int pageCount = new PdfDocument(fileName).Pages.Count; // Get one page at a time, instead of loading the entire document for (int j = 0; j < pageCount; j++) { Document document = new Document(); ImportedPageData pageData = new ImportedPageData(fileName, j + 1); document.Pages.Add(new Page()); document.Pages[document.Pages.Count - 1].Elements.Add(pageData); using (var iPdf = new InputPdf(document.Draw())) { using (var rastObj = new PdfRasterizer(iPdf)) { byte[][] t = rastObj.Draw(ceTe.DynamicPDF.Rasterizer.ImageFormat.Bmp, ImageSize.Dpi96); foreach (byte[] z in t) { using (var ms = new MemoryStream(z)) { using (Bitmap tempImage = new Bitmap(ms)) { Bitmap bmp = new Bitmap(100, 100); using (Graphics g = Graphics.FromImage(bmp)) { g.DrawImage(tempImage, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height)); } imgList.Add(bmp); imgList[i].Tag = fileName; } } i++; } t = null; } } }

Re: Memory Exception Fix

Support · Aug 22, 2017
Hello, Creating ImportedPageData object directly from a PDF file path within a for loop will be slower as the constructor has to load the PDF from file every time the loop executes. You may want to consider loading the PDF once using the PdfDocument object and loop through the PdfDocument pages and create ImportedPageData objects as shown below: PdfDocument pdf = new PdfDocument(@"f:\test.pdf"); foreach (PdfPage page in pdf.Pages) { Document document = new Document(); ImportedPageData pageData = new ImportedPageData(page); document.Pages.Add(new Page()); document.Pages[document.Pages.Count - 1].Elements.Add(pageData); byte[] outputBytes = document.Draw(); } Thanks, ceTe Software Support Team.

Re: Memory Exception Fix

Forum member · Aug 24, 2017
Yup, less I/O intensive. Thanks! I've seen several posts of users running into the memory exception error. You may want to re-direct them here as a viable solution.