empira / PDFsharp

PDFsharp and MigraDoc Foundation for .NET 6 and .NET Framework
https://docs.pdfsharp.net/
Other
531 stars 132 forks source link

[Suggestion] Avoid hardcoded font name in MigraDoc.Rendering.Rendering.ImageRenderer.cs #162

Open pihalve opened 2 months ago

pihalve commented 2 months ago

In MigraDoc.Rendering.Rendering.ImageRenderer.cs class the RenderFailureImage method uses a hardcoded font name.

XFont font = new XFont("Courier New", 8);

This doesn't work using MigraDoc in an application hosted as a Docker container on a Linux-based Kubernetes cluster. Throws this exception:

System.InvalidOperationException: No appropriate font found for family name 'Courier New'.

Yes, that should be a good hint to the problem, but not being familiar with the MigraDoc code base, it took me a while to figure out, that the issue was caused by a hardcoded font name. So at a minimum I hope this suggestion can serve as useful information to others experiencing the same issue.

What I did to solve the issue was to implement a custom font resolver - I needed one anyway - and have it also resolve the Courier New font. So basically, I included all the fonts I needed as embedded resources in the assembly, and then had the custom font resolver load the embedded fonts when requested.

However, in my opinion it would be nice if MigraDoc didn't hardcode font names. Instead perhaps make it possible to configure a default font to be used in these special cases, such as showing a text that an image couldn't be found.

Neralem commented 2 months ago

I've stumbled across this issue too. I use MigraDoc in my MAUI App to create PDF Reports. At least on Android there is not a single font that can be loaded automatically. So I embedded my own font in the assembly and wrote an IFontResolver implementation that gets that font. This is where I've noticed that MigraDoc invokes this FontResolver with Courier New even when setting the Font in the "Normal" style to my custom font. From my understanding this should change the font in the whole document. I just ignore that in my case and return my font instead.