ilyaz wrote:
The code I have throws out of memory exception probably because I am trying to load all source pages into memory before generating output PDF.
Not because you load all the images but because pdfsharp hoggs the memory.
ilyaz wrote:
How can I modify it to ingest one page at a time, add its contents to the output PDF and then cleaning as much memory as possible before ingesting the next page?
Just save the pdf after adding an image and reopen it on the next iteration like this:
Code:
Image myimage = Image.FromFile(source);
System.Drawing.Imaging.FrameDimension oFDimension = new System.Drawing.Imaging.FrameDimension(myimage.FrameDimensionsList[0]);
int iCount = myimage.GetFrameCount(oFDimension) - 1;
for (int index = 0; index <= (iCount); index++)
{
PdfDocument doc = default(PdfDocument);
if index == 0) {
doc = new PdfDocument();
} else {
doc = PdfSharp.Pdf.IO.PdfReader.Open(destinaton, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify);
}
PdfPage page = doc.AddPage();
page.Size = PageSize.Letter;
page.Orientation = PageOrientation.Portrait;
XGraphics xgr = XGraphics.FromPdfPage(page);
myimage.SelectActiveFrame(oFDimension, index);
XImage img = XImage.FromGdiPlusImage(myimage);
xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
}