1

I have a .htm page where the design is in the page with css files. and now i want to create this .htm page to PDF document. So how can i do this using ASP.Net in c#.

1 Answer 1

1

You can use itext sharp.

import these

using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using iTextSharp.text;

Next is add this method

public void ConvertHtmlStringToPDF()
{
    StringBuilder sb = new StringBuilder(); 
    StringWriter tw = new StringWriter(sb); 
    HtmlTextWriter hw = new HtmlTextWriter(tw); 

    ///This is the panel from the webform
    pnlPDF.RenderControl(hw);
    string htmlDisplayText = sb.ToString(); 
    Document document = new Document();
    MemoryStream ms = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, ms);
    StringReader se = new StringReader(htmlDisplayText);
    HTMLWorker obj = new HTMLWorker(document);
    document.Open();
    obj.Parse(se);
    // step 5: we close the document
    document.Close();
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=report.pdf");
    Response.ContentType = "application/pdf";
    Response.Buffer = true;
    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.End();
}

Then in your webform you need to have a panel which contains the html. The purpose of this is for you to be able to call it on the server side.

<asp:Panel ID="pnlPDF" runat="server">
    <div>
      html contents
    </div>
</asp:Panel>
Sign up to request clarification or add additional context in comments.

2 Comments

So how can i do this for the html page using iTextSharp?
iTextSharp needs to run on the code behind. I'm not sure if there is a way to use it only in the html page. But as far as I know it can't be done using just pure html. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.