I have a method in my program, that uses PDFShap to export the users project to a pdf. At first I prepared all the data and then exported it to a pdf. This lead to an OutOfMemory exception when there was a lot of data. Then I changed the method, so that every time one page is filled, it is imediatly exported. But now I get a lot of PDFSharp.Font objects that are kept in memory. I tried to do the export in a new Thread, which I was not able to do. I tried calling the Dispose method of all PDFShap objects, setting them to null and to create them all using a statement. Nothing worked. How can I dispose these PDFShap.Font objects completely?
private static void AddPageToPdf(string goalfile, PrinterPage page)
{
using (PdfDocument doc = File.Exists(goalfile) ? PdfReader.Open(goalfile, PdfDocumentOpenMode.Modify) : new PdfDocument(goalfile))
{
string temp = goalfile.Substring(0, goalfile.LastIndexOf("\\")) + "\\temp.pdf";
int pagenumber = doc.PageCount + 1;
FixedDocument fixedDoc = new FixedDocument();
fixedDoc.DocumentPaginator.PageSize = page.GetSize();
// Refresh the page content
page.Page = pagenumber;
page.MaxPages = pagenumber;
page.Width = fixedDoc.DocumentPaginator.PageSize.Width;
page.Height = fixedDoc.DocumentPaginator.PageSize.Height;
// Create a new document page
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
// Initialize the new document page
fixedPage.Background = Brushes.White;
fixedPage.Width = fixedDoc.DocumentPaginator.PageSize.Width;
fixedPage.Height = fixedDoc.DocumentPaginator.PageSize.Height;
// Insert the current page to the document
fixedPage.Children.Add(page);
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
// Save the content to a xps file as base structure for the pdf
MemoryStream lMemoryStream = new MemoryStream();
Package package = Package.Open(lMemoryStream, FileMode.Create);
XpsDocument xpsdoc = new XpsDocument(package);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsdoc);
writer.Write(fixedDoc);
xpsdoc.Close();
package.Close();
// Convert the xps document into a pdf document and save it
using (var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream))
{
PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, temp, 0);
lMemoryStream.Close();
pdfXpsDoc.Close();
using (PdfDocument singlePage = PdfReader.Open(temp, PdfDocumentOpenMode.Import))
{
PdfPage pdfPage = singlePage.Pages[0];
doc.AddPage(pdfPage);
doc.Close();
doc.Save(goalfile);
//try to clean up memory
File.Delete(temp);
singlePage.Dispose();
doc.Dispose();
lMemoryStream = null;
package = null;
writer = null;
pdfPage = null;
}
}
}
GC.Collect();
}
Since VS doesn't provide a wa to export a snapshot from the diagnostic tool (at least none that I could find) I made a screenshot of the snapshot table:

This is a screenshot after i exported the same project a second time
