Convert HTML div to image in jQuery - javascript

I want to pass an url from my jsp page. It should parse that page, fetch a specific div of html and convert div output in to a image and display it on my page.
Example: I pass www.google.com and output of div i want to convert in image is
I got a good jQuery for the same "http://codepedia.info/convert-html-to-image-in-jquery-div-or-table-to-jpg-png/" but its working on local page only not allowing to pass a URL
can anyone help in this matter.

#Pushkar Sharan you can do this with html2canvas just add some script
like jquery-ui.css, jquery.js, jquery-ui.js,
https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js
then try to understand below code
<html>
<head>
<link href="jquery-ui.css" rel="stylesheet">
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script>
$(window).load(function(){
$('#load').click(function(){ //calling this function when Save button pressed
html2canvas($('#cont'), {//give the div id whose image you want in my case this is #cont
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png",1.0);//here set the image extension and now image data is in var img that will send by our ajax call to our api or server site page
$.ajax({
type: 'POST',
url: "http://localhost/my/index.php",//path to send this image data to the server site api or file where we will get this data and convert it into a file by base64
data:{
"img":img
},
success:function(data){
$("#dis").html(data);
}
});
}
});
});
});
</script>
</head>
<body>
<div id="cont">
</div><br>
<center><input type="button" value="Save" id="load"></center><br>
<div id="dis"></div>
</body>
</html>
Now server site program suppose this is index.php so
index.php
<?php
$img = $_POST['img'];//getting post img data
$img = substr(explode(";",$img)[1], 7);//converting the data
$target=time().'img.png';//making file name
file_put_contents('uploads/'.$target, base64_decode($img));//converting the $img with base64 and putting the image data in uploads/$target file name
//now just check in your upload folder you will get your html div image in that folder
?>

Related

Parse HTML input value to php over javascript file

I have the following scenario running:
graph.html --> uses ChartJS to display a line graph and imports graph.js
<html>
<head>
<title>ChartJS - LineGraph</title>
</head>
<body>
<div class="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<form name="form" action="" method="get">
<input type="text" name="input" id="subject" value="">
</form>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/graph.js"></script>
</body>
graph.js --> makes a AJAX call on the graph.php file to get the data and format it.
$(document).ready(function(){
$.ajax({
url : "/graph.php",
type : "GET",
success : function(data){
console.log(data);
...
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
graph.php --> Calls mysql database to get data
$var = $_GET['input'];
$query = sprintf("SELECT $var FROM wetter");
//execute query
$result = $mysqli->query($query);
I like to change the SELECT statement in the php-file by entering a new SELECT-statement in a input field of the .html file. If I put the normal $_GET[] method into the .php it will not find the input value from the .html file.
How can I parse the input value from the .html to the .php when there is a Javascript file in between?
Do I need to change something in my scenario?
From the code you've shown, it doesn't look like you're passing the input value along with your ajax request, you should add something like
$.ajax({
url : "/graph.php",
type : "GET",
data : {input : $('#subject').val()}, <-- added this
success : function(data){
In order to be able to see the value in $_GET['input'] on the php side.
But there is another issue I believe, your ajax request is sent as soon as your document is ready ($(document).ready(function(){), but at that time your input is most likely going to be empty. You probably want to change it to $('form[name="form"]').on('submit',function(event){event.preventDefault(); ...}), assuming your form only does that one thing (display a graph according to the input)

$.post() Get url of php in html

I am making an html script that will use jQuery.post() method in order to use a php script. The post() method needs an url of the php code but my php code is part of the html code
What Url should i use?
<html>
<body>
<button onclick="test()">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var test = function() {
$('--I DONT KNOW--',{testvar:"hello"});
}
</script>
<?php
$testvar = $_POST['testvar'];
echo $testvar;
?>
</body>
</html>
An empty URL is a relative URL that resolves as the URL of the current page.
$.post("", {testvar:"hello"});
(Keep in mind that since your PHP does nothing with the data except output it, and your JS does nothing with the response, this will have no visible effect outside of the Network tab of your browser's developer tools).

Html code to Png image

I made a web application which allow the user to create an image dynamically in JavaScript.
It use jQuery to allow the user to place div, resize them and drag them into a <div> Container.
When the user finished to place all div, he can press the "Generate" button which send the <div> Container outerHTML code into a local database.
Then the user can use another script, in php, and past in parameter the id in the database of which render he want to display, then the php script create a page using the code in the database.
My problem is now I want to take the code of this generated html page, then convert it into a png image.
I looked at some other posts and found something interesting : Phantom.js
But what I tried doesn't seem to work. Here is my code :
<html>
<head>
<title>Test</title>
<LINK rel='stylesheet' type='text/css' href='style.css'>
<script type='text/javascript' src='jquery/jquery.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>
</head>
<body>
<script>
var page = require('webpage').create();
page.open('http://10.237.35.10/maxime/affichage.php?afficheur=0', function() {
page.render('affichageTest.png');
phantom.exit();
});
</script>
</body>
</html>
So we have the database with the div outerHTML code contained at the id '0'.
"affichage.php" take in parameter a variable "afficheur" then it ask the database to get the code from this variable. For example, afficheur=0 will return the div code contained in the database at the id=0.
When I go to "http://10.237.35.10/maxime/affichage.php?afficheur=0" I have a html page with the render I want. But when I try to run the script I'd posted higher, I haven't any "affichageTest.png" rendered in my folder.
What do I have to do? Do I have to import anything else to run Phantom.js? Or maybe I need to add something to my code?
PhantomJS is a binary not a javascript librarie (it is actually a headless webkit), I can not test it here atm, but here the main idea :
First download the PhantomJS binary, upload it somewhere and make it executable (chmod +x).
Create a file named test.js with this code below :
var page = require('webpage').create();
page.open('http://10.237.35.10/maxime/affichage.php?afficheur=0', function() {
page.render('affichageTest.png');
phantom.exit();
});
Create a file named display.php with this code below :
<?php
$file_path = exec('/path/to/phantomjs test.js');
?>
<html>
<head>
<title>Test</title>
<LINK rel='stylesheet' type='text/css' href='style.css'>
<script type='text/javascript' src='jquery/jquery.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>
</head>
<body>
<img src="<?php $file_path ?>" alt="test">
</body>
</html>
Visit the display.php page to see the screen capture
If you need a full script solution, as you have said in comments, your only hope is Image Magic php extension. This in conjunction with HTML2PDF can be used to device html to image conversion for non-complex markup.
The trick is to create a pdf out of html first:
$html2pdf = new HTML2PDF('P', 'A4');
$html2pdf->writeHTML($html_content);
$file = $html2pdf->Output('temp.pdf','F');
Now you can get this pdf file and convert it image using Image Magic
$im = new imagick('temp.pdf');
$im->setImageFormat( "jpg" );
$img_name = time().'.jpg';
$im->setSize(800,600);
$im->writeImage($img_name);
$im->clear();
$im->destroy();
Installation of Image Magic extensions and support libraries could be painstaking. Please read the installation notes carefully.
The complexity of the html markup which could be converted is limited. You can do a fairly good job. But you can't call it a day if you need to convert ANY html.

Call a function from another file [duplicate]

This question already has answers here:
Why am I seeing 'function not defined' on my error console when I'm sure my function IS defined?
(3 answers)
Closed 4 months ago.
I want to call the function like I did in the following HTML code:
<html>
<head>
<script>
var reg1 = new Image
var red1 = new Image
reg1.src="1.gif"
red1.src="1R.gif"
var reg1s = new Image
var red1s = new Image
reg1s.src="1s.gif"
red1s.src="1sR.gif"
var reg3s = new Image
var red3s = new Image
reg3s.src="3s.gif"
red3s.src="3sR.gif"
</script>
</head>
<body>
<script LANGUAGE="JavaScript" src="script.js">
NavigationBar();
</script>
<h1 align="center">Welcome to Drexel!</h1>
<center> <img src="DrexelDragons.png"> </center>
These images are public domain clip art obtained from
<img src="cwbutton.gif">
</body>
</html>
I am calling it from a separate .js file. Here is the code.
function NavigationBar()
{
document.write("<img src=\"1.gif\" Name=\"thereg1\">")
return ""
}
My problem is that this will run but it wont display the image or do what I want it to do while it is declared as a Function. If I just put it as a document.write statement it works just fine but I need it as a function.
Don't mix script tags that load an external resource and script tags that should execute their content. Browsers are required to ignore the content in the tag if the tag has a src attribute:
If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI
Change it to this and it should work:
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
NavigationBar();
</script>
Sources:
What does a script-Tag with src AND content mean?
http://www.w3.org/TR/1999/REC-html401-19991224/interact/scripts.html#edef-SCRIPT

How to load more jquery script to DOM by jquery ajax

I am creating an application that may become very large over time. So in order to keep things simple, we have decided to keep Javascript (mostly jQuery code), CSS and html for one particular feature in one file. for example, if upload is a function, then we have all the jQuery validation and css, html for upload in one file (without head and html tags).
We have a home dashboard in which a click handler will load all the links by ajax and append to the designated DIV of class indicated by additional attribute in links called "whereTOadd". so if a link has its "WhereTOadd" attribute set to ".here" and href set to upload.php then the contents of upload.php will be added to a div of class 'here' in the same page. it is done using script given below.
But the problem i am facing is that I need to include jQuery file again in every file to get the codes working, which is a terrible thing. What can be done to avoid this?
This is html of my dashboard:
<html>
<head>
..
<script src="Path-to-jquery-min-file.php" ></script>
<script>
$( document ).ready(function(){
$(document).on("click","a",function(e){
if( $(this).attr('href'))var ajaxurl = $(this).attr('href').valueOf();
if( $(this).attr('whereTOadd'))
var target = $(this).attr('whereToadd').valueOf();
/*for ajax request */
var options= {
type: 'GET',
url: ajaxurl,
dataType: 'html',
success: function (html, textStatus){
$(target).empty().append(html);
},
error: function(xhr, textStatus){
alert('error');
}
}
$.ajax(options);
return false;
});
});
</script>
</head>
<body>
<a href="upload.php" >Upload data</a>
<div class=".here" ></div>
</body>
upload.php contains:
<script type="javascript" >
$('body').append('load successful!');
</script>
This setup will not work until I make change in upload.php as:
<script src="Path-to-jquery-min-file.php" ></script>
<script type="javascript" >
$('body').append('load successful!');
</script>
Please help in solving this because loading jQuery again and again in the same page may cause errors and conflicts. Please suggest me a better approach to what I am doing.
Thanks

Categories