empira / PDFsharp

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

How to use Chinese fonts? #114

Closed HmgsLJ closed 2 months ago

HmgsLJ commented 2 months ago

First thanks to the author for providing a good library, but I had a problem with version 6.0, that is, using Chinese fonts will make an error, what can I do to solve it.

Error:

System.InvalidOperationException:“No appropriate font found for family name '宋体'. Implement IFontResolver and assign to 'GlobalFontSettings.FontResolver' to use fonts.”

Code:

           // 创建一个新的PDF文档
           using (PdfDocument document = new PdfDocument())
           {
               // 添加一页
               PdfPage page = document.AddPage();
               XGraphics gfx = XGraphics.FromPdfPage(page);
               // 加载字体
               //XFont font = new XFont("simsun.ttc", 12, XFontStyleEx.Regular);
               XFont font = new XFont("宋体", 12, XFontStyleEx.Regular);

               // 绘制中文文本
               gfx.DrawString("你好,世界!", font, XBrushes.Black, new XRect(50, 50, page.Width, page.Height), XStringFormats.TopLeft);

               // 保存PDF文档
               string outputPath = "D://output.pdf";
               document.Save(outputPath);
           }
ThomasHoevel commented 2 months ago

The answer to your question is in the error message: Implement IFontResolver or use either the GDI or WPF build.

See also:
https://docs.pdfsharp.net/PDFsharp/Topics/Fonts/About.html

HmgsLJ commented 2 months ago

问题的答案在错误消息中:实现或使用 GDI 或 WPF 生成。IFontResolver

另请参阅:https://docs.pdfsharp.net/PDFsharp/Topics/Fonts/About.html

Yes, I saw it, felt my stupidity, the problem was solved, implementing IFontResolver fixed the problem

ThomasHoevel commented 2 months ago

No need to feel stupid. This is a breaking change that needs some explanation and we are trying to improve this error message even further.

HmgsLJ commented 2 months ago

No need to feel stupid. This is a breaking change that needs some explanation and we are trying to improve this error message even further.

Thank you .