using System;
using System.Web.Mvc;
using System.Configuration;
using SelectPdf;

namespace SelectPdf.Samples.Controllers
{
    public class ConvertMultipleUrlsToPdfController : Controller
    {
        // GET: ConvertMultipleUrlsToPdf
        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 url1 = collection["TxtUrl1"];
            string url2 = collection["TxtUrl2"];
            string url3 = collection["TxtUrl3"];

            // create a new pdf document 
            PdfDocument doc = new PdfDocument();

            // add a new page to the document
            PdfPage page = doc.AddPage();

            // add the first url
            PdfHtmlElement html1 = new PdfHtmlElement(url1);
            html1.RenderingEngine = renderingEngine;
            html1.CefEnginePath = Server.MapPath(ConfigurationManager.AppSettings["CefEnginePath"]);
            PdfRenderingResult result = page.Add(html1);

            // get the last page of the previous conversion
            PdfPage page2 = doc.Pages[result.PdfPageLastIndex];

            // add the second url
            PdfHtmlElement html2 = new PdfHtmlElement(result.PdfPageLastRectangle.Left,
                result.PdfPageLastRectangle.Bottom, url2);
            html2.RenderingEngine = renderingEngine;
            html2.CefEnginePath = Server.MapPath(ConfigurationManager.AppSettings["CefEnginePath"]);
            result = page2.Add(html2);

            // get the last page of the previous conversion
            PdfPage page3 = doc.Pages[result.PdfPageLastIndex];

            // add the third url
            PdfHtmlElement html3 = new PdfHtmlElement(result.PdfPageLastRectangle.Left,
                result.PdfPageLastRectangle.Bottom, url3);
            html3.RenderingEngine = renderingEngine;
            html3.CefEnginePath = Server.MapPath(ConfigurationManager.AppSettings["CefEnginePath"]);
            result = page3.Add(html3);

            // save pdf document
            byte[] pdf =  doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;

        }
    }
}