Open Revenantus556 opened 3 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();
}
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");
}
}
`
Thank you @PSanilP , your solution of checking GlobalFontSettings.FontResolver
for null helped me resolve my problem.
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.