Imports SelectPdf

Namespace Controllers
    Public Class ConvertFromJsController
        Inherits Controller

        ' GET: ConvertFromJs
        Public Function Index() As ActionResult
            Dim url As String = System.Web.VirtualPathUtility.
                ToAbsolute("~/files/js-conversion.html")
            ViewData.Add("ViewTxtUrl", (New Uri(Request.Url, url)).AbsoluteUri)

            ViewData.Add("ViewTxtHref", url)
            ViewData.Add("ViewDdlStartupModeSel", "Manual")

            Dim DdlStartupMode As New List(Of SelectListItem)()
            DdlStartupMode.Add(New SelectListItem() With {
                 .Text = "Automatic",
                 .Value = "Automatic",
                 .Selected = ViewData("ViewDdlStartupModeSel") IsNot Nothing _
                    AndAlso ViewData("ViewDdlStartupModeSel").ToString() = "Automatic"
            })
            DdlStartupMode.Add(New SelectListItem() With {
                 .Text = "Manual",
                 .Value = "Manual",
                 .Selected = ViewData("ViewDdlStartupModeSel") IsNot Nothing _
                    AndAlso ViewData("ViewDdlStartupModeSel").ToString() = "Manual"
            })
            ViewData.Add("ViewDdlStartupMode", DdlStartupMode)
            Return View()
        End Function

        <HttpPost>
        Public Function SubmitAction(collection As FormCollection) As ActionResult
            ' instantiate a html to pdf converter object
            Dim converter As New HtmlToPdf()

            ' set startup mode
            converter.Options.StartupMode = DirectCast([Enum].Parse(
                GetType(HtmlToPdfStartupMode), collection("DdlStartupMode"), True),
                HtmlToPdfStartupMode)

            ' set timeout
            Dim timeout As Integer = 10
            Try
                timeout = Convert.ToInt32(collection("TxtTimeout"))
            Catch
            End Try
            converter.Options.MaxPageLoadTime = timeout

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

            ' 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
