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

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

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            RenderingEngine renderingEngine =
                (RenderingEngine)Enum.Parse(typeof(RenderingEngine), Request["DdlRenderingEngine"], true);

            // 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();
            imgConverter.RenderingEngine = renderingEngine;
            imgConverter.CefEnginePath = Server.MapPath(ConfigurationManager.AppSettings["CefEnginePath"]);

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