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

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

Url:

Image Format:


Web Page Width:
px

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


Sample Code C#



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

namespace SelectPdf.Samples.Controllers
{
    public class ConvertUrlToImageController : Controller
    {
        // GET: ConvertUrlToImage
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // read parameters from the webpage
            string url = collection["TxtUrl"];

            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 = System.Convert.ToInt32(collection["TxtWidth"]);
            }
            catch { }

            int webPageHeight = 0;
            try
            {
                webPageHeight = System.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.ConvertUrl(url);

            // 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();
        }
    }
}