Convert Html Code to Image | |
Using SelectPdf Html to Image Converter for .NET any html code can be converted to a PNG image. SelectPdf Library supports the latest HTML5 with CSS3 style sheets.
To convert a raw html string to pdf, HtmlToImage class exposes the ConvertHtmlString(String) and ConvertHtmlString(String, String) methods.
The first method, that has only the htmlString parameter, can be used to convert html strings that don't have external references to javascript, css files or images. In case the html string contains references to external resources specified using relative paths, the second method needs to be used. ConvertHtmlString(String, String) contains an additional parameter: baseUrl. The baseUrl parameter allows the converter to resolve relative urls. Basically, baseUrl + relative image/css url = full absolute url.
This sample shows how to use SelectPdf html to image converter to convert a raw html code to a PNG image, also setting a few properties.
// read parameters from the webpage string htmlString = "<html><body><h1>Hello world</h1></body></html>"; string baseUrl = "https://www.example.com/"; int webPageWidth = 1024; try { webPageWidth = Convert.ToInt32(widthValue); } catch { } int webPageHeight = 0; try { webPageHeight = Convert.ToInt32(heightValue); } catch { } // instantiate a html to image converter object HtmlToImage imgConverter = new HtmlToImage(); // set converter options imgConverter.WebPageWidth = webPageWidth; imgConverter.WebPageHeight = webPageHeight; // convert the html string to a PNG image (returned as a byte array) byte[] imageBytes = imgConverter.ConvertHtmlString(htmlString, baseUrl); // save the image to a file System.IO.File.WriteAllBytes("image.png", imageBytes);