using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SelectPdf.Samples
{
    public partial class convert_html_code_to_image : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TxtHtmlCode.Text = @"<html>
 <body>
  <br/>
  Hello World from selectpdf.com.
  <br/>
  <br/>
  <br/>
  <br/>
  Hello World from selectpdf.com.
  <br/>
  <br/>
 </body>
</html>
";
            }
        }

        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            RenderingEngine renderingEngine =
                (RenderingEngine)Enum.Parse(typeof(RenderingEngine), DdlRenderingEngine.SelectedValue, true);

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

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