ststeiger / PdfSharpCore

Port of the PdfSharp library to .NET Core - largely removed GDI+ (only missing GetFontData - which can be replaced with freetype2)
Other
1.06k stars 235 forks source link

FontResolver - 'Must not change font resolver after is was once used.' #156

Open Revenantus556 opened 3 years ago

Revenantus556 commented 3 years ago

I'm getting a 'Must not change font resolver after is was once used.' error when GlobalFontSettings.FontResolver = new FontResolver(); is the very first line of a LINQPad query. I'm using the version 1.2.16 NuGet package.

The FontResolver class is taken from the example on the project front page (with a DefaultFontName added to complete the updated IFontResolver interface).

Am I doing something incorrectly or if not is there a workaround for this? The goal is to embed a custom barcode font into the generated PDF.

Thanks for your help.

MagnusJohansson commented 2 years ago

I just got this as well. In my case, PdfSharpCore is inside a DI container (ASPNet Core) service, so I registered the service as a singleton (as opposed to a Scoped one). Works for my use case.

I suppose you also can check if you already has assigned your custom resolver before you try to assign it:

  if (PdfSharpCore.Fonts.GlobalFontSettings.FontResolver is not CustomFontResolver)
  {
    PdfSharpCore.Fonts.GlobalFontSettings.FontResolver = new CustomFontResolver();
  }
PSanilP commented 8 months ago

I had this issue as well. Resolved ` [HttpGet] [Route("[controller]/sample/{text?}")] public FileContentResult Get_sample(string text) { try { var document = new PdfDocument(); document.Info.Title = "Created with PDFsharp";

        PdfPage page = document.AddPage();

        XGraphics gfx = XGraphics.FromPdfPage(page);

        if (PdfSharp.Fonts.GlobalFontSettings.FontResolver is null)
        {
           GlobalFontSettings.FontResolver = new FileFontResolver();
        }

        XFont font = new XFont("Arial", 20, XFontStyleEx.BoldItalic);

        gfx.DrawString("Hello, " + text + "!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);

        // Save the document...

        byte[]? response = null;
        using (MemoryStream stream = new MemoryStream())
        {
           document.Save(stream);
           response = stream.ToArray();
        }

        string filename = "Sample_" + text + ".pdf";

        return File(response, "application/pdf", filename);
     }
     catch
     {
        return new FileContentResult(new byte[] { }, "application/pdf");
     }

  }

`

pdqsoftware commented 5 months ago

Thank you @PSanilP , your solution of checking GlobalFontSettings.FontResolver for null helped me resolve my problem.