Home > DeveloperSection > Forums > Getting error to generate pdf
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    April-09-2013 2:18 AM

 ASP.Net ASP.Net 
Ratings:


 2 Reply(s)
 981  View(s)
Rate this:
Hi All!

protected void txt_btn_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=TestResult.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringBuilder htmlText = new StringBuilder();
    htmlText.Append("<table style='color:red;' border='1'><tr><th>createing pdf</th><tr><td> abcdef</td></tr></table>");

    StringReader stringReader = new StringReader(htmlText.ToString());
    Document doc = new Document(PageSize.A4);
    List<iTextSharp.text.IElement> elements =
            iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(stringReader, null);
    doc.Open();
    foreach (object item in elements)
    {
        doc.Add((IElement)item);
    }
    doc.Close();
    // Response Output
    PdfWriter.GetInstance(doc, Response.OutputStream);
    doc.Open();

    //doc.Close();

    Response.Write("PDF is created");
}
}

I am try to create pdf file.But pdf is created only 0kb.Mean when i open this it's shw error that May be pdf damaged

Thank you in advance!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    April-09-2013 7:45 AM

Hi Jeet!

you are using iTextSharp library so try as below

private void GeneratePDF()
    {
        try
        {
            string pdfPath = "~/PDF/File_1.pdf";
            StringBuilder sb = new StringBuilder();
            sb.Append("Name : chamara" + Environment.NewLine);
            sb.Append("Address : sri lanaka" + Environment.NewLine);
            sb.Append("Institute : SLIIT" + Environment.NewLine);
            Document doc = new Document();
            PdfWriter.GetInstance(doc, new FileStream(Server.MapPath(pdfPath), FileMode.Create));
            doc.Open();
            doc.Add(new Paragraph(sb.ToString()));
            doc.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Ely Sanders

Total Post:3

Points:21
Posted on    January-07-2014 4:43 AM

Hi, you can also try the following:

protected void txt_btn_Click(object sender, EventArgs e)
{
   
var doc = new DocumentModel();
   
string htmlText = "<table style='color:red;' border='1'><tr><th>createing pdf</th><tr><td> abcdef</td></tr></table>";
    doc.Content.LoadText(htmlText,
LoadOptions.HtmlDefault);
    doc.Save(
this.Response, "TestResult.pdf", SaveOptions.PdfDefault);
}

I believe this will simplify your code a bit. I used this C# Word component, it has a direct API call for exporting PDF files in ASP.NET.


Don't want to miss updates? Please click the below button!

Follow MindStick