Thursday, July 14, 2011

html to pdf converter in c#


using iTextSharp.text.pdf;
using System.Diagnostics;
using System.Data;
using iTextSharp.text;
using System.IO;
using System.Collections;
using iTextSharp.text.html.simpleparser;


protected void Page_Load(object sender, EventArgs e)
    {
                ConvertHtmlToPdf();
    }

private void ConvertHtmlToPdf()
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/pdf";
        // Create PDF document
        Document pdfDocument = new Document(PageSize.A4, 50, 25, 15, 10);

        PdfWriter wri = PdfWriter.GetInstance(pdfDocument, new FileStream("c:\\Test12.pdf", FileMode.Create));

        PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);

        pdfDocument.Open();
        //string htmlText = "<p></p>";

        string htmlText = @"<html><head></head><body>
                        <p>A paragraph</p>  
                        <table border='1'>
                        <tr><td>row1-column1</td><td>row1-column2</td><td>row1-column3</td></tr>
                        <tr><td>row2-column1</td><td>row2-column2</td><td>row2-column3</td></tr>
                        </table>
                        </body></html>";
                       


        //string htmlText = htmlText1.Replace(Environment.NewLine, "<br/>");

        HTMLWorker htmlWorker = new HTMLWorker(pdfDocument);

        htmlWorker.Parse(new StringReader(htmlText));


        pdfDocument.Close();
        HttpContext.Current.Response.End();

    }



No comments:

Post a Comment