PDFSharp with Chinese characters

前端 未结 3 1759
野性不改
野性不改 2021-01-20 16:23

I have problem with displaying Chinese characters in PDFSharp in C#. During process of creating the PDF string it\'s ok, but after creating pdf file it doesn\'t display it.

相关标签:
3条回答
  • 2021-01-20 16:50

    Neither of the solutions worked for a newer version of the lib, so I came up with a workaround on drawing chars to a bitmap, then adding the bitmap to a PDF:

            Font font = GetFont(fieldInfo, fontSize * 0.97f); // Chosen empirically
            using (var imageStream = new MemoryStream())
            {
                // Draw string as an image
                using (var bitmap = new Bitmap((int) fieldRect.Width, (int) (fieldRect.Height * 1.5f)))
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                    graphics.DrawString(fieldValue, font, Brushes.Black, PointF.Empty);
                    bitmap.Save(imageStream, ImageFormat.Png);
                }
    
                // Draw image on PDF
                using (XImage xImage = XImage.FromStream(imageStream))
                {
                    double labelPositionX = fieldRect.X1 + 2;
                    double labelPositionY = fieldRect.Y2 - 2;
                    xGraphics.DrawImage(xImage, labelPositionX, page.Height - labelPositionY);
                }
            }
    
    0 讨论(0)
  • 2021-01-20 16:52

    Make sure the font is installed correctly on the beta server and make sure application has sufficient rights. Make sure the font is embedded in the PDF file.

    According to the PDFsharp FAQ, CJK fonts are not supported. But still you should get the same results on server and local computer if the environments are set up correctly.

    0 讨论(0)
  • 2021-01-20 17:06

    You can embed original Chinese font into your pdf file and use correct CMAP.

    var options = new XPdfFontOptions(PdfFontEmbedding.Always);
    var font = new XFont("微软雅黑", 9, XFontStyle.Regular, options);
    

    OR

    var page = new PdfPage();
    var gfx = XGraphics.FromPdfPage(page);
    gfx.MFEH = PdfFontEmbedding.Automatic;
    
    0 讨论(0)
提交回复
热议问题