带特殊字符的iTextSharp

问题描述:

我有一个aspx表单,用户在其中进行调查并将调查保存到数据库。保存到数据库后,会显示用户给出的调查答复,以便用户可以将答复保存为pdf。带特殊字符的iTextSharp

这是为了保存为PDF

//Save as PDF 
protected void SaveAsPDF_Click(object sender, EventArgs e) 
{ 
    Random nRandom = new Random(DateTime.Now.Second); 
    string strFileName = nRandom.Next().ToString() + ".pdf"; 
    string target = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["NewResponsePDF"].ToString() + strFileName); 

    string filepath = target; 
    string filename = Path.GetFileName(filepath); 

    Response.Clear(); 
    Response.ContentType = "application/pdf"; 
    Response.AddHeader("content-disposition", "attachment;filename=" + filename); 

    Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    StringWriter sw = new StringWriter(); 
    HtmlTextWriter hw = new HtmlTextWriter(sw); 
    this.Page.Form.RenderControl(hw); 
    StringReader sr = new StringReader(sw.ToString()); 
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); 
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc); 
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream); 
    pdfDoc.Open(); 
    htmlparser.Parse(sr); 
    pdfDoc.Close(); 
    Response.Write(pdfDoc); 
    Response.End(); 
} 

它工作正常,一切都很好的功能。该表格有一些文本框。用户可以在文本框中输入文本。有时,用户输入数学符号,如<,>,=。为确保将文本框值保存到数据库中,以下ValidateRequest="false"已在aspx文件中完成。但是,SaveAsPDF抛出一个错误,因为它无法解析这些符号。

我敢肯定它主要是导致该问题与

htmlparser.Parse(sr)方法

,因为如果在文本框中没有特殊符号,生成PDF精细这些特殊符号。

你能帮我解决我能做什么吗?/任何指针。

谢谢。

在处理文本并执行保存之前,应首先使用HttpUtility.HtmlEncode对输入文本进行编码。

http://msdn.microsoft.com/en-us/library/73z22y6h.aspx