How to turn HTML into an image on the server?

5

I have a Asp.Net MVC project with .Net Framework 4 in Visual Studio, where I need to transform a string with HTML code into a server-side image .

I've tried using this library , but I'm open to new options.

The code looks like this:

Image m_Bitmap = new Bitmap(400, 600);
PointF point = new PointF(0, 0);
SizeF maxSize = new System.Drawing.SizeF(500, 500);
TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(m_Bitmap, "<html><body><p>This is a shitty html code</p><p>This is another html line</p></body>");

m_Bitmap.Save(@"C:\Test.bmp");

I downloaded the library, but I'm not sure if I'm using the correct DLL as I did not find an option for Asp.Net MVC.

HtmlRenderer 1.5.0.6\WinForms\NET40\HtmlRenderer.WinForms.dll
    
asked by anonymous 26.11.2015 / 18:59

2 answers

4

I got a lot of help with this link , and I realized that I was using the wrong library.

I had downloaded the DLL, placed in a folder in the project and added a reference. But it did not work very well like that, so I installed the library via Nuget , and voilà!

Soon after, I installed that other library in the same way, following the tutorial.

The code looks like this:

var result = PreMailer.Net.PreMailer.MoveCssInline(html: html, 
                                                    removeStyleElements: false, 
                                                    ignoreElements: null, 
                                                    stripIdAndClassAttributes: false);

var image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(result.Html, new Size(390, 290));

So I can do anything with image , save from disk to work on MemoryStream ...

    
30.11.2015 / 19:05
7

Within the context of projects is normal the need to generate reports , basically as the level of detail increases, complexity of the report also increases. Hence the need to incorporate images into texts, or tables into images or even all together.

So I'm going to suggest a response to the transformation from HTML to PDF, so that the code can be reusable and without the need to have to change library or plugins, besides the fact that the PDF is for the most part composed of Post Script .

In other words, PDF is basically an Image.

There is a free library called iTextSharp , I already used and solved a similar problem I had.

Example how to use :

//Cria um array de bytes para salvar os dados do PDF
Byte[] bytes;
//Para evitar preocupação com alocação de memória e etc...
using (var ms = new MemoryStream()) {
    //Cria um documento abstrato
    using (var doc = new Document()) {
        //Cria um escritor para bindar os dados no documento abstrato
        using (var writer = PdfWriter.GetInstance(doc, ms)) {
            //Abre o documento abstrato
            doc.Open();
            //Insere o HTML e o CSS como string ou como variável
            var example_html = @"<body><p>This is a shitty html code</p><p>This is another html line</p></body>";
            var example_css = @"CSS AQUI";
            //Converte as strings do HTML e CSS
            using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) {
                using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) {
                    //Faz o Parse do HTML
                  iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                }
            }
          //Fecha o documento
            doc.Close();
        }
    }
    //Fecha MemoryStream e joga dentro do array de bytes
    bytes = ms.ToArray();
}
//Transfere o array para o disco
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "download.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);

Now if what you really want is an image, simply do:

//Realiza uma iteração para cada página
for(int i=0;i< pdfdocument.Pages.Count;i++)  
{
  //Salva a página como imagem
  System.Drawing.Image image= pdfdocument.SaveAsImage(i, 96, 96);  
  image.Save(string.Format("ImagePage{0}.png", i), System.Drawing.Imaging.ImageFormat.Png);  
}

Reference

    
30.11.2015 / 18:32