Exception of type ‘System.OutOfMemoryException’ was thrown in GroupDocs Conversion

Halo,

We have an application that has preview file feature.
Every time we hit the Preview button, we got an error of “Exception of type ‘System.OutOfMemoryException’ was thrown.”

Screenshot_20230503_111144.png (110.7 KB)

The application running on Linux Centos 7, under docker container.
And here are our preview file codes:

public async Task<IActionResult> PrintPIQByID(string ID, string DocNo)
    {
        //var result = JsonConvert.DeserializeObject<HeaderDetailData>(Data);
        DocNo = DocNo.Replace("/", "-");
        string saveFile = "Template/tmpProtocolIQ.docx";
        string sourceTemplatePath = Path.Combine(Directory.GetCurrentDirectory(), saveFile);
        string outputTemplatePath = Path.Combine(Directory.GetCurrentDirectory(), saveFile.Replace("tmpProtocolIQ", DocNo));
        FileStream template = System.IO.File.OpenRead(sourceTemplatePath);
        FileStream output = System.IO.File.Create(outputTemplatePath);
        List<string> Attachs = new List<string>();
        List<byte[]> AttachmentsPathFolder = new List<byte[]>();

        try
        {
            HeaderDetailData result = new HeaderDetailData();
            ApprovalController approvalController = new ApprovalController(_configuration);
            result = await _iProtocolIQClient.GetByIDAsync(new Guid(ID));
            DateTime createdDate = (DateTime)result.IQProtocol.CreatedDate;
            string getFromattedDate = createdDate.ToString("dd MMM yyyy");
            result.ListApprovalLog = await approvalController.GetApprovalLog(moduleCode, ID.ToString());

            #region Cover
            var dtReportIQ = new DataTable();
            dtReportIQ.Columns.Add("NoProtokol");
            dtReportIQ.Columns.Add("NamaAset");
            dtReportIQ.Columns.Add("Lokasi");
            dtReportIQ.Columns.Add("Tipe");
            dtReportIQ.Columns.Add("NoDoc");
            dtReportIQ.Columns.Add("SerialNo");

            DataRow rowReportDQ = dtReportIQ.NewRow();
            rowReportDQ["NoProtokol"] = result.IQProtocol.NoProtokol;
            rowReportDQ["NamaAset"] = result.IQProtocol.NamaAset;
            rowReportDQ["Lokasi"] = result.IQProtocol.Lokasi;
            rowReportDQ["Tipe"] = result.IQProtocol.Tipe;
            rowReportDQ["NoDoc"] = result.IQProtocol.DocNo;
            rowReportDQ["SerialNo"] = result.IQProtocol.ModelNoSeri;
            dtReportIQ.Rows.Add(rowReportDQ);
            #endregion

            #region 1. Gambar Mesin
            var dtGambarMesin = new DataTable();
            dtGambarMesin.Columns.Add("No");
            dtGambarMesin.Columns.Add("NamaFile");
            dtGambarMesin.Columns.Add("Keterangan");
            Attachs = Attachs.Distinct().ToList();
            if (result.GambarMesin.Any())
            {
                //NEW ASSET
                if (result.IQProtocol.Tipe == "New Asset")
                {
                    if (result.IQProtocol.IsCheckGambar)
                    {
                        //(var item in Model.OrderBy(i => i.Order))
                        foreach (var item in result.GambarMesin.OrderBy(i => i.No))
                        {
                            if (item.TypeOldNew == "NEW")
                            {
                                DataRow rowGambarMesin = dtGambarMesin.NewRow();
                                rowGambarMesin["No"] = item.No;
                                rowGambarMesin["NamaFile"] = HtmlToText(item.FileName);
                                rowGambarMesin["Keterangan"] = HtmlToText(item.Keterangan);
                                dtGambarMesin.Rows.Add(rowGambarMesin);
                                Attachs.Add(item.FileID.ToString());

                            }
                        }
                    }
                }

                //REQUALIFICATION
                else
                {
                    if (result.IQProtocol.IsCheckNewGambarMesin)
                    {
                        foreach (var item in result.GambarMesin.OrderBy(i => i.No))
                        {
                            if (item.TypeOldNew == "NEW")
                            {
                                DataRow rowGambarMesin = dtGambarMesin.NewRow();
                                rowGambarMesin["No"] = item.No;
                                rowGambarMesin["NamaFile"] = HtmlToText(item.FileName);
                                rowGambarMesin["Keterangan"] = HtmlToText(item.Keterangan);
                                dtGambarMesin.Rows.Add(rowGambarMesin);
                                Attachs.Add(item.FileID.ToString());
                            }
                        }
                    }
                    else
                    {
                        foreach (var item in result.GambarMesin.OrderBy(i => i.No))
                        {
                            if (item.TypeOldNew == "OLD")
                            {
                                DataRow rowGambarMesin = dtGambarMesin.NewRow();
                                rowGambarMesin["No"] = item.No;
                                rowGambarMesin["NamaFile"] = HtmlToText(item.FileName);
                                rowGambarMesin["Keterangan"] = HtmlToText(item.Keterangan);
                                dtGambarMesin.Rows.Add(rowGambarMesin);
                                Attachs.Add(item.FileID.ToString());
                            }
                        }
                    }
                }
            }
            #endregion

            #region ATTACHMENT
            var dtAttachment2 = new DataTable();
            dtAttachment2.Columns.Add("AttachPath");
            dtAttachment2.Columns.Add("AttachName");

            foreach (var FileID in Attachs.ToList())
            {
                Guid _id = new Guid(FileID);
                var resultFile = await _iFilesClient.GetByIdAsync(_id);
                var imageFilesFolder = Utils.GetOutputDirectoryPath(resultFile.FileName);
                string imageFilesPath = Path.Combine(imageFilesFolder, "page-{0}.png");
                byte[] file = await DownloadFile(_id, _iFilesClient);
                int pagesCount = 0;

                //==================== LIST GAMBAR MESIN PATH LOCATION =========================
                Stream stream = new MemoryStream(file);
                using (Viewer viewer = new Viewer(stream))
                {
                    //Get document info
                    ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));
                    pagesCount = info.Pages.Count;

                    //Set options and render document
                    PngViewOptions optionpng = new PngViewOptions(imageFilesPath);
                    viewer.View(optionpng);
                }
                for (int i = 1; i <= pagesCount; i++)
                {
                    string attachmentPath = Path.Combine(imageFilesFolder, "page-" + i + ".png");
                    string getFolder = Path.GetFileNameWithoutExtension(resultFile.FileName);
                    folderName.Add(attachmentPath);

                    DataRow rowAttachment2 = dtAttachment2.NewRow();
                    rowAttachment2["AttachPath"] = attachmentPath;
                    rowAttachment2["AttachName"] = getFolder + " (" + i + ")";
                    dtAttachment2.Rows.Add(rowAttachment2);
                }
            }
            #endregion

            #region Data Source
            DataSourceInfo dsProtocolIQ = new DataSourceInfo(dtReportIQ, "dsProtocolIQ");
            DataSourceInfo dsAttachment2 = new DataSourceInfo(dtAttachment2, "dsAttachment2");

            DocumentAssembler assembler = new DocumentAssembler();
            assembler.Options |= DocumentAssemblyOptions.UpdateFieldsAndFormulas;
            assembler.AssembleDocument(
                template
                , output
                , dsProtocolIQ
                , dsAttachment2
                );
            output.Dispose();
            template.Dispose();
            #endregion

            #region download pdf
            var converter = new GroupDocs.Conversion.Converter(outputTemplatePath);
            var options = new PdfConvertOptions();
            converter.Convert(outputTemplatePath.Replace("docx", "pdf"), options);
            byte[] bytes = System.IO.File.ReadAllBytes(outputTemplatePath.Replace("docx", "pdf"));
            string ouptutPdf1 = outputTemplatePath.Replace("docx", "pdf");
            converter.Dispose();

            if (System.IO.File.Exists(outputTemplatePath))
            {
                System.IO.File.Delete(outputTemplatePath);
            }
            foreach (var item in folderName.ToList())
            {
                if (System.IO.File.Exists(item))
                {
                    System.IO.File.Delete(item);
                }
            }
            if (System.IO.File.Exists(outputTemplatePath.Replace("docx", "pdf")))
            {
                System.IO.File.Delete(outputTemplatePath.Replace("docx", "pdf"));
            }
            foreach (var FileID in Attachs.ToList())
            {
                if (System.IO.File.Exists(FileID))
                {
                    System.IO.File.Delete(FileID);
                }
            }
            return File(bytes, "application/pdf", DocNo + ".pdf");
            #endregion
        }
        catch (Exception)
        {
            output.Dispose();
            template.Dispose();
            if (System.IO.File.Exists(outputTemplatePath))
            {
                System.IO.File.Delete(outputTemplatePath);
            }
            foreach (var item in folderName.ToList())
            {
                if (System.IO.File.Exists(item))
                {
                    System.IO.File.Delete(item);
                }
            }
            if (System.IO.File.Exists(outputTemplatePath.Replace("docx", "pdf")))
            {
                System.IO.File.Delete(outputTemplatePath.Replace("docx", "pdf"));
            }
            foreach (var FileID in Attachs.ToList())
            {
                if (System.IO.File.Exists(FileID))
                {
                    System.IO.File.Delete(FileID);
                }
            }
            throw;
        }

    }

Thank You,
Margaretha

@teguhmargaretha2010

We need a problematic file and a sample code/docker image to reproduce the issue at our end.

Hi @atir.tahir

Here is the problematic file tmpProtocolIQ.docx (130.7 KB)

And below is the sample code

public async Task<IActionResult> PrintPIQByID(string ID, string DocNo)
{
    //var result = JsonConvert.DeserializeObject<HeaderDetailData>(Data);
    DocNo = DocNo.Replace("/", "-");
    string saveFile = "Template/tmpProtocolIQ.docx";
    string sourceTemplatePath = Path.Combine(Directory.GetCurrentDirectory(), saveFile);
    string outputTemplatePath = Path.Combine(Directory.GetCurrentDirectory(), saveFile.Replace("tmpProtocolIQ", DocNo));
    FileStream template = System.IO.File.OpenRead(sourceTemplatePath);
    FileStream output = System.IO.File.Create(outputTemplatePath);
    List<string> Attachs = new List<string>();
    List<byte[]> AttachmentsPathFolder = new List<byte[]>();

    try
    {
        HeaderDetailData result = new HeaderDetailData();
        ApprovalController approvalController = new ApprovalController(_configuration);
        result = await _iProtocolIQClient.GetByIDAsync(new Guid(ID));
        DateTime createdDate = (DateTime)result.IQProtocol.CreatedDate;
        string getFromattedDate = createdDate.ToString("dd MMM yyyy");
        result.ListApprovalLog = await approvalController.GetApprovalLog(moduleCode, ID.ToString());

        #region Cover
        var dtReportIQ = new DataTable();
        dtReportIQ.Columns.Add("NoProtokol");
        dtReportIQ.Columns.Add("NamaAset");
        dtReportIQ.Columns.Add("Lokasi");
        dtReportIQ.Columns.Add("Tipe");
        dtReportIQ.Columns.Add("NoDoc");
        dtReportIQ.Columns.Add("SerialNo");

        DataRow rowReportDQ = dtReportIQ.NewRow();
        rowReportDQ["NoProtokol"] = result.IQProtocol.NoProtokol;
        rowReportDQ["NamaAset"] = result.IQProtocol.NamaAset;
        rowReportDQ["Lokasi"] = result.IQProtocol.Lokasi;
        rowReportDQ["Tipe"] = result.IQProtocol.Tipe;
        rowReportDQ["NoDoc"] = result.IQProtocol.DocNo;
        rowReportDQ["SerialNo"] = result.IQProtocol.ModelNoSeri;
        dtReportIQ.Rows.Add(rowReportDQ);
        #endregion

        #region 1. Gambar Mesin
        var dtGambarMesin = new DataTable();
        dtGambarMesin.Columns.Add("No");
        dtGambarMesin.Columns.Add("NamaFile");
        dtGambarMesin.Columns.Add("Keterangan");
        Attachs = Attachs.Distinct().ToList();
        if (result.GambarMesin.Any())
        {
            //NEW ASSET
            if (result.IQProtocol.Tipe == "New Asset")
            {
                if (result.IQProtocol.IsCheckGambar)
                {
                    //(var item in Model.OrderBy(i => i.Order))
                    foreach (var item in result.GambarMesin.OrderBy(i => i.No))
                    {
                        if (item.TypeOldNew == "NEW")
                        {
                            DataRow rowGambarMesin = dtGambarMesin.NewRow();
                            rowGambarMesin["No"] = item.No;
                            rowGambarMesin["NamaFile"] = HtmlToText(item.FileName);
                            rowGambarMesin["Keterangan"] = HtmlToText(item.Keterangan);
                            dtGambarMesin.Rows.Add(rowGambarMesin);
                            Attachs.Add(item.FileID.ToString());

                        }
                    }
                }
            }

            //REQUALIFICATION
            else
            {
                if (result.IQProtocol.IsCheckNewGambarMesin)
                {
                    foreach (var item in result.GambarMesin.OrderBy(i => i.No))
                    {
                        if (item.TypeOldNew == "NEW")
                        {
                            DataRow rowGambarMesin = dtGambarMesin.NewRow();
                            rowGambarMesin["No"] = item.No;
                            rowGambarMesin["NamaFile"] = HtmlToText(item.FileName);
                            rowGambarMesin["Keterangan"] = HtmlToText(item.Keterangan);
                            dtGambarMesin.Rows.Add(rowGambarMesin);
                            Attachs.Add(item.FileID.ToString());
                        }
                    }
                }
                else
                {
                    foreach (var item in result.GambarMesin.OrderBy(i => i.No))
                    {
                        if (item.TypeOldNew == "OLD")
                        {
                            DataRow rowGambarMesin = dtGambarMesin.NewRow();
                            rowGambarMesin["No"] = item.No;
                            rowGambarMesin["NamaFile"] = HtmlToText(item.FileName);
                            rowGambarMesin["Keterangan"] = HtmlToText(item.Keterangan);
                            dtGambarMesin.Rows.Add(rowGambarMesin);
                            Attachs.Add(item.FileID.ToString());
                        }
                    }
                }
            }
        }
        #endregion

        #region ATTACHMENT
        var dtAttachment2 = new DataTable();
        dtAttachment2.Columns.Add("AttachPath");
        dtAttachment2.Columns.Add("AttachName");

        foreach (var FileID in Attachs.ToList())
        {
            Guid _id = new Guid(FileID);
            var resultFile = await _iFilesClient.GetByIdAsync(_id);
            var imageFilesFolder = Utils.GetOutputDirectoryPath(resultFile.FileName);
            string imageFilesPath = Path.Combine(imageFilesFolder, "page-{0}.png");
            byte[] file = await DownloadFile(_id, _iFilesClient);
            int pagesCount = 0;

            //==================== LIST GAMBAR MESIN PATH LOCATION =========================
            Stream stream = new MemoryStream(file);
            using (Viewer viewer = new Viewer(stream))
            {
                //Get document info
                ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));
                pagesCount = info.Pages.Count;

                //Set options and render document
                PngViewOptions optionpng = new PngViewOptions(imageFilesPath);
                viewer.View(optionpng);
            }
            for (int i = 1; i <= pagesCount; i++)
            {
                string attachmentPath = Path.Combine(imageFilesFolder, "page-" + i + ".png");
                string getFolder = Path.GetFileNameWithoutExtension(resultFile.FileName);
                folderName.Add(attachmentPath);

                DataRow rowAttachment2 = dtAttachment2.NewRow();
                rowAttachment2["AttachPath"] = attachmentPath;
                rowAttachment2["AttachName"] = getFolder + " (" + i + ")";
                dtAttachment2.Rows.Add(rowAttachment2);
            }
        }
        #endregion

        #region Data Source
        DataSourceInfo dsProtocolIQ = new DataSourceInfo(dtReportIQ, "dsProtocolIQ");
        DataSourceInfo dsAttachment2 = new DataSourceInfo(dtAttachment2, "dsAttachment2");

        DocumentAssembler assembler = new DocumentAssembler();
        assembler.Options |= DocumentAssemblyOptions.UpdateFieldsAndFormulas;
        assembler.AssembleDocument(
            template
            , output
            , dsProtocolIQ
            , dsAttachment2
            );
        output.Dispose();
        template.Dispose();
        #endregion

        #region download pdf
        var converter = new GroupDocs.Conversion.Converter(outputTemplatePath);
        var options = new PdfConvertOptions();
        converter.Convert(outputTemplatePath.Replace("docx", "pdf"), options);
        byte[] bytes = System.IO.File.ReadAllBytes(outputTemplatePath.Replace("docx", "pdf"));
        string ouptutPdf1 = outputTemplatePath.Replace("docx", "pdf");
        converter.Dispose();

        if (System.IO.File.Exists(outputTemplatePath))
        {
            System.IO.File.Delete(outputTemplatePath);
        }
        foreach (var item in folderName.ToList())
        {
            if (System.IO.File.Exists(item))
            {
                System.IO.File.Delete(item);
            }
        }
        if (System.IO.File.Exists(outputTemplatePath.Replace("docx", "pdf")))
        {
            System.IO.File.Delete(outputTemplatePath.Replace("docx", "pdf"));
        }
        foreach (var FileID in Attachs.ToList())
        {
            if (System.IO.File.Exists(FileID))
            {
                System.IO.File.Delete(FileID);
            }
        }
        return File(bytes, "application/pdf", DocNo + ".pdf");
        #endregion
    }
    catch (Exception)
    {
        output.Dispose();
        template.Dispose();
        if (System.IO.File.Exists(outputTemplatePath))
        {
            System.IO.File.Delete(outputTemplatePath);
        }
        foreach (var item in folderName.ToList())
        {
            if (System.IO.File.Exists(item))
            {
                System.IO.File.Delete(item);
            }
        }
        if (System.IO.File.Exists(outputTemplatePath.Replace("docx", "pdf")))
        {
            System.IO.File.Delete(outputTemplatePath.Replace("docx", "pdf"));
        }
        foreach (var FileID in Attachs.ToList())
        {
            if (System.IO.File.Exists(FileID))
            {
                System.IO.File.Delete(FileID);
            }
        }
        throw;
    }

}

@teguhmargaretha2010

We still need a docker image (you can make a simple console application as well) to reproduce this issue at our end.

@atir.tahir

The issue has been resolved thank you.

@teguhmargaretha2010

You are welcome.