Memory Exception Fix

Skip Navigation LinksHome  /  Support  /  Forums  /  DynamicPDF Merger for .NET (v8.x)  /  Display Thread

DynamicPDF Merger for .NET (v8.x) Forum

 Aug 15 2017 1:35 PM
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;
}
}
}
 Aug 22 2017 4:51 PM
Posted by a ceTe Software moderator
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.
 Aug 24 2017 2:29 PM
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.

All times are US Eastern Standard time. The time now is 3:11 PM.