Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HTML to Image using c#. Html has tags as well base64 string issue

Tags:

html

c#

.net

I am trying to convert HTML to image in c#, but I am not able to.

My html has tags as well base64 string data for images.

If I convert, everything is coming empty.

Please do help me for this.

public void ConvertHtmlToImage()
{
       Bitmap m_Bitmap = new Bitmap(400, 600);
       PointF point = new PointF(0, 0);
       SizeF maxSize = new System.Drawing.SizeF(500, 500);
       HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                               "<html><body><p>This is a shitty html code</p>"
                                               + "<p>This is another html line</p>        <span style='left:356px;top:34px;position:absolute;'><img
                src='data:image/gif;base64,R0lGODlhFABgAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAUAGAAAAKKjI+py+0Po5y02ouz3rz7nwAiMJHXaEZphYJMK60UrGK0i9yPXI6l7cNxeAeUbsFLBXMKkzLUNDyhxaJRdpxdQ1dnFfmdRqVWIvkcE+XUP7S0i8aO4e46mLpj2rnszbK29/IVE2Dm8gchljio0iekYSiUJWgR2WD0WDZ5p2WJ55kZKjpKWmp66lIAADs%3D'/></span>
</body>",point, maxSize);
m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}

Thanks in advance.

like image 760
Sharad Avatar asked Oct 16 '25 14:10

Sharad


1 Answers

Download this package: https://www.nuget.org/packages/CoreHtmlToImage/

Then write this code:

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        var converter = new HtmlConverter();
        var html = "<html>" +
            "<body>" +
            "<p>This is a shitty html code</p><p>This is another html line</p>" +
            "<span style='left:356px;top:34px;position:absolute;'>" +
            "<img src='data:image/gif;base64,R0lGODlhFABgAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAUAGAAAAKKjI+py+0Po5y02ouz3rz7nwAiMJHXaEZphYJMK60UrGK0i9yPXI6l7cNxeAeUbsFLBXMKkzLUNDyhxaJRdpxdQ1dnFfmdRqVWIvkcE+XUP7S0i8aO4e46mLpj2rnszbK29/IVE2Dm8gchljio0iekYSiUJWgR2WD0WDZ5p2WJ55kZKjpKWmp66lIAADs%3D'/>" +
            "</span>" +
            "</body>" +
            "</html>";
        var bytes = converter.FromHtmlString(html);
        File.WriteAllBytes("image.jpg", bytes);
    }

Run and you will get your page:

enter image description here

like image 165
Andrey Avatar answered Oct 18 '25 05:10

Andrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!