我想通過使用itextsharp庫將gridview導出爲pdf。問題在於pdf文檔中缺少一些土耳其字符,例如©,ı,Ş,等等。用於導出PDF的代碼是:HTML到pdf某些字符丟失(itextsharp)
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:\\WINDOWS\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font fontozel = new Font(bffont, 12, Font.NORMAL, new Color(0, 0, 0));
doc.Add(new Paragraph("İİııŞŞşşĞĞğğ", fontozel));
這完美的作品。特別是當出口gridview到PDF。非常感謝。 – bselvan 2013-01-31 09:55:22
謝謝。它在一開始並不起作用。除您之外,我搜索整個項目並更改所有「BaseFont.WINANSI」 - >「BaseFont.CP1254」。然後它完美地工作。 – VVovoVV 2013-10-07 08:45:02