create pdf from current page ASP.NET

1.2k views Asked by At

I want to create a PDF from my current page on button click. Now my Code looks like that:

protected void btnSave_Click(object sender, EventArgs e)
{           
     renderPDF = true;
}

protected override void Render(HtmlTextWriter writer)
    {
        if (renderPDF == true)
        {
            dtAnswer = taAnswer.GetData();
            MemoryStream mem = new MemoryStream();
            StreamWriter twr = new StreamWriter(mem);
            HtmlTextWriter myWriter = new HtmlTextWriter(twr);
            base.Render(myWriter);
            myWriter.Flush();
            myWriter.Dispose();
            StreamReader strmRdr = new StreamReader(mem);
            //strmRdr.BaseStream.Position = 3300;
            //string pageContent = strmRdr.ReadToEnd();
            //strmRdr.Dispose();
            //mem.Dispose();
            //writer.Write(pageContent);

            //CreatePDFDocument(pageContent);

            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='1' width='100%' style='font-size:11px; font-weight:bold; border-collapse:collapse; font-family: Arial, 'Lucida Sans Unicode', sans-serif; '>");
            sb.Append("<tr>");
            sb.Append("<td style='background-color:red; text-align:center;' colspan ='3'>maxon motor</td>");
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td width='18%'><p>maxon motor ag</p><p>Sachseln</p></td>");
            sb.Append("<td width ='64%' style='text-align:center'><p>VorstellungsgesprÀch</p></td>");
            sb.Append("<td width='18%'><p>Seite</p></td>");
            sb.Append("</tr>");
            sb.Append("</table>");

            sb.Append("<br /><br />");
            sb.Append("<Table style=\"width:100%;font-weight:bold;border-collapse:collapse; font-family: Arial, 'Lucida Sans Unicode', sans-serif;\">");
            sb.Append("<tr>");
            sb.Append("<td><p>Name / Vorname:</p></td>");
            sb.Append("<td></td>");
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td><p>Geb. Datum:</p></td>");
            sb.Append("<td></td>");
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td><p>Offene Stelle zugewiesen:</p></td>");
            sb.Append("<td></td>");
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td><p>GesprÀchsteilnehmer:</p></td>");
            sb.Append("<td></td>");
            sb.Append("</tr>");
            sb.Append("</table>");
            sb.Append("<br /><br />");

            sb.Append("<div>");
            for (int i = 0; i < pQuestions.Controls.Count; i++)
            {
                string sName = "lbl" + pQuestions.Controls[i].ID.Substring(3, pQuestions.Controls[i].ID.Length - 3);
                if (pQuestions.Controls[i].ID == sName)
                {
                    if (!pQuestions.Controls[i].ID.Contains(","))
                    {
                        string sBlockName = pQuestions.Controls[i].ID.Substring(3, pQuestions.Controls[i].ID.Length - 3);
                        sb.Append("<p><b>" + sBlockName + "</b></p>");
                        sb.Append("<br />");
                        for (int t = 0; t < pQuestions.Controls.Count; t++)
                        {
                            if (pQuestions.Controls[t].ID.Contains(sBlockName))
                            {
                                if (pQuestions.Controls[t].ID.Contains("lbl") && pQuestions.Controls[t].ID != pQuestions.Controls[i].ID)
                                {
                                    sb.Append("<p>" + ((Label)(pQuestions.Controls[t])).Text + "</p>");
                                    sb.Append("<br />");
                                }
                                else if (pQuestions.Controls[t].ID.Contains("txt"))
                                {
                                    if (((TextBox)(pQuestions.Controls[t])).Text != "")
                                    {
                                        sb.Append("<p>" + ((TextBox)(pQuestions.Controls[t])).Text + "</p>");
                                        sb.Append("<br />");
                                    }
                                    else
                                    {
                                        sb.Append("<br /><br /><br /><br />");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            sb.Append("</div>");

            StringReader sr = new StringReader(sb.ToString());
            string rr= sb.ToString();
            CreatePDFDocument(rr);
        }
        else
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            HtmlTextWriter tw = new HtmlTextWriter(new StringWriter(sb));
            base.Render(tw);
            // get the captured markup as a string
            string pageSource = tw.ToString();
            //Get the rendered content
            string sContent = sb.ToString();
            //Now output it to the page, if you want
            writer.Write(sContent);
        }
    }

public void CreatePDFDocument(string strHtml)
        {
            string strHTMLpath = "c:\\MyHTML.html";
            StreamWriter strWriter = new StreamWriter(strHTMLpath, false, System.Text.Encoding.UTF8);
            strWriter.Write(strHtml);
            strWriter.Close();
            string strFileName = "C:\\map1.pdf";
            // step 1: creation of a document-object
            Document document = new Document();
            // step 2:
            // we create a writer that listens to the document
            PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
            StringReader se = new StringReader(strHtml);
            TextReader tr = new StreamReader("C:\\MyHTML.html");

            //add the collection to the document
            document.Open();
            HTMLWorker worker = new HTMLWorker(document);

            worker.StartDocument();

            //// step 5: parse the html into the document
            worker.Parse(tr);

            //// step 6: close the document and the worker
            worker.EndDocument();

            //worker.Parse(tr); // getting error "Illegal characters in path"
            document.Close();
            ShowPdf(strFileName);
        }

public void ShowPdf(string strFileName)
            {
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
                Response.ContentType = "application/pdf";
                Response.WriteFile(strFileName);
                Response.Flush();
                Response.Clear();
            }  

Now, my problem is, I want to create e pdf from one part of the page and not the whole page. How can i realize that?

Thanks a lot! Sarah

1

There are 1 answers

5
Imad On BEST ANSWER

You have to create string congaing all Html that you want to see in pdf but css will not be applied through class. For applying css you have to write inline-css for all DOM elements. You can do so as below

            string = "Pdf Contents in html format";
            StringReader sr = new StringReader(sb.ToString());

            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
           }

for more info visit this

Hope this is helpfull