jspdf function not working - php

I am in a situation where I have to download a HTML page into PDF now. I know JSPDF is the best solution for this and I have implemented the following code but its not working...
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
<title>Invoice</title>
<link rel="stylesheet" type="text/css" href="/jspdf/examples/css/smoothness/jquery-ui-1.8.17.custom.css">
<link rel="stylesheet" type="text/css" href="/jspdf/examples/css/smoothness/css/main.css">
<script type="text/javascript" src="/jspdf/examples/js/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/jspdf/examples/js/jquery/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript" src="jspdf/dist/jspdf.debug.js"></script>
<script type="text/javascript" src="/jspdf/examples/js/basic.js"></script>
<script type="text/javascript">
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
</script>
</script>
</head>
<body id="target">
<div id="content">
<h3>H3 tag</h3>
<p>a Para</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
</body>
</html>
Please help me with this situation...

The following is an example of how to implement the jspdf.js library in order to create PDF pages out of the current website.
The JS libraries needed can be downloaded here:
Please contact me or write down your comment if you find any bugs.
<script type="text/javascript" src='jspdf.min.js'></script>
<script type="text/javascript" src='html2canvas.js'></script>
<script type="text/javascript">
function genPDF()
{
html2canvas(document.body, {
onrendered : function(canvas)
{
try
{
var canvas1 = document.createElement('canvas');
canvas1.width = canvas.width; canvas1.height = canvas.height;
var context1 = canvas1.getContext('2d');
context1.drawImage(canvas, 0,0);
options = {orientation: "0", unit: "mm",format: "a4" };
var doc = new jsPDF(options,'p', 'pt', 'a4');
var number_needed_pages = canvas.height / 900;
if(number_needed_pages < 1) number_needed_pages = 1;
for(var x=0; x < number_needed_pages ; x++)
{
var canvas2 = document.createElement('canvas');
canvas2.width = 794; canvas2.height = 900;
var context2 = canvas2.getContext('2d');
context2.drawImage(canvas1, 0 , 0 + 900*x , canvas1.width, canvas2.height, 50, 0, canvas.width, canvas2.height);
doc.addImage(canvas2.toDataURL('image/png'), 'JPEG', '', '', '');
doc.addPage();
}
doc.save("output_file.pdf");
} catch(e){alert(e);}
}
});
}

Related

GeoLocation using PHP

I copied paste following code and I am a noob at this. So can you point out error please? I am sorry for asking such a stupid question.
<HTML>
<HEAD>
</HEAD>
<BODY>
<h3>Client side IP geolocation using ipinfo.io</h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>
</BODY>
</HTML>
<script type="text/javascript" charset="utf-8">
$.get("http://ipinfo.io", function(response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
</script>
HtML5 using get user latitude, longitude and get current user address.
Sample code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
</head>
<body>
<p>Address: <div id="address"></div></p>
</body>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var currgeocoder;
//Set geo location lat and long
navigator.geolocation.getCurrentPosition(function(position, html5Error) {
geo_loc = processGeolocationResult(position);
currLatLong = geo_loc.split(",");
initializeCurrent(currLatLong[0], currLatLong[1]);
});
//Get geo location result
function processGeolocationResult(position) {
html5Lat = position.coords.latitude; //Get latitude
html5Lon = position.coords.longitude; //Get longitude
html5TimeStamp = position.timestamp; //Get timestamp
html5Accuracy = position.coords.accuracy; //Get accuracy in meters
return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}
//Check value is present or
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
//call google api function
var myLatlng = new google.maps.LatLng(latcurr, longcurr);
return getCurrentAddress(myLatlng);
}
}
//Get current address
function getCurrentAddress(location) {
currgeocoder.geocode({
'location': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0]);
$("#address").html(results[0].formatted_address);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
</script>
</html>
Demo: http://jsfiddle.net/hmy7e0fs/
<HTML>
<HEAD>
</HEAD>
<script src="http://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript" ></script>
<script src="http://js.maxmind.com/js/geoip.js" type="text/javascript" ></script>
<script type="text/javascript" charset="utf-8">
$.get("http://ipinfo.io", function (response) {
alert('hello');
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
</script>
<BODY>
<h3>Client side IP geolocation using ipinfo.io</h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>
</BODY>
</HTML>
Use this:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$locationArray = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $ip));
echo '<pre>';
print_r($locationArray);
?>
I would like to prefer geoplugin better than http://ipinfo.io as its request limit per minute is max.
For more info please visit: http://www.geoplugin.com/

passing array to flot

I have been trying to make a graph plot with flot, and have ran into a problem.I Think the problem is with the way m using the php variable with flot Aside from that the graph isn't showing so I must have done something wrong. Below is the graph code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="./flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.categories.js"></script>
</head>
<body>
<?php
//CONNECTING TO THE SERVER
$servername = "XXX";
$username = "YYY";
$password = "ZZZ";
conn = new mysqli($servername, $username, $password);
$sql = "SELECT NAME, AGE FROM pro_db";
$result = $conn->query($sql);
$wt=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//storing the values in the array
$wt[]=$row;//is this the right way
}
} else {
echo "0 results";
}
?>
<div id="placeholder" style="width:600px;height:300px;"></div>
<script type="text/javascript">
$(function () {
//accessing the array
var data = <?php echo $wt; ?>;
$.plot($("#placeholder"), [data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center" }
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
});
</script>
</body>
</html>``
Here's completely working example i made. If something doesn't work - there's some error with data. Try var_dump how your $wt array looks like in the end;
$data = [
['Andrew', 31],
['Helen', 29],
['Dasha', 24],
['Denis', 23]
];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="canvas" style="width: 600px; height: 400px;"></div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/flot/jquery.flot.js"></script>
<script src="bower_components/flot/jquery.flot.categories.js"></script>
<script>
var data = <?php echo json_encode($data) ?>;
$("#canvas").plot([data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
</script>
</body>
</html>

Getting data in a text file after updating it on highcharts but initially retrieving from csv file

I am actually trying to do exactly what has been done in this example "http://jsfiddle.net/BrLp7/" but unfortunately not able to perform this task when retrieving data from csv file. Below is my code which doesn't output anything and when we click on a point in a given example the resulting graph has to be stored in some text file in this form 5,10,13 if last point was clicked.
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION = "BasicForm.php">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="../js/highcharts.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../js/excanvas.compiled.js"></script>
<![endif]-->
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Input'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
$.get('testFile.csv', function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var x=this.series.processedXData.indexOf(this.x);
var items = line.split(',');
seriesData =[];
$.each(items, function(itemNo, item) {
if (itemNo < x) {
seriesData.push(parseFloat(item));
} else if (itemNo == x){
seriesData.push(0);
}
});
}
this.series.setData(seriesData);
}
}
}
},
series: []
};
$.get('testFile.csv', function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
series.data.push(parseFloat(item)); });
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- 3. Add the container -->
<div id="container" style="width: 1400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
</FORM>
</body>
</html>

How to reload a page in jquerymobile?

In My Project I am having some javascript to implement my work, but it is not taking when I am starting the page,but it is working after reloading the page.
Here is the code:
<?php
require_once"session.php";
$slat =$_GET['slat'];
$slang =$_GET['slang'];
$elat =$_GET['elat'];
$elang =$_GET['elang'];
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php require_once"header.php";?>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Near My Location Contacts</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
/* function refreshPage() {
alert('dfg');
window.location.href,
{
allowSamePageTransition : true,
transition : 'none',
showLoadMsg : false,
reloadPage : true
}
}
refreshPage();*/
//<![CDATA[
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
//var haight = new google.maps.LatLng(37.7699298, -122.4469157);
//var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);
var haight = new google.maps.LatLng(<?php echo $slat;?>,<?php echo $slang;?>);
var oceanBeach = new google.maps.LatLng(<?php echo $elat;?>,<?php echo $elang;?>);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
function calcRoute() {
var request = {
origin:haight,
destination:oceanBeach,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
//]]>
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize();calcRoute()">
<div data-role=page id=nmContacts >
<div data-role=header data-theme="e" >
Back</font>
<h1 align="left"><font size="2px">Near My Contacts</font></h1>
</div>
<div data-role=content style="width:100%;height:100%;">
<div data-role=content id="map_canvas" style="width:95%; height:300px"></div>
<div id="directionsPanel" style="width:97%;height 100%"></div>
</div>
</body>
</html>
In the above I am having body onload it is not working at the first time after refreshing only it is working.
Here is the answer:
Before You are calling to this page You have to specify in href like the following
assume that you are having the following link to load:
sample
here `href="external" You have to specify otherwise it wont work.....

HTML5: saving the chart as an image on the server

Who knows about rgraph and HTML5? ( http://www.rgraph.net )
The code of my chart is the following and my problem is that I can't save the canvas (image) on the server even following their suggestion.
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Title</title>
<meta name="keywords" content="rgraph javascript charts html5 canvas basic example" />
<meta name="description" content="A basic example of an RGraph chart for implementation help" />
<meta name="googlebot" content="NOODP">
<!-- Place this tag in your head or just before your close body tag -->
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<script src="../libraries/RGraph.common.core.js" ></script>
<script src="../libraries/RGraph.common.context.js" ></script>
<script src="../libraries/RGraph.common.annotate.js" ></script>
<script src="../RGraph.common.tooltips.js" ></script>
<script src="../libraries/RGraph.common.zoom.js" ></script>
<script src="../libraries/RGraph.common.effects.js" ></script>
<script src="../libraries/RGraph.common.key.js" ></script>
<script src="../libraries/RGraph.line.js" ></script>
<script src="../libraries/RGraph.common.key.js" ></script>
<!--[if lt IE 9]><script src="../excanvas/excanvas.original.js"></script><![endif]-->
<script src="../libraries/jquery.min.js" ></script>
<script>
window.onload = function ()
{
var line1 = new RGraph.Line('line1', [3,56,22,7,84,8,34,1,1], [3,4,45,0,5,97,46,29,7]);
line1.Set('chart.background.grid', true);
line1.Set('chart.linewidth', 3);
line1.Set('chart.gutter.left', 35);
line1.Set('chart.hmargin', 5);
if (!document.all || RGraph.isIE9up()) {
line1.Set('chart.shadow', true);
}
line1.Set('chart.tickmarks', null);
line1.Set('chart.units.post', '');
line1.Set('chart.colors', ['#FA4E1D', '#2D659A']);
line1.Set('chart.background.grid.autofit', true);
line1.Set('chart.background.grid.autofit.numhlines', 10);
line1.Set('chart.background.grid.autofit.numvlines', 29);
line1.Set('chart.curvy', 0);
line1.Set('chart.curvy.factor', 0.25);
line1.Set('chart.labels',['1','2','3','4','5','6','7','8','9']);
line1.Set('chart.title','Title of the Chart');
line1.Set('chart.key.text.size',7);
line1.Set('chart.key',['A','B']);
line1.Set('chart.key.shadow','shadow');
line1.Set('chart.key.position','graph');
line1.Set('chart.ymax',200);
line1.Draw();
}
</script>
</head>
<body>
<center><h2>My title</h2><center>
<!-- 2/3. This is the canvas that the graph is drawn on -->
<div style="text-align: center">
<canvas id="line1" width="300" height="180">[Please wait...]</canvas>
</div>
</body>
</html>
The suggestion is at the end of this page: http://www.rgraph.net/docs/index.html#image at the specific paragraph "Saving the chart as an image on the server".
My only result is a 0-lenght file .png inside my server.
Could someone help me?
Thanks in advance.
Mattew
This is how I do it (you'll probably want to add some sort of validation in the PHP to prevent random uploading):
JS:
function saveImage(){
var xmlhttp;
xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"));
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//do something with the response
}
}
xmlhttp.open("POST","myImageSavingScript.php",true);
var oldCanvas = document.getElementById('line1').toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
xmlhttp.setRequestHeader("Content-type", "application/upload")
xmlhttp.send(oldCanvas);
}
PHP:
<?php
$im = imagecreatefrompng($GLOBALS["HTTP_RAW_POST_DATA"]);
imagepng($im, 'filename.png');
?>
And this is a variation if you need to pass other parameters along with it:
JS (just the mod):
var oldCanvas = document.getElementById('line1').toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
var params=oldCanvas+"&someOtherParameter=parameterValue";
xmlhttp.setRequestHeader("Content-type", "application/upload")
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
PHP:
<?php
$params=explode('&',$GLOBALS["HTTP_RAW_POST_DATA"]);
$val=split("=",$params[1]);
$someOtherParam=urldecode($val[1]);
$imgsrc=str_replace(' ','+',$params[0]);
$im = imagecreatefrompng($imgsrc);
imagepng($im, 'filename.png');
?>

Categories