Code:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.util;
using System.Net;
using System.Xml;
protected void btn_submit_Click(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(Server.MapPath("~") + "/App_Data/test.html"))
{
String line = reader.ReadToEnd();
Text2PDF(line);
}
}
protected void Text2PDF(string PDFText)
{
StringReader reader = new StringReader(PDFText);
Document document = new Document(PageSize.A4);
HTMLWorker parser = new HTMLWorker(document);
string PDF_FileName = Server.MapPath("~") + "/App_Data/PDF_File.pdf";
PdfWriter.GetInstance(document, new FileStream(PDF_FileName, FileMode.Create));
document.Open();
try
{
parser.Parse(reader);
}
catch (Exception ex)
{
Paragraph paragraph = new Paragraph("Error!" + ex.Message);
Chunk text = paragraph.Chunks[0] as Chunk;
if (text != null)
{
text.Font.Color = BaseColor.RED;
}
document.Add(paragraph);
}
finally
{
document.Close();
DownLoadPdf(PDF_FileName);
}
}
private void DownLoadPdf(string PDF_FileName)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(PDF_FileName);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}