SelectPdf for .NET - Convert from Html Code to Image - C# / ASP.NET MVC Sample

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

Html Code:


Base Url:

Image Format:


Web Page Width:
px

Web Page Height:
px
(leave empty to auto detect)


Sample Code C#



using System;
using System.IO;
using System.Drawing.Imaging;
using System.Web.Mvc;

namespace SelectPdf.Samples.Controllers
{
    public class ConvertHtmlCodeToImageController : Controller
    {
        // GET: ConvertHtmlCodeToImage
        public ActionResult Index()
        {
            string stringdata = "";

            stringdata = @"<html>
    <body>
        Hello World from selectpdf.com.
    </body>
</html>
";
            ViewData.Add("TxtHtmlCode", stringdata);
            return View();
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // read parameters from the webpage
            string htmlString = collection["TxtHtmlCode"];
            string baseUrl = collection["TxtBaseUrl"];

            string image_format = collection["DdlImageFormat"];
            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(collection["TxtWidth"]);
            }
            catch { }

            int webPageHeight = 0;
            try
            {
                webPageHeight = Convert.ToInt32(collection["TxtHeight"]);
            }
            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);

            // get image bytes
            byte[] img = ImageToByteArray(image, imageFormat);

            // return resulted image
            FileResult fileResult = new FileContentResult(img, "image/" +
                imageFormat.ToString().ToLower());
            fileResult.FileDownloadName = "image." + image_format;
            return fileResult;
        }

        private byte[] ImageToByteArray(
            System.Drawing.Image imageIn,
            ImageFormat imageFormat)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, imageFormat);
            return ms.ToArray();
        }
    }
}