iTextSharp 生成pdf时 部分信息用中文等显示

在ParseXHtml时用重写的IFontProvider

因为除了一部分信息可能有中文外  其余是英文 保留TIMES_ROMAN字体

因此重写的代码为

public Font GetFont(
                string fontname,
                string encoding,
                bool embedded,
                float size,
                int style,
                BaseColor color)
            {
                BaseFont font = null;
                try
                {
                    if (string.Equals(fontname, "STSong-Light"))
                    {
                        font = BaseFont.CreateFont(GetAppsetting.GetValue("WebDataFileDir")  + "\\simsun.TTF", BaseFont.IDENTITY_H,
                            BaseFont.NOT_EMBEDDED);
                        size = 7;
                    }
                    else
                    {
                        font = BaseFont.CreateFont(FontFactory.TIMES_ROMAN, FontFactory.DefaultEncoding, true);
                    }
                }
                catch (System.Exception e)
                {
                    // do something
                }
                return new Font(font, size, style);
            }
            public bool IsRegistered(string fontname)
            {
                return true;
            }

 

 

public static byte[] ConvertHtml(byte[] htmlText)
        {
            try
            {
                if (htmlText == null || htmlText.Length == 0)
                {
                    return null;
                }
                MemoryStream outputStream = new MemoryStream();
                byte[] data = htmlText;
                MemoryStream msInput = new MemoryStream(data);
                Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
                PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
                PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
                doc.Open();
                XMLWorkerHelper.GetInstance()
                    .ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new SmartUIFontProvider());
                PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                writer.SetOpenAction(action);
                doc.Close();
                msInput.Close();
                outputStream.Close();
                return outputStream.ToArray();
            }
            catch(System.Exception e)
            {
                return null;
            }
        }

  

 模板内容的style加上 font-family:STSong-Light

 

上一篇:iTextSharp: 从PDF文件中复制指定的页面到一个新的PDF文件


下一篇:web端生成pdf