How to transform HTML into an image on the server?

Asked

Viewed 987 times

5

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

I’ve been trying to use that library, but I’m open to new options.

The code is 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 don’t know if I am using the correct DLL, because I couldn’t find an option for Asp.Net MVC.

HtmlRenderer 1.5.0.6\WinForms\NET40\HtmlRenderer.WinForms.dll
  • 1

    Why would you need an option for ASP.Net MVC?

  • Man, if this Winforms thing worked on my project, it’d be good for me...

  • I don’t understand how this works but it’s strange to be specific, you should generate an image and point, no matter where you should use it. I already question her quality because of this. Are there others that work? Is specific to Mono that works? Or p/PDF? Here seems to be the right one: http://htmlrenderer.codeplex.com/wikipage?title=Image%20generation

  • 1

    Try this if you want to be treated on the client side: http://html2canvas.hertzen.com/examples.html If it’s on the server side, maybe this answer will help you because it helped me in the past: http://stackoverflow.com/questions/25164257/-howto-converthtml-to-pdf-using-itextsharp

2 answers

7

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

Therefore, I will suggest as a response the transformation of HTML to PDF, because then the code can be reusable and without the need to keep changing library or plugins, besides the fact that the PDF is mostly composed of Post Script.

In other words, PDF is basically an image.

There is a library free calling for iTextSharp, I’ve used and solved a similar problem I’ve had.

Example of 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, just do it:

//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

  • +1 to gain permission to comment, remembering to read the topics [Ask] and [Answer]

  • +1 to gain permission to comment also, rsrsrs... Thank you for the reply my friend. Unfortunately I have to do everything on the server side (I will edit the question to add this). I received help here and will post later the solution found.

  • 3

    I believe that it was not long before you could really give an answer, you could bring some of the content of these links to the publication that I believe could already be considered. The way it is will end up being removed or turned into comment.

  • Chance granted :)

  • 1

    Just one question, in this snippet of code you’re generating a pdf or imagem?

  • Taking into account that the PDF is basically an image, the answer would be: both. Anyway I edited the answer to cover both cases.

Show 1 more comment

4


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

I had downloaded the DLL, put it in a folder in the project and added a reference. But it didn’t work very well 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 went 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, from saving on disk to working on MemoryStream...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.