SharePoint Pals
 | Sign In
How to Insert Google Charts Image into PDF using iTextSharp in SharePoint
by Ahamed Fazil Buhari 28 Aug 2016
SharePoint Developer
Today  :   1     Total  :    2589

Hello everyone, in this article we’re going to look step by step approach to insert Google Chart into PDF. Here, the idea is to get the ImageURI from the printed google chart using JavaScript and append that Image into our newly created PDF file.

You can refer these articles Generate PDF report using iTextSharp (.NET PDF library) in SharePoint Environment and Google Chart in SharePoint – to get an idea about Google Chart and iTextSharp dll to Generate PDF in SharePoint.

Google Chart provide the function getImageURI() and by using JavaScript we’ll get the PNG Image of a chart. Pass this image/png data into our server side code and convert this into Base64 format and finally we can easily convert this Base64 data into .NET Image object which can be later inserted into the PDF file using iTextSharp.

Note: getImageURI() function currently works for core charts and geocharts. You can refer Google Chart - official website to know more about Printing PNG Charts

Let me explain about the process in step by step procedure,

Step 1: Convert Google Chart into Image URI using chart.getImageURI();

Here, I’ve created the Visual Web Part and inside the ascx controller Pie Chart to show the data. I consider that you the knowledge to create the Google, so I show only the code that needs to be added for PNG Chart.

 <script type="text/javascript" language="javascript">
     // script to create Google Chart, leaving it to the reader
     var chart = new google.charts.Bar(document.getElementById("Piechart_Phone"));
     var imgURI_Phone = “”;
     // Wait for the chart to finish drawing before calling the getImageURI() method., 'ready', function () {
         imgURI_Phone = chart.getImageURI();        
         document.getElementById('<%=hdImgSrcChart.ClientID %>').value = imgURI_Phone;
     chart.draw(data, options);    
 <asp:HiddenField ID="hdImgSrcChart" runat="server" />
 <div id='chart_content_div' style='top: 0; left: 0; position: absolute; visibility: hidden;
     width: 100% !important; height: 100% !important;'>
     <div id='Piechart_Phone' style='width: 650px; height: 600px; top: 0; left: 0;'>

Once we get the PNG data from client side scripting, we are passing its value to server side code using HiddenField element as shown above. getImageURI will return the value something like this,

Step 2: Convert ImageURI to Base64 data and change it to .NET Image object

In the server side code, add the below code script inside your <WebPartController>.cs file.

 string imgSrc = this.hdImgSrcChart.Value;
        string base64Data = "";
        //Create .NET Image object, please make sure it is not iTextSharp Image object
        System.Drawing.Image chartImage = null;
        if ((!string.IsNullOrEmpty(imgSrc)) && (imgSrc != "undefined"))
        	base64Data = Regex.Match(imgSrc, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
               chartImage = Base64ToImage(base64Data);
 //Function to Convert Base64 to Image obj
 public static System.Drawing.Image Base64ToImage(string base64String)
 // Convert base 64 string to byte[]
        byte[] imageBytes = Convert.FromBase64String(base64String);
        // Convert byte[] to Image
        using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
        	System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
               return image;

Step 3: Create an iTextSharp Image object

In Step 2, we generated the .NET Image object from base64 data. The below code snippet is continuation of the above step. In this we are adding the Image into PDF.

 if (chartImage != null)
 table = GetTables.GoogleChartInPDF(chartImage, 600, 350, "Chart:");
 //Add this table into main table, create new cell in the main table and add //chart image
        PdfPCell colMaintable = new PdfPCell(table);
               colMaintable.Border = Rectangle.NO_BORDER;
               colMaintable.BorderWidth = 0;
 //Function to Insert Google Chart Image into PDF
 public static PdfPTable GoogleChartInPDF(System.Drawing.Image GC_Image, float widthPixel, float heightPixel, string chartTitle)
 	     // Create new PDF table for Google Chart
             PdfPTable table = new PdfPTable(1);
             table.DefaultCell.BorderWidth = 0;
             table.DefaultCell.PaddingTop = 15;
             table.DefaultCell.PaddingBottom = 15;            
             if (GC_Image != null)
 		  //Insert the Image only if the GV_Image is available               
                 PdfPTable imgdataTable = new PdfPTable(1);
                 imgdataTable.TotalWidth = 100;
                 imgdataTable.PaddingTop = 15;
 		  //Adding Title
                 PdfPCell ImgCol = new PdfPCell(new Phrase(chartTitle,14));
 //Create iTextSharp.text.Image reference and assign .NET Image obj
              iTextSharp.text.Image orgChartImg = iTextSharp.text.Image.GetInstance(GC_Image, System.Drawing.Imaging.ImageFormat.Jpeg);
                 if (orgChartImg.Height > orgChartImg.Width)
                     float percentage = 0.0f;
                     percentage = heightPixel / orgChartImg.Height;
                     orgChartImg.ScalePercent(percentage * 100);
                     float percentage = 0.0f;
                     percentage = widthPixel / orgChartImg.Width;
                     orgChartImg.ScalePercent(percentage * 100);
                 PdfPCell rowImgData = new PdfPCell(orgChartImg);                
                 rowImgData.BorderWidth = 0;
 		  //Appending Data into Main Table
             return table;

The above code is self-explained through comments. Here I’ve show the approach to insert Google Chart Image to iTextSharp PDF Table. For creating PDF file from scratch and download that PDF into your local, please refer this Generate PDF report using iTextSharp (.NET PDF library) in SharePoint Environment.




Happy Coding


blog comments powered by Disqus

SharePoint Pals

SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile


Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community

SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation