Click or drag to resize
Pdf Library for .NET

Convert Html Code to Image

Using SelectPdf Html to Image Converter for .NET any html code can be converted to PNG, JPEG or BMP. 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.

Sample Code

This sample shows how to use SelectPdf html to image converter to convert a raw html code to PNG, JPEG or BMP, also setting a few properties.

// read parameters from the webpage
string htmlString = TxtHtmlCode.Text;
string baseUrl = TxtBaseUrl.Text;

string image_format = DdlImageFormat.SelectedValue;
ImageFormat imageFormat = ImageFormat.Png;
if (image_format == "jpg")
{
    imageFormat = ImageFormat.Jpeg;
}
else if (image_format == "bmp")
{
    imageFormat = ImageFormat.Bmp;
}

int webPageWidth = 1024;
try
{
    webPageWidth = Convert.ToInt32(TxtWidth.Text);
}
catch { }

int webPageHeight = 0;
try
{
    webPageHeight = Convert.ToInt32(TxtHeight.Text);
}
catch { }

// instantiate a html to image converter object
HtmlToImage imgConverter = new HtmlToImage();

// set converter options
imgConverter.WebPageWidth = webPageWidth;
imgConverter.WebPageHeight = webPageHeight;

// create a new image converting an url
System.Drawing.Image image = 
    imgConverter.ConvertHtmlString(htmlString, baseUrl);

// send image to browser
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "image/" +
    imageFormat.ToString().ToLower());
Response.AppendHeader("content-disposition",
    "attachment;filename=\"image." + image_format + "\"");
image.Save(Response.OutputStream, imageFormat);
Response.End();
See Also