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

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

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // create a new pdf document
            PdfDocument doc = new PdfDocument();

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

            // get image path 
            // the image will be used to display the digital signature over it
            string imgFile = Server.MapPath("~/files/logo.png");

            // get certificate path
            string certFile = Server.MapPath("~/files/selectpdf.pfx");

            // define a rendering result object
            PdfRenderingResult result;

            // create image element from file path 
            PdfImageElement img = new PdfImageElement(0, 0, imgFile);
            result = page.Add(img);

            // get the #PKCS12 certificate from file
            PdfDigitalCertificatesCollection certificates =
                PdfDigitalCertificatesStore.GetCertificates(certFile, "selectpdf");
            PdfDigitalCertificate certificate = certificates[0];

            // create the digital signature object
            PdfDigitalSignatureElement signature =
                new PdfDigitalSignatureElement(result.PdfPageLastRectangle, certificate);
            signature.Reason = "SelectPdf";
            signature.ContactInfo = "SelectPdf";
            signature.Location = "SelectPdf";
            page.Add(signature);

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