1. 程式人生 > 實用技巧 >iTextSharp 生成pdf時 部分資訊用中文等顯示

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