Intermittent errors trying to get text width

Using GemBox PDF version 17.0.1342.
Error occurs intermittently on Windows Server 2016 Datacenter.

The code causing the error (in simplified form), looks like this:

using GemBox.Pdf.Content;

        public double GetTextWidth()
        {
            string fontFamilyName = "Verdana";
            double fontSize = 6;
            PdfFontFamily fontFamilyToUse = new PdfFontFamily(fontFamilyName);

            string text = "999 of 999";

            double width;

            // work out width
            using (var formattedText = new PdfFormattedText())
            {
                formattedText.FontFamily = fontFamilyToUse;                
                formattedText.FontSize = fontSize;

                formattedText.Append(text);

                width = formattedText.Width;                
            }

            return width;
        }

When GetTextWidth is called, it sometimes throws a Win32Exception:

Exception: System.ComponentModel.Win32Exception
Exception Message: An attempt was made to reference a token that does not exist

Stack trace:
   at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D wc_d)
   at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
   at System.Windows.Threading.Dispatcher..ctor()
   at System.Windows.Threading.Dispatcher.get_CurrentDispatcher()
   at   ..ctor(Boolean ,    , Double )
   at   .(   , Boolean , Double )
   at GemBox.Pdf.Content.PdfFormattedText.()
   at GemBox.Pdf.Content.PdfFormattedText.()

The Win32Exception NativeErrorCode is 1008, which in hex is: 0x000003F0 , ERROR_NO_TOKEN
in: [MS-ERREF]: Win32 Error Codes | Microsoft Learn

The code is running in a Windows Service, and GetTextWidth() will get called many times.
Any ideas ?

Hi,

It seems there is an issue with the WPF Dispatcher.
Just in case, please try again with this bugfix:

Install-Package GemBox.Pdf -Version 17.0.1396-hotfix

If the problem remains, can you try using the PdfTextFormattingMode.HarfBuzz like the following to avoid the usage of WPF:

using (var formattedText = new PdfFormattedText())
{
    formattedText.TextFormattingMode = PdfTextFormattingMode.HarfBuzz;
    formattedText.FontFamily = fontFamilyToUse;
    formattedText.FontSize = fontSize;

    formattedText.Append(text);
    width = formattedText.Width;
}

I hope this helps.

Regards,
Mario

Thanks Mario. The windows service application is running in .NET Framework 4.7.2, and does not (explicitly) use WPF. For my understanding: will that code for GetTextWidth() I’ve shown, use WPF under the hood, for this type of app ?

Yes exactly, please check the PdfTextFormattingMode enum.

Last, note that for the PdfTextFormattingMode.HarfBuzz you’ll need to have a HarfBuzzSharp package installed: