Add the Itextsharp and Itextsharp.xmlworker Nuget packages to your project
Add the following using in your code:
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;
In my example below, I will take an html that is in String and display on the screen.
#region Transformar o HTML em PDF
using (var documentPDF = new Document(PageSize.A4, 40, 40, 40, 40))
{
HttpContext.Current.Response.ContentType = "application/pdf";
//TextReader xhmtlStr = new StringReader(readStream.ReadToEnd());//Leio o seu HTML da Stream
TextReader xhmtlStr = new StringReader(@"<html><h1>Teste!</h1><p style=""backgroung:red;color:white;"">Parágrafo de Teste</p></html>");//Leio o HTML da Stream
var ms = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(documentPDF, ms);
documentPDF.Open();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
IPipeline pdfWriterPipeline = new PdfWriterPipeline(documentPDF, pdfWriter);
//Exporta para o PDF.
IPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfWriterPipeline);
var xmlWorker = new XMLWorker(htmlPipeline, true); //True para parse do HTML
var xmlParser = new XMLParser(true, xmlWorker);
xmlParser.Parse(xhmtlStr);
xmlParser.Flush();
documentPDF.Close();
documentPDF.Dispose();
// O MemoryStream contém seu PDF com o HTML convertido em PDF, só pegar e enviar por email.
//Caso queira exibir na tela, use o código abaixo
HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //Aqui se quiser exibir o PDF na página.
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
#endregion
Taking the value of Memorystream, you can now click on your email.
A source that can help you is also in http://jeffersonsn.blogspot.com.br/2013/08/html-pdf-itextsharp-xmlworker-c.html
The
Stream
is what, exactly? An HTML page?– Leonel Sanches da Silva
Yes, it’s an HTML I just recovered from the url passed.
– Henrique Abreu