Imports SelectPdf
Imports System.Drawing

Namespace Controllers
    Public Class WebElementsLocationController
        Inherits Controller

        ' GET: WebElementsLocation
        Function Index() As ActionResult
            Return View()
        End Function

        <HttpPost>
        Public Function SubmitAction(fields As FormCollection) As ActionResult
            Dim renderingEngine As RenderingEngine = CType([Enum].Parse(GetType(RenderingEngine), Request("DdlRenderingEngine"), True), RenderingEngine)
            ' instantiate a html to pdf converter object
            Dim converter As New HtmlToPdf()
            converter.Options.RenderingEngine = renderingEngine
            converter.Options.CefEnginePath = Server.MapPath(ConfigurationManager.AppSettings("CefEnginePath"))
            ' set the css selectors for the web elements
            ' whose positions will be retrieved
            converter.Options.WebElementsMappingOptions.CssSelectors =
                fields("TxtElements").Split(New Char() {","c})

            ' create a new pdf document converting an url
            Dim doc As PdfDocument = converter.ConvertUrl(fields("TxtUrl"))

            ' get all web elements and mark/highlight them with a green rectangle
            For Each element As WebElement In
                converter.Options.WebElementsMappingOptions.Result
                ' each web element has several rendering rectangles 
                ' (if it is displayed in more than 1 page)
                For Each webElementRectangle As WebElementPdfRectangle In
                    element.PdfRectangles
                    ' get the PDF page
                    Dim page As PdfPage = doc.Pages(webElementRectangle.PageIndex)
                    Dim rectangle As RectangleF = webElementRectangle.Rectangle

                    ' highlight the HTML element
                    Dim blueRectangle As New PdfRectangleElement(
                        rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height)
                    blueRectangle.ForeColor = Color.Blue

                    page.Add(blueRectangle)
                Next
            Next

            ' save pdf document
            Dim pdf As Byte() = doc.Save()

            ' close pdf document
            doc.Close()

            ' return resulted pdf document
            Dim fileResult As FileResult = New FileContentResult(pdf, "application/pdf")
            fileResult.FileDownloadName = "Document.pdf"
            Return fileResult
        End Function
    End Class
End Namespace