Free Support Forum - aspose.com

A generic error occurred in GDI+ When saving PDF - Version 19.8.0

I’m getting the following error in our PROD domain. Running the same code in our DEV domain does not get the error.

Source: System.Drawing

Target: Void Save(System.String, System.Drawing.Imaging.ImageCodecInfo, System.Drawing.Imaging.EncoderParameters)

Description: A generic error occurred in GDI+.

Stack Trace:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at Aspose.Pdf.Image.#=zmYNWndA=(String #=zU3JopbM=) at Aspose.Pdf.Image.#=zwYl5uwk=(Double& #=z0vx1X_s=, Double& #=zNlbvMUg=, Double& #=zV8HuGkM=, Boolean #=z7n4ociiD2a0t, MarginInfo #=zKPvYDC0=, Double #=zb3uiWh2iQua2, Double #=zp1wo_jc=, Page #=zjjW15wQ=, List1 #=zzSaZ$l4=, Boolean #=zjD3iGRm2R8cH, Boolean #=zkjbyHw2V_cmP, Boolean #=zo3qqxC0=, Paragraphs& #=zzP4X4QkFAd7pTo3AXg==, Double #=z1r3jrBo4AERhPph0kg==, Double #=zspnZeVs=, Int32 #=zXH4dLBfowudSP4R5rTJL$sk=) at #=zY9GaegCLTwV6ufBvBLKjZyY=.#=zwYl5uwk=() at Aspose.Pdf.Cell.#=z1OazhyL7ilJ1(Table #=zPJF0cRU=, Double #=zFX7ZxNU=, Page #=zjjW15wQ=, Double #=zspnZeVs=, Double #=zV8HuGkM=, Boolean #=zBTtRI2RWsb3_XEeWKUW6KV4=) at Aspose.Pdf.Row.#=zQ6ZPIenA$3Qc7OyPOw==(Table #=zPJF0cRU=, Page #=zjjW15wQ=, Double #=zV8HuGkM=, Double #=zspnZeVs=, Int32 #=zkRPHzV4=) at Aspose.Pdf.Row.#=zwYl5uwk=(Table #=zPJF0cRU=, Double& #=zV8HuGkM=, Double& #=z0vx1X_s=, Boolean #=zjD3iGRm2R8cH, Double #=z7zTpG83LkQ_P, Double #=zspnZeVs=, Page #=zjjW15wQ=, Int32& #=zZ6C2WWJSmFAe) at Aspose.Pdf.Table.#=zwYl5uwk=(Double& #=z0vx1X_s=, Double& #=zV8HuGkM=, Boolean #=zjD3iGRm2R8cH, Double #=zvtp9HdZHlHbq, Double #=zspnZeVs=, Page #=zjjW15wQ=, Boolean #=zUNLkfSu7xd4v, List1 #=zzSaZ$l4=) at #=zY9GaegCLTwV6ufBvBLKjZyY=.#=zwYl5uwk=() at Aspose.Pdf.Page.#=zo01hIao=(Page #=zjjW15wQ=) at Aspose.Pdf.Page.#=zPyFghwFyZl_uw34oxg==() at Aspose.Pdf.Document.ProcessParagraphs() at Aspose.Pdf.Document.#=zX0JuM$$nMZfL(Stream #=zu6xQV10=, SaveOptions #=zNM2u7RsscuCD) at Aspose.Pdf.Document.#=zD90fPvhST9SM(Stream #=z_oI$NCBLFtmI, SaveOptions #=zmSsktBU=) at Aspose.Pdf.Document.Save(Stream outputStream, SaveFormat format) at Mosaic.Framework.Helpers.ProviderDirectoryHelper.CreatePDF(List1 providerPages) in C:\Code\SVN\branches\MVC-5.2.4\Mosaic\Framework\Helpers\ProviderDirectoryHelper.cs:line 298 at Mosaic.Areas.Caregiver.Controllers.ProviderDirectoryController.GeneratePDF(FormCollection form) in C:\Code\SVN\branches\MVC-5.2.4\Mosaic\Areas\Caregiver\Controllers\ProviderDirectoryController.cs:line 173 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.b__0() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_6.b__4() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.b__1(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Error line
using (MemoryStream pageMemoryStream = new MemoryStream())
{
pdfDocument.Save(pageMemoryStream, SaveFormat.Pdf);
pageArray = pageMemoryStream.ToArray();
}

Code

public class ProviderDirectoryHelper
{
private static Injected _serviceLocator { get; set; }

    /// <summary>
    /// Create PDF Stream
    /// </summary>
    /// <param name="providerPages"></param>
    /// <returns></returns>
    public static byte[] CreatePDF(List<ProviderDetailsPage> providerPages)
    {
        //https://docs.aspose.com/pdf/net/working-with-tables/

        System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        //*******************************
        //*** Load the Aspose License ***
        //*** //https://github.com/aspose-pdf/Aspose.PDF-for-.NET
        //*******************************
        License pdflic = new License();
        // specify the embedded file information. MergedAPI is default namespace of project
        pdflic.SetLicense("XXX.Aspose.Total.lic");
        // embed the license file within solution
        pdflic.Embedded = true;
        //*******************************

        //*************************
        //*** Base PDF Document ***
        //*************************
        Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document();
        pdfDocument.PageInfo.Height = Aspose.Pdf.PageSize.A4.Height;
        pdfDocument.PageInfo.Width = Aspose.Pdf.PageSize.A4.Width;
        pdfDocument.PageInfo.Margin = new MarginInfo
        {
            Left = 0f,
            Right = 0f,
            Top = 0f,
            Bottom = 0f
        };
        //*************************

        //******************
        //*** Cover Page ***
        //******************
        //AddCoverPageToPDF(pdfDocument);

        Page pageCover = pdfDocument.Pages.Add();
        pageCover.Background = Aspose.Pdf.Color.White;
        pageCover.PageInfo.Margin = new MarginInfo
        {
            Left = 0f,
            Right = 0f,
            Top = 0f,
            Bottom = 0f
        };

        BinaryStorage coverPageImage = GetCoverPage();

        using (MemoryStream streamCoverPage = new MemoryStream(coverPageImage.Binary))
        {
            pageCover.AddImage(streamCoverPage, imageRect: pageCover.GetPageRect(false));
        }
        //******************

        //**********************
        //*** Provider Cards ***
        //**********************
        Page pageCard = pdfDocument.Pages.Add();
        pageCard.Background = Aspose.Pdf.Color.White;
        pageCard.PageInfo.Margin = new MarginInfo
        {
            Left = 0f,
            Right = 0f,
            Top = 0f,
            Bottom = 0f
        };

        string baseURL = ConfigurationManager.AppSettings["BaseURL"];
        var urlHelper = _serviceLocator.Service.GetInstance<UrlHelper>();
        
        float pageWidth = Aspose.Pdf.PageSize.A4.Width;
        string colOneWidth = (pageWidth * 0.22d).ToString();

        float colTwoLength = pageWidth * 0.395f;
        string colTwoWidth = (colTwoLength).ToString();

        float colThreeLength = pageWidth * 0.395f;
        string colThreeWidth = (colThreeLength).ToString();
        Color colorGreen = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.FromArgb(46017)); //RGBA Hex = 00B3C1)

        BorderInfo borderGreen = new BorderInfo
        {
            Bottom = new GraphInfo()
        };
        borderGreen.Bottom.Color = colorGreen;
        borderGreen.Bottom.LineWidth = 3f;

        BorderInfo borderWhite = new BorderInfo
        {
            Bottom = new GraphInfo()
        };
        borderWhite.Bottom.Color = Aspose.Pdf.Color.White;
        borderWhite.Bottom.LineWidth = 3f;

        // Instantiate a table object
        Aspose.Pdf.Table card = new Aspose.Pdf.Table
        {
            DefaultColumnWidth = pageWidth.ToString(),

            // Set with column widths of the table
            ColumnWidths = string.Format("{0} {1} {2}", colOneWidth, colTwoWidth, colThreeWidth),

            RepeatingRowsCount = 1
        };

        foreach (ProviderDetailsPage providerPage in providerPages)
        {
            //Aspose.Pdf.Table card = CreatProviderCard(providerPage, baseURL, urlHelper);

            string providerPageURL = GetUrlAbsoluteFromInsideEPiServer(providerPage.ContentLink, providerPage.Language.Name);

            // Create rows in the table and then cells in the rows
            Aspose.Pdf.Row row = card.Rows.Add();

            //******************
            //*** Column One ***
            //******************
            Aspose.Pdf.Cell colOne = row.Cells.Add();
            colOne.Margin = new MarginInfo
            {
                Top = 34d,
                Left = 34d,
                Right = 0d,
                Bottom = 10d
            };
            colOne.BackgroundColor = Aspose.Pdf.Color.White;
            colOne.Border = borderGreen;
            colOne.Alignment = HorizontalAlignment.Left;
            colOne.VerticalAlignment = VerticalAlignment.Top;

            Aspose.Pdf.Image providerImage = new Aspose.Pdf.Image
            {
                File = string.Format("{0}{1}", baseURL, urlHelper.ContentUrl(providerPage.ProviderImageUrl)),
                FixHeight = 130d,
                FixWidth = 140d
            };
            colOne.Paragraphs.Add(providerImage);

            //QRCode
            Aspose.Pdf.Image qrCodeImage = new Aspose.Pdf.Image
            {
                File = GenerateQRCodeURL(providerPageURL),
                FixHeight = 70d,
                FixWidth = 70d,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Bottom,
                Margin = new MarginInfo
                {
                    Top = 6d,
                    Left = 0d,
                    Right = 0d,
                    Bottom = 0d
                },
            };

            colOne.Paragraphs.Add(qrCodeImage);
            //******************

            //******************
            //*** Column Two ***
            //******************
            Aspose.Pdf.Cell colTwo = row.Cells.Add("");
            colTwo.Margin = new MarginInfo
            {
                Top = 25d,
                Left = 22d,
                Right = 22d,
                Bottom = 0d
            };
            colTwo.BackgroundColor = Color.White;
            colTwo.Border = borderGreen;
            colTwo.IsWordWrapped = true;
            colTwo.Alignment = HorizontalAlignment.Left;
            colTwo.VerticalAlignment = VerticalAlignment.Top;

            //Provider Info - Provider Page Link
            TextFragment fragPageLink = new TextFragment(providerPage.Provider.DisplayName)
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                Hyperlink = new WebHyperlink(providerPageURL)
            };
            //fragPageLink.TextState.BackgroundColor = Color.Aqua;
            fragPageLink.TextState.ForegroundColor = Color.Blue;
            fragPageLink.TextState.FontStyle = FontStyles.Bold;
            fragPageLink.TextState.FontSize = 11f;
            //fragPageLink.Margin.Top = -6f;
            fragPageLink.Margin.Bottom = 3f;
            //fragPageLink.Hyperlink = new WebHyperlink(fridenlyUrl);
            colTwo.Paragraphs.Add(fragPageLink);

            //Specialties
            PopulateSpecialties(colTwo, providerPage.Provider);

            //Phone
            if (!string.IsNullOrEmpty(providerPage.Provider.Phone))
            {
                TextFragment fragPhone = new TextFragment(string.Format("{0:###-###-####}", double.Parse(providerPage.Provider.Phone)).Replace("-", "."));
                fragPhone.TextState.ForegroundColor = Color.Black;
                fragPhone.TextState.FontSize = 11f;
                fragPhone.Margin.Top = 3f;
                colTwo.Paragraphs.Add(fragPhone);
            }

            //Locations
            PopulateLocations(colTwo, providerPage.Provider);
            //******************

            //********************
            //*** Column Three ***
            //********************
            Aspose.Pdf.Cell colThree = row.Cells.Add("");
            colThree.Margin = new MarginInfo
            {
                Top = 0d,
                Left = 22d,
                Right = 22d,
                Bottom = 0d
            };
            colThree.Border = borderWhite;
            colThree.DefaultCellTextState.ForegroundColor = Aspose.Pdf.Color.White;
            colThree.BackgroundColor = colorGreen;
            colThree.DefaultCellTextState.ForegroundColor = Color.White;

            List<string> educationList = new List<string>();

            if (providerPage.Education != null && providerPage.Provider.Education.Any())
            {
                educationList = GetEducation(providerPage.Provider, "Education");

                if (educationList != null && educationList.Any())
                    AssembleECRInfo(colThree.Paragraphs, "Education", educationList);
            }

            if (providerPage.Provider.Certifications != null && providerPage.Provider.Certifications.Any())
            {
                AssembleECRInfo(colThree.Paragraphs, "Certification", GetCertifications(providerPage.Provider));
            }

            if (providerPage.Education != null && providerPage.Provider.Education.Any())
            {
                educationList = GetEducation(providerPage.Provider, "Residency");

                if (educationList != null && educationList.Any())
                    AssembleECRInfo(colThree.Paragraphs, "Residency", educationList);
            }
            //********************

            card.BackgroundColor = Aspose.Pdf.Color.LightGray;
            pageCard.Paragraphs.Add(card);
        }

        byte[] pageArray;

        using (MemoryStream pageMemoryStream = new MemoryStream())
        {
            pdfDocument.Save(pageMemoryStream, SaveFormat.Pdf);
            pageArray = pageMemoryStream.ToArray();
        }

        return pageArray;
    }

    /// <summary>
    /// Populate Specialties
    /// </summary>
    /// <param name="cellInfo"></param>
    /// <param name="provider"></param>
    private static void PopulateSpecialties(Cell cellInfo, Provider provider)
    {
        if (provider.Specialties != null && provider.Specialties.Any())
        {
            int iCnt = provider.Specialties.Count();
            int iIdx = 0;
            TextFragment fragSpecialties = new TextFragment("");
            fragSpecialties.TextState.ForegroundColor = Color.Black;
            fragSpecialties.TextState.FontSize = 11f;
            string value = string.Empty;

            foreach (string item in provider.Specialties.Select(x => x.Specialty.Name))
            {
                iIdx++;

                if (iIdx == 1)
                {
                    value = "Specialties: " + item;
                }
                else
                    value = string.Format("{0}\r\n{1}", value, item);
            }

            fragSpecialties.Text = value;
            cellInfo.Paragraphs.Add(fragSpecialties);
        }
    }

    /// <summary>
    /// Populate Locations
    /// </summary>
    /// <param name="cellInfo"></param>
    /// <param name="provider"></param>
    private static void PopulateLocations(Cell cellInfo, Provider provider)
    {
        List<string> locationList = LocationList(provider: provider);

        if (locationList != null && locationList.Any())
        {
            TextFragment fragLocationHeader = new TextFragment("\r\nLocations:");
            fragLocationHeader.TextState.ForegroundColor = Color.Black;
            fragLocationHeader.TextState.FontSize = 11f;
            fragLocationHeader.TextState.FontStyle = FontStyles.Bold;
            fragLocationHeader.Margin.Bottom = 3f;
            cellInfo.Paragraphs.Add(fragLocationHeader);
            TextFragment fragLocations = new TextFragment("");

            foreach (string item in locationList)
            {
                fragLocations.Text += item;
            }

            cellInfo.Paragraphs.Add(fragLocations);
        }
    }

    /// <summary>
    /// Location List
    /// </summary>
    /// <param name="provider"></param>
    /// <returns></returns>
    private static List<string> LocationList(Provider provider)
    {
        string address = "";
        string zip = "";
        List<string> locationList = new List<string>();

        if (provider.Clinics != null && provider.Clinics.Count > 0)
        {
            foreach (Clinic clinic in provider.Clinics)
            {
                address = null;

                if (!string.IsNullOrEmpty(clinic.Name))
                    address = clinic.Name;

                if (!string.IsNullOrEmpty(clinic.Address1))
                {
                    if (string.IsNullOrEmpty(address))
                        address = clinic.Address1;
                    else
                        address = string.Format("{0}\r\n{1}", address, clinic.Address1);
                }

                if (!string.IsNullOrEmpty(clinic.Address2))
                {
                    if (string.IsNullOrEmpty(address))
                        address = clinic.Address2;
                    else
                        address = string.Format("{0}\r\n{1}", address, clinic.Address2);
                }

                if (!string.IsNullOrEmpty(clinic.City))
                {
                    if (string.IsNullOrEmpty(address))
                        address = clinic.City;
                    else
                        address = string.Format("{0}\r\n{1}", address, clinic.City);
                }

                if (!string.IsNullOrEmpty(clinic.State))
                {
                    if (string.IsNullOrEmpty(address))
                        address = clinic.City;
                    else
                        address = string.Format("{0}, {1}", address, clinic.State);
                }

                if (!string.IsNullOrEmpty(clinic.Zip))
                {
                    if (clinic.Zip.Length > 5)
                        zip = string.Format("{0}-{1}", clinic.Zip.Substring(startIndex: 0, length: 5), clinic.Zip.Substring(startIndex: 5, length: clinic.Zip.Length - 5));
                    else
                        zip = clinic.Zip;

                    if (string.IsNullOrEmpty(address))
                        address = zip;
                    else
                        address = string.Format("{0} {1}", address, zip);
                }

                locationList.Add(string.Format("{0}\r\n\r\n", address));
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(provider.BusinessName))
                address = provider.BusinessName;

            if (!string.IsNullOrEmpty(provider.Address1))
            {
                if (string.IsNullOrEmpty(address))
                    address = provider.Address1;
                else
                    address = string.Format("{0}\r\n{1}", address, provider.Address1);
            }

            if (!string.IsNullOrEmpty(provider.Address2))
            {
                if (string.IsNullOrEmpty(address))
                    address = provider.Address2;
                else
                    address = string.Format("{0}\r\n{1}", address, provider.Address2);
            }

            if (!string.IsNullOrEmpty(provider.City))
            {
                if (string.IsNullOrEmpty(address))
                    address = provider.City;
                else
                    address = string.Format("{0}\r\n{1}", address, provider.City);
            }

            if (!string.IsNullOrEmpty(provider.State))
            {
                if (string.IsNullOrEmpty(address))
                    address = provider.City;
                else
                    address = string.Format("{0}, {1}", address, provider.State);
            }

            if (!string.IsNullOrEmpty(provider.Zip))
            {
                if (string.IsNullOrEmpty(address))
                    address = provider.ZipFormatted;
                else
                    address = string.Format("{0} {1}", address, provider.ZipFormatted);
            }

            locationList.Add(string.Format("{0}\r\n\r\n", address));
        }

        return locationList;
    }

    /// <summary>
    /// Assemble Education-Certification-Residency Info
    /// </summary>
    /// <param name="paragraphs"></param>
    /// <param name="heading"></param>
    /// <param name="infoList"></param>
    private static void AssembleECRInfo(Paragraphs paragraphs, string heading, List<string> infoList)
    {
        Aspose.Pdf.Text.TextFragment textFragmentHeading = new TextFragment();
        textFragmentHeading.TextState.ForegroundColor = Color.White;
        textFragmentHeading.TextState.FontStyle = FontStyles.Bold;
        textFragmentHeading.TextState.FontSize = 11f;
        textFragmentHeading.Text = Environment.NewLine + heading;
        paragraphs.Add(textFragmentHeading);

        Aspose.Pdf.Text.TextFragment textFragment = new TextFragment();
        textFragment.TextState.ForegroundColor = Color.White;
        textFragment.TextState.FontStyle = FontStyles.Regular;
        textFragment.TextState.FontSize = 11f;
        textFragment.Text = heading;

        int iCnt = infoList.Count();
        int iIdx = 0;

        foreach (string item in infoList)
        {
            iIdx++;

            if (iIdx == iCnt)
                textFragment.Text += item;
            else
                textFragment.Text += item + Environment.NewLine;
        }

        paragraphs.Add(textFragment);
    }

    /// <summary>
    /// Get Education
    /// </summary>
    /// <param name="provider"></param>
    private static List<string> GetEducation(Provider provider, string educationType)
    {
        List<string> education = new List<string>();

        if (provider != null && provider.Education != null && provider.Education.Any())
        {
            foreach (ProviderEducation edu in provider.Education.Where(x => x.EducationType != null).ToList())
            {
                if (edu.EducationalInstitution != null)
                {
                    switch (educationType)
                    {
                        case "Education":
                            if (edu.EducationType.IsMedSchool)
                                education.Add(FormatEducationalInstitution(edu.EducationalInstitution));

                            break;

                        case "Residency":
                            if (edu.EducationType.IsResidency)
                                education.Add(FormatEducationalInstitution(edu.EducationalInstitution));

                            break;

                        case "Fellowship":
                            if (edu.EducationType.IsFellowship)
                                education.Add(FormatEducationalInstitution(edu.EducationalInstitution));

                            break;

                        case "Internship":
                            if (edu.EducationType.IsInternship)
                                education.Add(FormatEducationalInstitution(edu.EducationalInstitution));

                            break;
                    }
                }
            }
        }

        return education;
    }

    /// <summary>
    /// Format Educational Institution
    /// </summary>
    /// <param name="educationalInstitution"></param>
    /// <returns></returns>
    private static string FormatEducationalInstitution(EducationalInstitution educationalInstitution)
    {
        string school = null; //string.Empty;

        if (!string.IsNullOrEmpty(educationalInstitution.School))
        {
            school = educationalInstitution.School;

            if (!string.IsNullOrEmpty(educationalInstitution.City))
                school += ", " + educationalInstitution.City;

            if (!string.IsNullOrEmpty(educationalInstitution.State))
                school += ", " + educationalInstitution.State;
        }

        return school;
    }

    /// <summary>
    /// Get Certifications
    /// </summary>
    /// <param name="provider"></param>
    private static List<string> GetCertifications(Provider provider)
    {
        List<string> certs = new List<string>();

        if (provider != null && provider.Certifications != null && provider.Certifications.Any())
        {
            certs = provider.Certifications.Select(x => x.Certification.Description).ToList();
        }

        return certs;
    }

    /// <summary>
    /// Get Ur lAbsolute From Inside EPiServer
    /// </summary>
    /// <param name="contentLink"></param>
    /// <param name="language"></param>
    /// <param name="urlResolver"></param>
    /// <returns></returns>
    private static string GetUrlAbsoluteFromInsideEPiServer(ContentReference contentLink, string language, UrlResolver urlResolver = null)
    {
        if (urlResolver == null)
        {
            urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>();
        }

        var url = urlResolver.GetUrl(contentLink: contentLink, language: language, virtualPathArguments: new VirtualPathArguments()
        {
            ContextMode = ContextMode.Default,
            ForceAbsolute = true
        });

        if (url.StartsWith("/"))
        {
            string baseURL = ConfigurationManager.AppSettings["BaseURL"];
            url = string.Format("{0}{1}", baseURL, url);
        }

        return url.ToString();
    }

    /// <summary>
    /// Generate QR Code URL
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private static string GenerateQRCodeURL(string url)
    {
        QRCodeHelper qrCodeHelper = new QRCodeHelper(data: url, width: 70, height: 70, encoding: QREncodingOptions.UTF, errorlevel: "7%", margin: 0);

        //Sample: "https://chart.googleapis.com/chart?cht=qr&chl=www.mywebsite.com&chs=100x100&choe=UTF-8&chld=L|4"
        //Sample: "https://chart.googleapis.com/chart?cht=qr&chl=www.mywebsite.com&chs=80x80&choe=UTF-8&chld=7%|0"
        return qrCodeHelper.GenerateUrl();
    }

    /// <summary>
    /// Get Cover Page
    /// </summary>
    /// <returns></returns>
    private static BinaryStorage GetCoverPage()
    {
        BinaryStorage coverPageBinary = null;

        using (MosaicContext dbContext = new MosaicContext())
        {
            var avCoverPage = dbContext.ApplicationVariables.Where(x => x.Name == "ProviderDirectoryCoverPageId").FirstOrDefault();


            if (Int32.TryParse(avCoverPage.ValueString, out int coverPageId))
                coverPageBinary = dbContext.BinaryStorage.Where(x => x.Id == coverPageId).FirstOrDefault();
        }

        return coverPageBinary;
    }

    /// <summary>
    /// Get Provider Page URLs
    /// </summary>
    /// <param name="providerPages"></param>
    /// <returns></returns>
    public static List<string> GetProviderPageURLs(List<ProviderDetailsPage> providerPages)
    {
        List<string> urls = new List<string>();

        foreach (ProviderDetailsPage page in providerPages)
        {
            urls.Add(GetUrlAbsoluteFromInsideEPiServer(page.ContentLink, page.Language.Name));
        }

        return urls;
    }

    /// <summary>
    /// Get Provider Image URLs
    /// </summary>
    /// <param name="providerPages"></param>
    /// <returns></returns>
    public static List<string> GetProviderImageURLs(List<ProviderDetailsPage> providerPages)
    {
        List<string> urls = new List<string>();
        string baseURL = ConfigurationManager.AppSettings["BaseURL"];
        var urlHelper = _serviceLocator.Service.GetInstance<UrlHelper>();

        foreach (ProviderDetailsPage page in providerPages)
        {

            urls.Add(string.Format("{0}{1}", baseURL, urlHelper.ContentUrl(page.ProviderImageUrl)));
        }

        return urls;
    }
}

@TeamHog

Could you please share the environment details where this exception is being occurred. If it is a non-Windows environment, please make sure to install libgdiplus package. Please share a narrowed down sample code snippet in case issue still happens so that we can test the scenario in our environment and address it accordingly.

Our server is a windows server. Here is the narrowed down code.

///


/// Generate PDF Simple
///

///
///
public ActionResult GeneratePDFSimple(int cardCount = 10)
{
byte[] pdf = ProviderDirectoryHelper.CreatePDFSimple(cardCount);
return new FileContentResult(pdf, “application/pdf”) { FileDownloadName = “PDFSimple.pdf” };
}

///


/// Create PDF Simple
///

///
///
public static byte[] CreatePDFSimple(int cardCount)
{
//*******************************
//*** Load the Aspose License ***
//*** //https://github.com/aspose-pdf/Aspose.PDF-for-.NET
//*******************************
License pdflic = new License();
// specify the embedded file information. MergedAPI is default namespace of project
pdflic.SetLicense(“xxx.Aspose.Total.lic”);
// embed the license file within solution
pdflic.Embedded = true;
//*******************************
        //*************************
        //*** Base PDF Document ***
        //*************************
        Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document();
        pdfDocument.PageInfo.Height = Aspose.Pdf.PageSize.A4.Height;
        pdfDocument.PageInfo.Width = Aspose.Pdf.PageSize.A4.Width;
        pdfDocument.PageInfo.Margin = new MarginInfo
        {
            Left = 0f,
            Right = 0f,
            Top = 0f,
            Bottom = 0f
        };
        //*************************

        //******************
        //*** Cover Page ***
        //******************

        Page pageCover = pdfDocument.Pages.Add();
        pageCover.Background = Aspose.Pdf.Color.White;
        pageCover.PageInfo.Margin = new MarginInfo
        {
            Left = 0f,
            Right = 0f,
            Top = 0f,
            Bottom = 0f
        };

        byte[] dataImage = GetImageFromURL("https://www.aspose.com/templates/brand/images/pdf/aspose_pdf-brand.png");
        using (MemoryStream coverMemoryStream = new MemoryStream(dataImage))
        {
            pageCover.AddImage(coverMemoryStream, pageCover.GetPageRect(false));
        }
        //******************

        //*************
        //*** Cards ***
        //*************
        Page pageCard = pdfDocument.Pages.Add();
        pageCard.Background = Aspose.Pdf.Color.White;
        pageCard.PageInfo.Margin = new MarginInfo
        {
            Left = 0f,
            Right = 0f,
            Top = 0f,
            Bottom = 0f
        };

        float pageWidth = Aspose.Pdf.PageSize.A4.Width;
        string colOneWidth = (pageWidth * 0.22d).ToString();

        float colTwoLength = pageWidth * 0.395f;
        string colTwoWidth = (colTwoLength).ToString();

        float colThreeLength = pageWidth * 0.395f;
        string colThreeWidth = (colThreeLength).ToString();
        Color colorGreen = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.FromArgb(46017)); //RGBA Hex = 00B3C1)

        BorderInfo borderGreen = new BorderInfo
        {
            Bottom = new GraphInfo()
        };
        borderGreen.Bottom.Color = colorGreen;
        borderGreen.Bottom.LineWidth = 3f;

        BorderInfo borderWhite = new BorderInfo
        {
            Bottom = new GraphInfo()
        };
        borderWhite.Bottom.Color = Aspose.Pdf.Color.White;
        borderWhite.Bottom.LineWidth = 3f;

        for (int idxCard = 1; idxCard < cardCount; idxCard++)
        {
            Aspose.Pdf.Table cardTable = new Aspose.Pdf.Table
            {
                DefaultColumnWidth = pageWidth.ToString(),

                // Set with column widths of the table
                ColumnWidths = string.Format("{0} {1} {2}", colOneWidth, colTwoWidth, colThreeWidth),
            };

            string cardURL = "https://products.aspose.com/pdf";

            // Create rows in the table and then cells in the rows
            Aspose.Pdf.Row row = cardTable.Rows.Add();

            //******************
            //*** Column One ***
            //******************
            Aspose.Pdf.Cell colOne = row.Cells.Add();
            colOne.Margin = new MarginInfo
            {
                Top = 34d,
                Left = 34d,
                Right = 0d,
                Bottom = 10d
            };
            colOne.BackgroundColor = Aspose.Pdf.Color.White;
            colOne.Border = borderGreen;
            colOne.Alignment = HorizontalAlignment.Left;
            colOne.VerticalAlignment = VerticalAlignment.Top;

            Aspose.Pdf.Image cardImage = new Aspose.Pdf.Image
            {
                File = "https://www.aspose.cloud/templates/aspose/App_Themes/V3/images/pdf/272x272/aspose_pdf-for-net.png",
                FixHeight = 130d,
                FixWidth = 140d
            };
            colOne.Paragraphs.Add(cardImage);

            //QRCode
            Aspose.Pdf.Image qrCodeImage = new Aspose.Pdf.Image
            {
                File = GenerateQRCodeURL(cardURL),
                FixHeight = 70d,
                FixWidth = 70d,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Bottom,
                Margin = new MarginInfo
                {
                    Top = 6d,
                    Left = 0d,
                    Right = 0d,
                    Bottom = 0d
                },
            };

            colOne.Paragraphs.Add(qrCodeImage);
            //******************

            //******************
            //*** Column Two ***
            //******************
            Aspose.Pdf.Cell colTwo = row.Cells.Add("");
            colTwo.Margin = new MarginInfo
            {
                Top = 25d,
                Left = 22d,
                Right = 22d,
                Bottom = 0d
            };
            colTwo.BackgroundColor = Color.White;
            colTwo.Border = borderGreen;
            colTwo.IsWordWrapped = true;
            colTwo.Alignment = HorizontalAlignment.Left;
            colTwo.VerticalAlignment = VerticalAlignment.Top;

            //Card Info
            TextFragment fragPageLink = new TextFragment(string.Format("Card {0}", idxCard))
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                Hyperlink = new WebHyperlink(cardURL)
            };

            fragPageLink.TextState.ForegroundColor = Color.Blue;
            fragPageLink.TextState.FontStyle = FontStyles.Bold;
            fragPageLink.TextState.FontSize = 11f;
            fragPageLink.Margin.Bottom = 3f;
            colTwo.Paragraphs.Add(fragPageLink);
            //******************

            //********************
            //*** Column Three ***
            //********************
            Aspose.Pdf.Cell colThree = row.Cells.Add("");
            colThree.Margin = new MarginInfo
            {
                Top = 0d,
                Left = 22d,
                Right = 22d,
                Bottom = 0d
            };
            colThree.Border = borderWhite;
            colThree.DefaultCellTextState.ForegroundColor = Aspose.Pdf.Color.White;
            colThree.BackgroundColor = colorGreen;
            colThree.DefaultCellTextState.ForegroundColor = Color.White;
            //********************

            cardTable.BackgroundColor = Aspose.Pdf.Color.LightGray;
            pageCard.Paragraphs.Add(cardTable);
        }

        byte[] pageArray;

        using (MemoryStream pageMemoryStream = new MemoryStream())
        {
            pdfDocument.Save(pageMemoryStream, SaveFormat.Pdf);
            pageArray = pageMemoryStream.ToArray();
        }

        return pageArray;
    }

    private static byte[] GetImageFromURL(string url)
    {
        byte[] dataArr = null;

        using (WebClient webClient = new WebClient())
        {
            dataArr = webClient.DownloadData(url);
        }

        return dataArr;
    }

@TeamHog

We are looking into it and will get back to you shortly.

@TeamHog

We tested the scenario in our environment and could not notice/replicate the issue that you mentioned. We tested the case using Aspose.PDF for .NET 21.2. It seems like the error is related to saving of image which is not yet downloaded or has been disposed of. Would you kindly try to test the scenario using latest version of the API and let us know in case issue still persists.

Was your test down within Visual Studio or did you deploy the site?

We would like to know what your ASPOSE code is saving and where to? This is the error your internal code is throwing. Does your code try to save to disk?

at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at Aspose.Pdf.Image.#=zmYNWndA=(String #=zU3JopbM=) at Aspose.Pdf.Image.#=zwYl5uwk=(Double& #=z0vx1X_s=, Double& #=zNlbvMUg=, Double& #=zV8HuGkM=, Boolean #=z7n4ociiD2a0t, MarginInfo #=zKPvYDC0=, Double #=zb3uiWh2iQua2, Double #=zp1wo_jc=, Page #=zjjW15wQ=, List1 #=zzSaZ$l4=, Boolean #=zjD3iGRm2R8cH, Boolean #=zkjbyHw2V_cmP, Boolean #=zo3qqxC0=, Paragraphs& #=zzP4X4QkFAd7pTo3AXg==, Double #=z1r3jrBo4AERhPph0kg==, Double #=zspnZeVs=, Int32 #=zXH4dLBfowudSP4R5rTJL$sk=) at #=zY9GaegCLTwV6ufBvBLKjZyY=.#=zwYl5uwk=() at Aspose.Pdf.Cell.#=z1OazhyL7ilJ1(Table #=zPJF0cRU=, Double #=zFX7ZxNU=, Page #=zjjW15wQ=, Double #=zspnZeVs=, Double #=zV8HuGkM=, Boolean #=zBTtRI2RWsb3_XEeWKUW6KV4=) at Aspose.Pdf.Row.#=zQ6ZPIenA$3Qc7OyPOw==(Table #=zPJF0cRU=, Page #=zjjW15wQ=, Double #=zV8HuGkM=, Double #=zspnZeVs=, Int32 #=zkRPHzV4=) at Aspose.Pdf.Row.#=zwYl5uwk=(Table #=zPJF0cRU=, Double& #=zV8HuGkM=, Double& #=z0vx1X_s=, Boolean #=zjD3iGRm2R8cH, Double #=z7zTpG83LkQ_P, Double #=zspnZeVs=, Page #=zjjW15wQ=, Int32& #=zZ6C2WWJSmFAe) at Aspose.Pdf.Table.#=zwYl5uwk=(Double& #=z0vx1X_s=, Double& #=zV8HuGkM=, Boolean #=zjD3iGRm2R8cH, Double #=zvtp9HdZHlHbq, Double #=zspnZeVs=, Page #=zjjW15wQ=, Boolean #=zUNLkfSu7xd4v, List1 #=zzSaZ$l4=) at #=zY9GaegCLTwV6ufBvBLKjZyY=.#=zwYl5uwk=() at Aspose.Pdf.Page.#=zo01hIao=(Page #=zjjW15wQ=) at Aspose.Pdf.Page.#=zPyFghwFyZl_uw34oxg==() at Aspose.Pdf.Document.ProcessParagraphs() at Aspose.Pdf.Document.#=zX0JuM$$nMZfL(Stream #=zu6xQV10=, SaveOptions #=zNM2u7RsscuCD) at Aspose.Pdf.Document.#=zD90fPvhST9SM(Stream #=z_oI$NCBLFtmI, SaveOptions #=zmSsktBU=) at Aspose.Pdf.Document.Save(Stream outputStream, SaveFormat format) at Mosaic.Framework.Helpers.ProviderDirectoryHelper.CreatePDFSimple(Int32 cardCount) in C:\Code\SVN\branches\MVC-5.2.5\Mosaic\Framework\Helpers\ProviderDirectoryHelper.cs:line 1164 at Mosaic.Areas.Caregiver.Controllers.ProviderDirectoryController.GeneratePDFSimple(Int32 cardCount) in C:\Code\SVN\branches\MVC-5.2.5\Mosaic\Areas\Caregiver\Controllers\ProviderDirectoryController.cs:line 509 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.b__0() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_6.b__4() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.b__1(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

@TeamHog

We tested the scenario in Visual Studio. Could you please share the server details where your web application is deployed? We need to investigate the case in details and as soon as we have the details of your production environment, we will log an investigation ticket and will share the ID with you.

PS: Please also try to use 21.2v of the API and see if issue still persists.

What details about our production server do you need to know?

@TeamHog

You may please share the OS details (name and version) and .NET Core version.

We are on Windows Server 2016 and .NET framework 4.8

@TeamHog

The issue seems related to your specific environment. We tested the scenario in a Windows Server environment using Aspose.PDF for .NET 21.2 and did not notice any issue. As requested earlier, could you please try to test the latest version at your side and let us know in case the issue still persists?

Our license has expired so I can’t upgrade to the newest in our production domain. We were hoping to resolve this issue before updating the license.

@TeamHog

You can please get a 30-days free temporary license in order to evaluate the latest version of the API and let us know about the results you notice.

I believe I have found the issue. This code fails in our production domain. Instead of using File property of your Image class, ImageStream works. It looks like your internal code cannot handle a url that needs to download an image.

Aspose.Pdf.Image cardImage = new Aspose.Pdf.Image
{
File = “https://www.aspose.cloud/templates/aspose/App_Themes/V3/images/pdf/272x272/aspose_pdf-for-net.png”,
FixHeight = 130d,
FixWidth = 140d
};
colOne.Paragraphs.Add(cardImage);

@TeamHog

It is good to know that you were able to resolve your issue. Please keep using our API and feel free to let us know in case you need further assistance.