SelectPdf for .NET - Convert from Html to Image - VB.NET / ASP.NET MVC Sample

This sample shows how to use SelectPdf html to image converter to convert an url to PNG, JPEG or BMP, also setting a few properties.

Url:

Image Format:


Web Page Width:
px

Web Page Height:
px
(leave empty to auto detect)


Sample Code VB.NET



Imports SelectPdf
Imports System.IO
Imports System.Drawing.Imaging

Namespace Controllers
    Public Class ConvertUrlToImageController
        Inherits Controller

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

        <HttpPost>
        Public Function SubmitAction(collection As FormCollection) As ActionResult
            ' read parameters from the webpage
            Dim url As String = collection("TxtUrl")

            Dim image_format As String = collection("DdlImageFormat")
            Dim imgFormat As ImageFormat = ImageFormat.Png
            If image_format = "jpg" Then
                imgFormat = ImageFormat.Jpeg
            ElseIf image_format = "bmp" Then
                imgFormat = ImageFormat.Bmp
            End If

            Dim webPageWidth As Integer = 1024
            Try
                webPageWidth = System.Convert.ToInt32(collection("TxtWidth"))
            Catch
            End Try

            Dim webPageHeight As Integer = 0
            Try
                webPageHeight = System.Convert.ToInt32(collection("TxtHeight"))
            Catch
            End Try

            ' instantiate a html to image converter object
            Dim imgConverter As New HtmlToImage()

            ' set converter options
            imgConverter.WebPageWidth = webPageWidth
            imgConverter.WebPageHeight = webPageHeight

            ' create a new image converting an url
            Dim image As System.Drawing.Image = imgConverter.ConvertUrl(url)

            ' get image bytes
            Dim img As Byte() = ImageToByteArray(image, imgFormat)

            ' return resulted image
            Dim fileResult As FileResult = New FileContentResult(img,
                        "image/" + imgFormat.ToString().ToLower())
            fileResult.FileDownloadName = Convert.ToString("image.") & image_format
            Return fileResult
        End Function

        Private Function ImageToByteArray(imageIn As System.Drawing.Image,
                                          imageFormat As ImageFormat) As Byte()
            Dim ms As New MemoryStream()
            imageIn.Save(ms, imageFormat)
            Return ms.ToArray()
        End Function
    End Class
End Namespace