If you have work on any PHP based dynamic web application and in which you are using Google Chart Library for creating report and visualization of your web application data then if you want to add one more feature like make PNG Image file or PDF file from your Dynamic Google chart which you have make by fetch data from Mysql database using PHP PDO script. So here you can find step by step guide how can we easily export Google chart in PDF file format or PNG Image. We have publish many post in this site regarding how to make dynamic chart by using Google Chart with PHP script with Mysql database.
For creating or exporting Google chart to PDF file first we want to convert into PNG image. So, first we need to save Google Chart as PNG Image then after we can easily export or convert into PDF file using PHP. Here we have use DomPDF library for export Google chart to PDF using PHP.
Convert Google Chart into PNG
In below you can find source code of Creating of Dynamic Pie Chart from fetch data from Mysql database and based on data we have make Pie chart using Google Chart Library with PHP. Here we have use getImageURI() method which print Google chart as PNG Image on web page.
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT gender, count(*) as number FROM tbl_employee GROUP BY gender";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<title>Export Google Chart to PDF using PHP with DomPDF</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
<?php
foreach($result as $row)
{
echo "['".$row["gender"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title : 'Percentage of Male and Female Employee',
pieHole : 0.4,
chartArea:{left:100,top:70,width:'100%',height:'80%'}
};
var chart_area = document.getElementById('piechart');
var chart = new google.visualization.PieChart(chart_area);
google.visualization.events.addListener(chart, 'ready', function(){
chart_area.innerHTML = '<img src="' + chart.getImageURI() + '" class="img-responsive">';
});
chart.draw(data, options);
}
</script>
</head>
<body>
<br /><br />
<div class="container" id="testing">
<h3 align="center">Export Google Chart to PDF using PHP with DomPDF</h3>
<br />
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Export Google Chart to PDF using PHP with DomPDF</h3>
</div>
<div class="panel-body" align="center">
<div id="piechart" style="width: 100%; max-width:900px; height: 500px; "></div>
</div>
</div>
</div>
<br />
<div align="center">
<form method="post" id="make_pdf" action="create_pdf.php">
<input type="hidden" name="hidden_html" id="hidden_html" />
<button type="button" name="create_pdf" id="create_pdf" class="btn btn-danger btn-xs">Make PDF</button>
</form>
</div>
<br />
<br />
<br />
</body>
</html>
<script>
$(document).ready(function(){
$('#create_pdf').click(function(){
$('#hidden_html').val($('#testing').html());
$('#make_pdf').submit();
});
});
</script>
Export Image to PDF
After create PNG image from Google Chart, now we can easily export it to PDF file. There are different ways for convert PNG to PDF using PHP. For example make PDF file from HTML we have use different PHP Library like TCPDF or DOMPDF. But here we have use DOMPDF library in which we can also use Bootstrap CSS library also which steps you can find below.
1. First Download the latest version of DOMPDF Library from here.
2. Unzip DOMPDF library file and put into your working folder from where you have execute php script.
3. Make a HTML form which send action to PHP file which convert HTML code to PDF. Here we have send request to create_pdf.php.
<form method="post" id="make_pdf" action="create_pdf.php">
<input type="hidden" name="hidden_html" id="hidden_html" />
<button type="button" name="create_pdf" id="create_pdf" class="btn btn-danger btn-xs">Make PDF</button>
</form>
Below you can find PHP Source code of pdf.php and create_pdf.php file for convert HTML to PDF.
<?php
//pdf.php
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
class Pdf extends Dompdf{
public function __construct(){
parent::__construct();
}
}
?>
<?php
//create_pdf.php
include('pdf.php');
if(isset($_POST["hidden_html"]) && $_POST["hidden_html"] != '')
{
$file_name = 'google_chart.pdf';
$html = '<link rel="stylesheet" href="bootstrap.min.css">';
$html .= $_POST["hidden_html"];
$pdf = new Pdf();
$pdf->load_html($html);
$pdf->render();
$pdf->stream($file_name, array("Attachment" => false));
}
?>
So, this is complete and step by step source code of Exporting of Google Chart to PDF using PHP PDO script with DOMPDF Library.
Database
--
-- Database: `testing`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_employee`
--
CREATE TABLE `tbl_employee` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`address` text NOT NULL,
`gender` varchar(10) NOT NULL,
`designation` varchar(100) NOT NULL,
`age` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_employee`
--
INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`) VALUES
(1, 'Bruce Tom', '656 Edsel Road\r\nSherman Oaks, CA 91403', 'Male', 'Driver', 36),
(5, 'Clara Gilliam', '63 Woodridge Lane\r\nMemphis, TN 38138', 'Female', 'Programmer', 24),
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 32),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29),
(175, 'Ronald D. Colella', '1571 Bingamon Branch Road, Barrington, IL 60010', 'Male', 'Top executive', 32),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 38),
(161, 'Glenda J. Stewart', '3482 Pursglove Court, Rossburg, OH 45362', 'Female', 'Cost consultant', 28),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 64),
(163, 'William C. Wright', '2653 Pyramid Valley Road, Cedar Rapids, IA 52404', 'Male', 'Political geographer', 33),
(178, 'Sara K. Ebert', '1197 Nelm Street\r\nMc Lean, VA 22102', 'Female', 'Billing machine operator', 50),
(177, 'Patricia L. Scott', '1584 Dennison Street\r\nModesto, CA 95354', 'Female', 'Urban and regional planner', 54),
(179, 'James K. Ridgway', '3462 Jody Road\r\nWayne, PA 19088', 'Female', 'Recreation leader', 41),
(180, 'Stephen A. Crook', '448 Deercove Drive\r\nDallas, TX 75201', 'Male', 'Optical goods worker', 36),
(181, 'Kimberly J. Ellis', '4905 Holt Street\r\nFort Lauderdale, FL 33301', 'Male', 'Dressing room attendant', 24),
(182, 'Elizabeth N. Bradley', '1399 Randall Drive\r\nHonolulu, HI 96819', 'Female', ' Software quality assurance analyst', 25),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29),
(184, 'Marks Johnson', '021, Big street, NY', 'Male', 'Head of IT', 41),
(185, 'Mak Pub', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 40),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 40);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=187;
very nice idea but in pdf css is not captured!
ReplyDelete
ReplyDeleteHello, the tutorial is great, it helped me a lot, I just have a problem, the graphics are too big and I can't control the amount of sheets that contain the pdf, help!
Hello, the tutorial is great, it helped me a lot, I just have a problem, the graphics are too big and I can't control the amount of sheets that contain the pdf, help!
ReplyDeleteit is perfectly working.. Thanks
ReplyDeleteWhere is autoload.inc.php file? "require_once 'dompdf/autoload.inc.php';"
ReplyDeletenot working
ReplyDeletenot showing pdf and no error in a console
ReplyDelete