Search code examples
c#imagememorystreamwkhtmltoimagesystem.drawing.imaging

Html To Image Using NReco.ImageGenerator : C#


Introduction

I am working with the functionality where we can convert "html" to image.For image creation, i use "Image" function(of System.Drawing).

Functionality working fine(including html styles etc) except for one thing i will describe later in problem.

Problem

Problem appears When using Non-english language in html, although for english it works fine.Obviously Unicode problem, i am doing something wrong due to my limited understanding.

string str ="<p> Have Good Day !!</p>"; //output : Have Good Day !!
string str2 = "<p>قطعا</p>"; //output : non-sense symbols like Omega

C# Code

var html = String.Format("<h1>فقط</h1><p>قطعا</p>");

var htmlToImageConv = new NReco.ImageGenerator.HtmlToImageConverter();

var jpegBytes = htmlToImageConv.GenerateImage(html,ImageFormat.Png.ToString());

MemoryStream memstr = new MemoryStream(jpegBytes);

System.Drawing.Image img = System.Drawing.Image.FromStream(memstr,true,true);

img.Save(Server.MapPath("~/App_Images/My_Converted11.png"));

I been trying to figure out how to hold that problem but couldn't yet.If someone can help regarding this problem, please do help.Any kind of help reference will be helpful and will be appreciated.Thanks for your time.


Solution

  • You must set the <head> <meta> tag inside your HTML and define the charset like this:

    string html =  @"<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>Hello world: 안녕하세요...</body></html>";
    

    I hope this will help you.