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

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

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // the test file
            string filePdf = Server.MapPath("~/files/selectpdf.pdf");

            // settings
            bool caseSensitive = collection["ChkCaseSensitive"] == "on";
            bool wholeWordsOnly = collection["ChkWholeWordsOnly"] == "on";

            // instantiate a pdf to text converter object
            PdfToText pdfToText = new PdfToText();

            // load PDF file
            pdfToText.Load(filePdf);

            // search for text and retrieve all found text positions
            TextPosition[] positions = pdfToText.Search(collection["TxtSearchText"],
                caseSensitive, wholeWordsOnly);

            // open the existing PDF document in editing mode
            PdfDocument doc = new PdfDocument(filePdf);

            // highlight the found text in the existing PDF document
            for (int i = 0; i < positions.Length; i++)
            {
                TextPosition position = (TextPosition)positions[i];

                PdfPage page = doc.Pages[position.PageNumber - 1];

                PdfRectangleElement rect = new PdfRectangleElement(
                    position.X, position.Y, position.Width, position.Height);
                rect.BackColor = new PdfColor(240, 240, 0);
                rect.Transparency = 30;
                page.Add(rect);
            }

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