简体   繁体   English

带有中文字符的 PDFSharp

[英]PDFSharp with Chinese characters

I have problem with displaying Chinese characters in PDFSharp in C#.我在 C# 中的 PDFSharp 中显示中文字符时遇到问题。 During process of creating the PDF string it's ok, but after creating pdf file it doesn't display it.在创建 PDF 字符串的过程中没问题,但在创建 pdf 文件后它不显示它。 I found one solution which is我找到了一种解决方案

XFont font_small2 = new XFont("微软雅黑", 9, XFontStyle.Regular, options)

This solutions works on my localhost but when I release this on beta server it doesn't display Chinese characters.此解决方案适用于我的本地主机,但是当我在测试版服务器上发布它时,它不显示中文字符。

You can embed original Chinese font into your pdf file and use correct CMAP.您可以将原始中文字体嵌入到您的 pdf 文件中并使用正确的 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;

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.确保字体嵌入在 PDF 文件中。

According to the PDFsharp FAQ, CJK fonts are not supported.根据 PDFsharp FAQ,不支持 CJK 字体。 But still you should get the same results on server and local computer if the environments are set up correctly.但是,如果环境设置正确,您仍然应该在服务器和本地计算机上获得相同的结果。

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:这两种解决方案都不适用于较新版本的 lib,因此我想出了一种将字符绘制到位图,然后将位图添加到 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);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM