How to save a rendered webpage as image with JavaScript? - javascript

In my app I have to provide a 'save as image' button. I want to save the HTML rendered on my webpage as an image in JavaScript. It is a webapp and will be used in browsers of desktop/tablet/mobile phones. How to save rendered HTML as an image?

Check out html2canvas. A javascript framework that renders the page content on a canvas element. Saving the canvas as an image is as easy as:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
source

Using http://html2canvas.hertzen.com/
index.php
<style>.wrap{background:white;padding:0 0 16px 0;width:1500px;}.colour{width:1500px;position:relative;height:1400px;}p.footer{text-align:center;font-family:arial;line-height:1;font-size:28px;color:#333;}.wrap img{height:389px;width:389px;position:absolute;bottom:0;right:0;left:0;top:0;margin:auto;}p.invert{position:absolute;top:300px;left:0;right:0;text-align:center;display:block;font-family:arial;font-size:48px;padding:0 40px;filter:invert(0%);}p.inverted{-webkit-filter: invert(100%);filter:invert(100%);}</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>
<?php // Open our CSV File
$colours = fopen('colours.csv', 'r');
// Reset Count
$i=0;
// Loop Through the Colours
while (($colour = fgetcsv($colours)) !== FALSE){
// Get the First Item and display some HTML
if($i==0){ ?>
<div id="target" class="wrap">
<div class="colour" style="background:<?php echo $colour[0]; ?>">
<img src="paragon2.png" alt="Image" />
<p class="invert inverted" style="filter:invert(100%);"><?php echo $colour[1]; ?></p>
</div>
<p class="footer"><?php echo $colour[1]; ?></p>
</div>
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
<input type="hidden" name="filename" id="filename" value="<?php echo $colour[0].".png"; ?>" />
</form>
<?php } // Count
$i++;
} // Loop
// Close the CSV File
fclose($colours); ?>
<script type="text/javascript">
$(window).load(function () {
$('#target').html2canvas({
onrendered: function (canvas) {
$('#img_val').val(canvas.toDataURL("image/png"));
document.getElementById("myForm").submit();
}
});
});
</script>
save.php
<?php // Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
$filename=$_POST['filename'];
// Decode the string
$unencodedData=base64_decode($filteredData);
// Save the image
file_put_contents("IMG2/".$filename, $unencodedData);
// Open the CSV File
$file = fopen('colours.csv', 'r');
// Loop through the colours
while (($line = fgetcsv($file)) !== FALSE) {
// Store every line in an array
$data[] = $line;
}
// Remove the first element from the stored array
array_shift($data);
// Write remaining lines to file
foreach ($data as $fields){
fputcsv($file, $fields);
}
// Close the File
fclose($file);
// Redirect and start again!
header( 'Location:/' ) ; ?>

Your question is very incomplete. First, is that a mobile or desktop app? In both cases, the solution to your problem will strongly depend on the HTML engine that renders the pages: Webkit, Geko/Firefox, Trident/IE for example have their own method to produce the view that you want to save as an image.
Anyway, you could start looking at how this Firefox plugin works: https://addons.mozilla.org/it/firefox/addon/pagesaver/
It should do what you want to implement, look for its source code.

Related

Save textarea data from HTML page to a TXT file

I am building a database server for an organization that I am a member of, and one of the options is that they need to be able to change a list of names. This list is in a txt file located in the webroot.
I have loaded the txt file content in a textarea in an html page, and now what I need to be able to do is to save the textarea content to the same file, in case we need to update or change the names.
I have tried this:
<textarea id="toroq" style="width: 100%; height: 200px;"><?php include("lista_toroq.txt") ?></textarea>
<input id="save_toroq" type="button" value="Save" onclick="WriteToFile();"/>
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var text=document.getElementById("toroq").innerText;
//var fileName=document.getElementById("TextArea2").innerText;
var s = fso.CreateTextFile("lista_toroq.txt", true);
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
the problem is that it is not saving the file
JavaScript is not able to edit or make changes directly to files stored on the web server without having some form of code running.
Using something like this:
<?php
if ($_POST["text"]) {
file_put_contents("file.txt", $_POST["text"]);
}
?>
The above code runs when $_POST["text"] has been set.
Change your HTML form to something like this:
<html>
<body>
<form method="POST">
<textarea name="text tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
You can store both of these bits of code in one PHP file. The result would be like this:
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>
<html>
<body>
<form method="POST">
<textarea name="text" tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
You cant write directly from javascript. You have to use PHP to write. You can use file_get_contents to get file content and you can use file_get_contents to write.
You can do something like below with HTML form.
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>

Loading Effect using JS and PHP

I am working on a project in PHP and AIML where the bot replies to the user queries asked by a user through a microphone. I am new to jQuery and JS so I need help in implementing loading effect in between the user input and final output.
<?php
$display = "";
$thisFile = __FILE__;
if (!file_exists('../../config/global_config.php'));
require_once ('../../config/global_config.php');
require_once ('../chatbot/conversation_start.php');
$get_vars = (!empty($_GET)) ? filter_input_array(INPUT_GET) : array();
$post_vars = (!empty($_POST)) ? filter_input_array(INPUT_POST) : array();
$form_vars = array_merge($post_vars, $get_vars); // POST overrides and overwrites GET
$bot_id = (!empty($form_vars['bot_id'])) ? $form_vars['bot_id'] : 1;
$say = (!empty($form_vars['say'])) ? $form_vars['say'] : '';
$convo_id = session_id();
$format = (!empty($form_vars['format'])) ? $form_vars['format'] : 'html';
?>
<!DOCTYPE html>
<html>
<head>
<title>Interact With Sia</title>
<script src="jquery.js"></script>
<script type="text/javascript" src="talk.js"></script>
</head>
<body onload='document.getElementById("say").focus(); document.getElementById("btn_say").style.display="none";'>
<center>
<h3>Talk to Sia</h3>
<form id="chatform1" name="chatform" method="post" action="index.php#end" >
<!-- <label for="say">Say:</label> -->
<input type="text" name="say" id="say" size="70" onmouseover="startDictation()" style="color:red" />
<input type="submit" class="say" name="submit" id="btn_say" value="say" />
<script>
$('#say').trigger('mouseover');
</script>
<input type="hidden" name="convo_id" id="convo_id" value="<?php echo $convo_id;?>" />
<input type="hidden" name="bot_id" id="bot_id" value="<?php echo $bot_id;?>" />
<input type="hidden" name="format" id="format" value="<?php echo $format;?>" />
</form>
<br/><br/>
<?php echo $display; ?> //THIS DISPLAYS THE OUTPUT TO THE QUERY
</center>
</body>
</html>
As soon as the page loads, the microphone in the user's browser is activated [via talk.js_startDictation()] and after the user finishes the voice input, the query is sent to the scripts and then the result is diplayed by <?php echo $display; ?>.
How can I implement a loading effect in place of <?php echo $display; ?> until the script returns the result of the query and updates the $display variable on the page?
You could use AJAX to archieve this, like:
1 - Load jquery.js (you could use CDN or download it).
2 - Create a div with a loader (usually a gif is fine, there are a lot). Hidde it with css: display:hidden;
3 - Add at the bottom of your page:
<script>
// Attach a submit handler to the form
$( "#chatform1" ).submit(function( event ) {
// Start the loader
$('#loader').show();
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var data = $(this).serialize();
var url = "urlToYourPhpFile.php";
// Send the data using post
var posting = $.post( url, { data: data } );
// Put the results in a div
posting.done(function( dataResponse ) {
//do something with dataResponse
$('#loader').hide();
});
});
</script>
When the form is sumitted, jquery 'catch' the request, process the .submit() functions and send the data via post to a .php file (you should create it) and receive the params with $_POST. Something like:
yourPhpFile.php
<?php
$convo_id = $data['convo_id'];
//do something
...
?>

how to manage in JavaScript null values from PHP code

I have the next PHP/HTML code for upload an image:
<label>Image (*)</label>
<!-- if image exists, show it -->
<?php if($category->getImage() === null) : ?>
<input type="file" name="image" id="image" required>
<?php else : ?>
<p><img src="../uploads/images/<?php echo $categoria->getImage(); ?>"></p>
<input type="file" name="image" id="image">
<?php endif; ?>
And I want to validate it using JavaScript
// Validate image
image = document.getElementById("image").value;
if (!image) {
window.alert("You must select a file for the image.");
document.getElementById("image").focus();
return false;
}
The image is required. If you create a new registry it sets all of its atributes to null, including the image. Then, the image is not show and you can set it in the form. If you want to update them, the form shows the current imagen but you don't have to update it if you don't want to.
I need to validate if the file hasn't been uploaded and the value is null it means that the user is creating a new registry and the image is required. If the file hasn't been uploaded but its value isn't null, the user is updating the registry and it isn't required to upload an image.
Thanks in advance and sorry for my bad english.
You can add id to the image
<img id="foo" src="../uploads/images/<?php echo $categoria->getImage(); ?>">
and check if it's in the DOM:
if ($('#foo').length) {
// image is there
}
or without jQuery:
if (document.getElementById("foo")) {
// image is there
}

How to save form/textarea to file with no file extension PHP

I am trying to pull a file in a textarea, edit it, then save the edited data to the same file. The submit function seems to go off, it posts the data, and in javascript console it returns the message "couldn't write values to file!", and in the original text area where it pulled the text from, it blanks out that file as if it overwrote the file with no information.
Am I using the wrong ID for my $data? (Textarea ID is edit, am presuming the information is coming from there).
I've used this same save setup on other .html pages, and am wondering if it is because I am saving to a file that has no file extension. If that is the issue, is there a way around that?
Maybe there is an issue elsewhere?
Snippet from my HTML page of the form area:
<form name="editorarea" method="post" action="/my/site/address/here/revotestingpdsave.php">
<textarea id="edit" style="width: 800px; height: 800px;">
<?php
$filevar = "/my/site/address/here/revotesting/actions";
$handle = fopen($filevar, "r");
$contents = fread($handle, filesize($filevar));
fclose($handle);
echo $contents;
?>
</textarea><p><input class="Save Button" type="submit" name="Save" value="Save" id="submit"></form></p></center>
And this is My Save Form PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['edit'];
if(get_magic_quotes_gpc()){
$data = stripslashes($data);}
$filevar = "/my/site/address/here/actions";
$fp = fopen($filevar, "w") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $filevar successfully!";
}
?>
<?php
// If this file is not on the server touch() will create it for you
$target = "/my/site/address/here/revotesting.cfg";
touch($target);
?>
to display the successful message on the same page just move the revotestingpdsave.php content to the same page so
<form method="post">
// rest of form
</form>
<?php
if(isset($_POST['edit'])) {
// add revotestingpdsave.php content here
}
?>
$_POST['edit'] is being sent empty, then it's being written to the file making it empty, just add name attribute to the textarea, like this:
<textarea id="edit" name="edit" style="width: 800px; height: 800px;">

Dynamic image upload and large image hover

I have a page that is supposed to dynamically upload photos and then display them as a thumbnail. Basically, this consists of two files: unit_edit.php and upload.php. My upload works fine, therefore I won't bother posting it. It places the uploaded image in the proper folder as well as the thumbnail with its proper size.
My issue is that it does not display the image once it's uploaded - I have to refresh the page. Also, the hover to display the larger image does not work, either. I am using YoxView which is giving my errors in the console - Uncaught ReferenceError: options is not defined I have to comment it out for the upload to work properly. I do not know how to define options. I tried following the installation guide and it isn't working. Here is my relevant code:
Here is the div where the photos are created and placed
<div class="editunitimages">
<form id="imageform" method="post" enctype="multipart/form-data" action='upload.php?id=<?php print $_GET['id']; ?>' >
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
<div id="unit_images">
<?php
require_once('config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = "SELECT id, image FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
$i = 1;
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/thumbnails/'.$row['image'].'" alt="'.$i.'" title="image '.$i.'" />';
$i++;
}
echo '</div>';
?>
</div>
</div> <!-- end editunitimages -->
Here is the javascript
<script>
$(document).ready(function()
{
//$("#thumbnails").yoxview([options]);
$('#photoimg').live('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="images/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>

Categories

Resources