user1691840
user1691840

Reputation: 13

iTextSharp with special characters

I have an aspx form in which user takes a survey and the survey is saved to the database. After saving to the database, the survey responses given by the user are displayed so the user can save the response as pdf.

This is the function to save as 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();
}

It works fine and everything is well. The form has some text boxes. The user can enter text into the textbox. Sometimes, the user enters mathematical symbols like <, >, =. To make sure that the textbox value is saved to the database, the following ValidateRequest="false" has been done in the aspx file. But, the SaveAsPDF throws up an error as it is unable to parse these symbols.

I am pretty sure it is mostly these special symbols causing the issue with the

htmlparser.Parse(sr) method

because if there are no special symbols in the text boxes, PDF is generated fine.

Could you help me out on what I can do?/ Any pointers.

Thank you.

Upvotes: 0

Views: 3238

Answers (1)

Furqan Safdar
Furqan Safdar

Reputation: 16698

You should first encode the input text by using HttpUtility.HtmlEncode before processing the text and performing the save.

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

Upvotes: 4

Related Questions