Here I have created sample that will help you out.
HTML
<div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
<script src="//cdn.jsdelivr.net/chart.js/0.2/Chart.js" type="text/javascript"></script>
<script src="Js/html2canvas.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
LoadChart();
$("[id*=ddlCountries]").bind("change", function () {
LoadChart();
});
$("[id*=rblChartType] input").bind("click", function () {
LoadChart();
});
});
function LoadChart() {
var chartType = parseInt($("[id*=rblChartType] input:checked").val());
$.ajax({
type: "POST",
url: "CS.aspx/GetChart",
data: "{country: '" + $("[id*=ddlCountries]").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dvChart").html("");
$("#dvLegend").html("");
var data = eval(r.d);
var el = document.createElement('canvas');
$("#dvChart")[0].appendChild(el);
//Fix for IE 8
if ($.browser.msie && $.browser.version == "8.0") {
G_vmlCanvasManager.initElement(el);
}
var ctx = el.getContext('2d');
var userStrengthsChart;
switch (chartType) {
case 1:
userStrengthsChart = new Chart(ctx).Pie(data);
break;
case 2:
userStrengthsChart = new Chart(ctx).Doughnut(data);
break;
}
for (var i = 0; i < data.length; i++) {
var div = $("<div />");
div.css("margin-bottom", "10px");
div.html("<span style = 'display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
$("#dvLegend").append(div);
}
},
failure: function (response) {
alert('There was an error.');
}
});
}
</script>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Country:
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="USA" Value="USA" />
<asp:ListItem Text="Germany" Value="Germany" />
<asp:ListItem Text="France" Value="France" />
<asp:ListItem Text="Brazil" Value="Brazil" />
</asp:DropDownList>
<asp:RadioButtonList ID="rblChartType" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Text="Pie" Value="1" Selected="True" />
<asp:ListItem Text="Doughnut" Value="2" />
</asp:RadioButtonList>
</td>
</tr>
</table>
<div id="dvTable" style="background-color: White; padding: 5px; width: 50%; height: 50%">
<asp:Panel ID="pnlPerson" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div id="dvChart">
</div>
</td>
<td>
<div id="dvLegend">
</div>
</td>
</tr>
</table>
</asp:Panel>
</div>
<br />
<asp:HiddenField ID="hfImageData" runat="server" />
<img id="imgCapture" runat="server" alt="" style="display: none; border: 1px solid #ccc" />
<asp:Button ID="btnExport" Text="Export to PDF" runat="server" UseSubmitBehavior="false"
OnClick="ExportToPDF" OnClientClick="return ExportToPDF(this)" />
<asp:Button ID="btnExportToExcel" Text="Export to Excel" runat="server" UseSubmitBehavior="false"
OnClick="ExportToExcel" OnClientClick="return ExportToExcel(this)" />
<asp:Button ID="btnExportToPPT" Text="Export to PPT" runat="server" UseSubmitBehavior="false"
OnClick="ExportToPPT" OnClientClick="return ExportToPPT(this)" />
<script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>
<script type="text/javascript">
function ExportToPDF(btnExport) {
ExportToImage(btnExport);
return false;
}
function ExportToPPT(btnExport) {
ExportToImage(btnExport);
return false;
}
function ExportToExcel(btnExport) {
ExportToImage(btnExport);
return false;
}
function ExportToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
}
</script>
</div>
C#
Namespaces
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
Code
[WebMethod]
public static string GetChart(string country)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country);
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
while (sdr.Read())
{
sb.Append("{");
System.Threading.Thread.Sleep(50);
string color = String.Format("#{0:X6}", new Random().Next(0x1000000));
sb.Append(string.Format("text :'{0}', value:{1}, color: '{2}'", sdr[0], sdr[1], color));
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
sb.Append("]");
con.Close();
return sb.ToString();
}
}
}
}
protected void ExportToPDF(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] imagebytes = Convert.FromBase64String(base64);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagebytes);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
document.Add(image);
document.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
}
protected void ExportToExcel(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] imagebytes = Convert.FromBase64String(base64);
MemoryStream stream = new MemoryStream(imagebytes);
System.Drawing.Image image = new Bitmap(stream);
image.Save(Server.MapPath("~/Temp/file.png"));
System.Web.UI.WebControls.Image img1 = new System.Web.UI.WebControls.Image();
img1.ImageUrl = Server.MapPath("~/Temp/file.png");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
TableRow row = new TableRow();
row.Cells.Add(new TableCell());
row.Cells[0].Controls.Add(img1);
table.Rows.Add(row);
table.RenderControl(hw);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Images.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
protected void ExportToPPT(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] imagebytes = Convert.FromBase64String(base64);
MemoryStream stream = new MemoryStream(imagebytes);
System.Drawing.Image image = new Bitmap(stream);
image.Save(Server.MapPath("~/Temp/file.png"));
String strTemplate = @"D:\1.pot";
PowerPoint.Application objApp;
PowerPoint.Presentations objPresSet;
PowerPoint._Presentation objPres;
PowerPoint.Slides objSlides;
PowerPoint._Slide objSlide;
PowerPoint.TextRange objTextRng;
PowerPoint.Shapes objShapes;
PowerPoint.Shape objShape;
PowerPoint.SlideShowWindows objSSWs;
PowerPoint.SlideShowTransition objSST;
PowerPoint.SlideRange objSldRng;
//Create a new presentation based on a template.
objApp = new PowerPoint.Application();
objApp.Visible = MsoTriState.msoTrue;
objPresSet = objApp.Presentations;
objPres = objPresSet.Open(strTemplate,
MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
objSlides = objPres.Slides;
int slideCount = 1;
//Adding Image to Slide
objSlide = objSlides.Add(slideCount, PowerPoint.PpSlideLayout.ppLayoutBlank);
objSlide.Shapes.AddPicture(Server.MapPath("~/Temp/file.png"), MsoTriState.msoFalse, MsoTriState.msoTrue,
150, 150, 500, 150);
//Modify the slide show transition settings for all 3 slides in
int[] SlideIdx = new int[slideCount];
for (int i = 0; i < slideCount; i++) SlideIdx[i] = i + 1;
objSldRng = objSlides.Range(SlideIdx);
objSST = objSldRng.SlideShowTransition;
objSST.AdvanceOnTime = MsoTriState.msoTrue;
objSST.AdvanceTime = 3;
objSST.EntryEffect = PowerPoint.PpEntryEffect.ppEffectBoxOut;
//Wait for the slide show to end.
objSSWs = objApp.SlideShowWindows;
objPres.SaveAs(Server.MapPath("~/Temp/" + DateTime.Today.ToShortDateString().Replace("/", "_") + ".ppt"));
objPres.Close();
objApp.Quit();
DownloadFile(Server.MapPath("~/Temp/" + DateTime.Today.ToShortDateString().Replace("/", "_") + ".ppt"));
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void DownloadFile(string filePath)
{
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=abc.ppt");
byte[] data = req.DownloadData(filePath);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
response.BinaryWrite(data);
response.End();
}
VB
Namespces
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web
Imports System.Web.Services
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports Microsoft.Office.Core
Imports PowerPoint = Microsoft.Office.Interop.PowerPoint
Code
<WebMethod> _
Public Shared Function GetChart(country As String) As String
Dim constr As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Using con As New SqlConnection(constr)
Dim query As String = String.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country)
Using cmd As New SqlCommand()
cmd.CommandText = query
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
Dim sb As New StringBuilder()
sb.Append("[")
While sdr.Read()
sb.Append("{")
System.Threading.Thread.Sleep(50)
Dim color As String = [String].Format("#{0:X6}", New Random().[Next](&H1000000))
sb.Append(String.Format("text :'{0}', value:{1}, color: '{2}'", sdr(0), sdr(1), color))
sb.Append("},")
End While
sb = sb.Remove(sb.Length - 1, 1)
sb.Append("]")
con.Close()
Return sb.ToString()
End Using
End Using
End Using
End Function
Protected Sub ExportToPDF(sender As Object, e As EventArgs)
Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(","C)(1)
Dim imagebytes As Byte() = Convert.FromBase64String(base64)
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagebytes)
Using memoryStream As New System.IO.MemoryStream()
Dim document As New Document(PageSize.A4, 88F, 88F, 10F, 10F)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, memoryStream)
document.Open()
document.Add(image)
document.Close()
Dim bytes As Byte() = memoryStream.ToArray()
memoryStream.Close()
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf")
Response.ContentType = "application/pdf"
Response.Buffer = True
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bytes)
Response.[End]()
End Using
End Sub
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(","C)(1)
Dim imagebytes As Byte() = Convert.FromBase64String(base64)
Dim stream As New MemoryStream(imagebytes)
Dim image As System.Drawing.Image = New Bitmap(stream)
image.Save(Server.MapPath("~/Temp/file.png"))
Dim img1 As New System.Web.UI.WebControls.Image()
img1.ImageUrl = Server.MapPath("~/Temp/file.png")
Using sw As New StringWriter()
Using hw As New HtmlTextWriter(sw)
Dim table As New System.Web.UI.WebControls.Table()
Dim row As New TableRow()
row.Cells.Add(New TableCell())
row.Cells(0).Controls.Add(img1)
table.Rows.Add(row)
table.RenderControl(hw)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=Images.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Response.Write(sw.ToString())
Response.Flush()
Response.[End]()
End Using
End Using
End Sub
Protected Sub ExportToPPT(sender As Object, e As EventArgs)
Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(","C)(1)
Dim imagebytes As Byte() = Convert.FromBase64String(base64)
Dim stream As New MemoryStream(imagebytes)
Dim image As System.Drawing.Image = New Bitmap(stream)
image.Save(Server.MapPath("~/Temp/file.png"))
Dim strTemplate As [String] = "D:\1.pot"
Dim objApp As PowerPoint.Application
Dim objPresSet As PowerPoint.Presentations
Dim objPres As PowerPoint._Presentation
Dim objSlides As PowerPoint.Slides
Dim objSlide As PowerPoint._Slide
Dim objTextRng As PowerPoint.TextRange
Dim objShapes As PowerPoint.Shapes
Dim objShape As PowerPoint.Shape
Dim objSSWs As PowerPoint.SlideShowWindows
Dim objSST As PowerPoint.SlideShowTransition
Dim objSldRng As PowerPoint.SlideRange
'Create a new presentation based on a template.
objApp = New PowerPoint.Application()
objApp.Visible = MsoTriState.msoTrue
objPresSet = objApp.Presentations
objPres = objPresSet.Open(strTemplate, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue)
objSlides = objPres.Slides
Dim slideCount As Integer = 1
'Adding Image to Slide
objSlide = objSlides.Add(slideCount, PowerPoint.PpSlideLayout.ppLayoutBlank)
objSlide.Shapes.AddPicture(Server.MapPath("~/Temp/file.png"), MsoTriState.msoFalse, MsoTriState.msoTrue, 150, 150, 500, _
150)
'Modify the slide show transition settings for all 3 slides in
Dim SlideIdx As Integer() = New Integer(slideCount - 1) {}
For i As Integer = 0 To slideCount - 1
SlideIdx(i) = i + 1
Next
objSldRng = objSlides.Range(SlideIdx)
objSST = objSldRng.SlideShowTransition
objSST.AdvanceOnTime = MsoTriState.msoTrue
objSST.AdvanceTime = 3
objSST.EntryEffect = PowerPoint.PpEntryEffect.ppEffectBoxOut
'Wait for the slide show to end.
objSSWs = objApp.SlideShowWindows
objPres.SaveAs(Server.MapPath("~/Temp/" + DateTime.Today.ToShortDateString().Replace("/", "_") + ".ppt"))
objPres.Close()
objApp.Quit()
DownloadFile(Server.MapPath("~/Temp/" + DateTime.Today.ToShortDateString().Replace("/", "_") + ".ppt"))
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
End Sub
Private Sub DownloadFile(filePath As String)
Dim req As New WebClient()
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.ClearContent()
response.ClearHeaders()
response.Buffer = True
response.AddHeader("Content-Disposition", "attachment;filename=abc.ppt")
Dim data As Byte() = req.DownloadData(filePath)
If File.Exists(filePath) Then
File.Delete(filePath)
End If
response.BinaryWrite(data)
response.[End]()
End Sub
Screenshot