Convert Webpage to Image from Asp.Net

Convert webpage to image from ASP.NET

Ok, this was rather easy when I combined several different solutions:

These solutions gave me a thread-safe way to use the WebBrowser from ASP.NET:

http://www.beansoftware.com/ASP.NET-Tutorials/Get-Web-Site-Thumbnail-Image.aspx

http://www.eggheadcafe.com/tutorials/aspnet/b7cce396-e2b3-42d7-9571-cdc4eb38f3c1/build-a-selfcaching-asp.aspx

This solution gave me a way to convert BMP to JPG:

Bmp to jpg/png in C#

I simply adapted the code and put the following into a .cs:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;

public class WebsiteToImage
{
private Bitmap m_Bitmap;
private string m_Url;
private string m_FileName = string.Empty;

public WebsiteToImage(string url)
{
// Without file
m_Url = url;
}

public WebsiteToImage(string url, string fileName)
{
// With file
m_Url = url;
m_FileName = fileName;
}

public Bitmap Generate()
{
// Thread
var m_thread = new Thread(_Generate);
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}

private void _Generate()
{
var browser = new WebBrowser { ScrollBarsEnabled = false };
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;

while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}

browser.Dispose();
}

private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Capture
var browser = (WebBrowser)sender;
browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.BringToFront();
browser.DrawToBitmap(m_Bitmap, browser.Bounds);

// Save as file?
if (m_FileName.Length > 0)
{
// Save
m_Bitmap.SaveJPG100(m_FileName);
}
}
}

public static class BitmapExtensions
{
public static void SaveJPG100(this Bitmap bmp, string filename)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}

public static void SaveJPG100(this Bitmap bmp, Stream stream)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}

public static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();

foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}

// Return
return null;
}
}

And can call it as follows:

WebsiteToImage websiteToImage = new WebsiteToImage( "http://www.cnn.com", @"C:\Some Folder\Test.jpg");
websiteToImage.Generate();

It works with both a file and a stream. Make sure you add a reference to System.Windows.Forms to your ASP.NET project. I hope this helps.

UPDATE: I've updated the code to include the ability to capture the full page and not require any special settings to capture only a part of it.

how to convert page in to image in asp.net

You can make use of canvas in this. Add this script to you .aspx page

<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("selector")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>

And cahnge your function to something like this

            string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
string folderPath = Server.MapPath("~/Images/"); //Create a Folder in your Root directory on your solution.
string fileName = "IMageName" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".jpg";
string imagePath = folderPath + fileName;
img.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png);

Add a button to your page on click of which you have to call this function and call the function ConvertToImage() on client click. And also add one hidden field like this:-

<asp:HiddenField ID="hfImageData" runat="server" />
<asp:Button ID="btnExport" Text="Export to Image" runat="server" UseSubmitBehavior="false"
OnClick="saveURLToImage" OnClientClick="return ConvertToImage(this)" />

Now when you click on the button it will save a image of the webpage on the server at the path specified. And you can change the jquery selector of which you want to capture image of. this solution uses jquery and canvas to make sure to import the libraries.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>

ASP.Net Panel to Image

Here's a great tutorial from Mudassar Ahmed Khan's website using HTML5 Canvas, div and table elements combined with Html2Canvas library.

Check it out:

https://www.aspsnippets.com/Articles/Convert-Export-HTML-DIV-or-Table-to-Image-using-HTML-Canvas-in-ASPNet-using-C-and-VBNet.aspx

UPDATE

I combined the tutorial with your requirement. I had to also update the references to the javascript files (cdn's):

PanelToImage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PanelToImage.aspx.cs" Inherits="PanelToImage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-alpha.8/html2canvas.min.js"></script>
</head>
<body>
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>

<form id="form1" runat="server">
<div id="dvTable" style="width: 340px; background-color: White; padding: 5px">
<asp:Panel ID="wordcloud2" runat="server">
<span data-weight="43">Nike</span>
<span data-weight="41">Reebok</span>
<span data-weight="60">Adidas</span>
<span data-weight="39">Roush</span>
<span data-weight="17">Bata</span>
<span data-weight="35">Lunar's</span>
<span data-weight="33">VKC</span>
<span data-weight="31">Lee cooper</span>
</asp:Panel>
</div>
<br />
<asp:HiddenField ID="hfImageData" runat="server" />
<asp:Button ID="btnExport" Text="Export to Image" runat="server" UseSubmitBehavior="false" OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
</form>
</body>
</html>

PanelToImage.cs (code behind)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PanelToImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);

Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=HTML.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
}

Results:

WebApp

Image result



Related Topics



Leave a reply



Submit