加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Html to pdf一些字符丢失(itextsharp)

发布时间:2020-12-15 17:36:24 所属栏目:百科 来源:网络整理
导读:我想通过使用itextsharp库将gridview导出为pdf.问题是在pdf文档中缺少一些土耳其字符,如?,?,?,?等.用于导出pdf的代码是: protected void LinkButtonPdf_Click(object sender,EventArgs e) { Response.ContentType = "application/pdf"; Response.ContentEnc
我想通过使用itextsharp库将gridview导出为pdf.问题是在pdf文档中缺少一些土耳其字符,如?,?,?,?等.用于导出pdf的代码是:
protected void LinkButtonPdf_Click(object sender,EventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.AddHeader("content-disposition","attachment;filename=FileName.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        System.IO.StringWriter stringWrite = new StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        StringReader reader = new StringReader(textConvert(stringWrite.ToString()));
        Document doc = new Document(PageSize.A4);
        HTMLWorker parser = new HTMLWorker(doc);
        PdfWriter.GetInstance(doc,Response.OutputStream);
        doc.Open();
        parser.Parse(reader);
        doc.Close();
    }
    public static string textConvert(string S)
    {
        if (S == null) { return null; }
        try
        {
            System.Text.Encoding encFrom = System.Text.Encoding.UTF8;
            System.Text.Encoding encTo = System.Text.Encoding.UTF8;
            string str = S;
            Byte[] b = encFrom.GetBytes(str);
            return encTo.GetString(b);
        }
        catch { return null; }
    }

注意:当我想在pdf文档中插入字符时,会显示缺少的字符.我用这段代码插入字符:

BaseFont bffont = BaseFont.CreateFont("C:WINDOWSFontsarial.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        Font fontozel = new Font(bffont,12,Font.NORMAL,new Color(0,0));
        doc.Add(new Paragraph("????????????",fontozel));

解决方法

最后我想我找到了解决方案,我改变了它的一些源代码,以显示土耳其字符(土耳其语字符代码是cp1254)

I add “public const string CP1254 = "Cp1254";” to [BaseFont.cs] in the source code.

After that I modify the [FactoryProperties.cs].I changed like this;

public Font GetFont(ChainedProperties props)
{
I don't write the whole code.I changed only code below;
------------Default itextsharp code------------------------------------------------------
  if (encoding == null)
                encoding = BaseFont.WINANSI;
            return fontImp.GetFont(face,encoding,true,size,style,color);
-------------modified code--------------------------------------------

            encoding = BaseFont.CP1254;
            return fontImp.GetFont("C:WINDOWSFontsarial.ttf",color);
}

在编译新的dll之后,显示缺少的字符.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读