Reference : http://git.macropus.org/2011/11/pdftotext/example/
In this project developer has taken a pdf as input and pass it to variable "input". I want to create an upload menu/dropzone so that anyone can upload their pdf and it automatically get passed to the variable "input" and text can be extracted. I am able to upload the file but don't know how to pass that pdf to the variable "input".
<body>
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<div id="drop">
Drop Here
<a>Browse</a>
<input id="inputx" src="./"type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
Now using this form a pdf will be uploaded now we have to pass it the variable "input ".
<script>
var input = document.getElementById("input");
var processor = document.getElementById("processor");
var output = document.getElementById("output");
window.addEventListener("message", function(event){
if (event.source != processor.contentWindow) return;
switch (event.data){
case "ready":
var xhr = new XMLHttpRequest;
xhr.open('GET', input.getAttribute("src"), true);
xhr.responseType = "arraybuffer";
xhr.onload = function(event) {
processor.contentWindow.postMessage(this.response, "*");
};
xhr.send();
break;
default:
output.innerHTML = event.data.replace(/\s+/g, " ");
break;
}
}, true);
</script>
</body>
You just need to point Pdf.js to the copy of the file you've uploaded.
In your code above, Pdf.js gets its data via an XMLHttpRequest wherein it looks for a .pdf with the file name defined as the src attribute of the element with ID input:
xhr.open('GET', input.getAttribute("src"), true);
If you set the src attribute on this element to the file path of the pdf you've uploaded to the server, then the script should work as-is.
Here's some code that might help you - index.html is a simple file upload form that calls PHP to upload a file into the same directory it (index.html) is served from. file_upload.php saves the uploaded file and sets the value of the src attribute on the iframe with this line:
<iframe id="input" src= <?php print $_FILES['userfile']['name'] ?> ></iframe>
index.html
<html>
<head>
<title>Converting PDF To Text using pdf.js</title>
</head>
<body>
<div>
<!-- the PDF file must be on the same domain as this page -->
<form enctype="multipart/form-data" action="file_upload.php" method="POST">
<input id="fileInput" type="file" name="userfile"></input>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
file_upload.php
<?php
$uploadfile = basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
<html>
<head>
<title>Converting PDF To Text using pdf.js</title>
<style>
html, body { width: 100%; height: 100%; overflow-y: hidden; padding: 0; margin: 0; }
body { font: 13px Helvetica,sans-serif; }
body > div { width: 48%; height: 100%; overflow-y: auto; display: inline-block; vertical-align: top; }
iframe { border: none; width: 100%; height: 100%; }
#output { padding: 10px; box-shadow: 0 0 5px #777; border-radius: 5px; margin: 10px; }
#processor { height: 70px; }
</style>
</head>
<div>
<!-- embed the pdftotext web app as an iframe -->
<iframe id="processor" src="../"></iframe>
<!-- a container for the output -->
<div id="output"><div id="intro">Extracting text from a PDF file using only Javascript.<br>Tested in Chrome 16 and Firefox 9.</div></div>
</div>
<div>
<iframe id="input" src= <?php print $_FILES['userfile']['name'] ?> ></iframe>
</div>
<script>
var input = document.getElementById("input");
var processor = document.getElementById("processor");
var output = document.getElementById("output");
window.addEventListener("message", function(event){
if (event.source != processor.contentWindow) return;
switch (event.data){
case "ready":
var xhr = new XMLHttpRequest;
xhr.open('GET', input.getAttribute("src"), true);
xhr.responseType = "arraybuffer";
xhr.onload = function(event) {
processor.contentWindow.postMessage(this.response, "*");
};
xhr.send();
break;
default:
output.textContent = event.data.replace(/\s+/g, " ");
break;
}
}, true);
</script>
</body>
</html>
Related
I would like to convert every message that is received into an image, and with the download button download it. every post is different
This is my .js code
// fetch Messages
function fetchData() {
$('#displayMessages').html('<div class="alert alert-info">Stiamo recuperando i tuoi messaggi!...</div>');
$('#messages').click();
$.ajax({
url: 'controller/fetch_comments.php',
//success
success: function(data){
if (data=='please login') {
window.location='./';
console.log(data);
}
else{
var $fetch ='';
var component ='';
if (/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '#').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
data=JSON.parse(data);
console.log(data);
$.each(data, function(i, fetchAll){
var fetchData= data[i];
let message_title = fetchData.message_title ?? ""
$fetch += '<div class="row m-0"> <div class="pull-left alert col-md-2 mb-0"><img src="assets/img/anon.jpg" style=" width: 50px; height: 50px; border-radius:50%; box-shadow: 0 3px 2px rgba(0, 0, 0, 0.3); border: 5px solid #2c2c2c;" class="m-0"></div> <div class="alert col-md-7 m-0" style="margin-left:0px; color:#2c2c2c;"> <b>' +message_title +'</b><br>' +fetchData.description
+'</div> <div class="col-md-3 alert pull-right m-0"><span style="color: black;" class="fa fa-clock m-0"></span><br><text style="color: black; font-size:10px;"> ';
$fetch+=fetchData.date_created+'</text></div></div>';
});
} else {
$fetch +='<div class="alert alert-danger">Ancora nessun messaggio 😒</div>';
console.log(fetch);
$('#displayMessages').html($fetch)
}
$('#displayMessages').html($fetch);
}
}
});
}
this is the php code
$usersObj = new Comments();
$logsObj = new Logs();
$id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1;
if (empty($id)) {
exit();
}
if ($allComments = $usersObj ->FETCH_COMMENTS($id)) {
$logDescription = 'data fetched!';
$logsObj->INSERT_LOG($id, $logDescription);
}else{
echo 'log failed';
}
echo isset($allComments) ? json_encode($allComments) : 'nothing found';
This is my html in my dashboard, is used to show the message
<div class="tab-pane active" id="home" role="tabpanel">
<div id="displayMessages">
</div>
</div>
I don't understand where I have to act, thanks for the help feel free to edit the code
You could do this as a oneliner in javascript.
Just by using the library html2canvas.
e.g.
html:
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
js:
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});
put the image into an a tag with the propertie of "download".
I hope i could help you out.
EDIT:
In your html file add the cdn as following to the head:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas
/1.4.1/html2canvas.min.js"></script>
then in your js file
const body = document.querySelector("body");
const a_tag = document.createElement("a"); //just create an a tag
a_tag.innerHTML = "download"; //this text is displayed
a_tag.download = "image.png"; //pictures will download as image.png - you can customize the name and file format, but not all formats are acceptet in html2canvas
body.appendChild(a_tag); //append the a tag to the body element, you will need to customize this for your needs
html2canvas(document.querySelector(".wrapper")).then((canvas) => {
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob); //creates location of image
a_tag.href = url; //append url to a tags href
});
});
You will need this for every Message you receive. After your messages are displayed in the dom as html, the "html2canvas" will create an image out of that. In the "toBlob" function the image is just cached but not showing anywhere. We link the blob url (location of the cached image) to the a tags href. So if we then click on it, it will download. The .wrapper in the html2canvas function i've selected should be your message-div
I have a templates / index.html file. When you click on the first button, btn_query, you should callstartDictation(), a javascript function for speech recognition. But there is a problem, which only appears on StackOverflow and with Chrome, with recognition.onresult = function (e) {...}.
 1. I do not get the pop-up window.alert (5 + 6); at the beginning of the function.
 2. The StackOverflow console recognizes that there is an error and writes: Recognition had an error. But I do not know which one.
It acts like this: it asks for the permission to use the microphone and then there is a red light on the tab on the top and finally the error message.
<!DOCTYPE html>
<html style="margin: auto; display:table;">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
</script>
<script>var synth = window.speechSynthesis;</script>
<!-- HTML5 Speech Recognition API -->
<script>
function startDictation() {
document.getElementById('transcript').value = '';
document.getElementById('output').value = '';
if (window.hasOwnProperty('webkitSpeechRecognition')) {
var recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = "en-US";
recognition.start();
recognition.onresult = function (e) {
window.alert(5 + 6);
document.getElementById('loader').hidden = false;
document.getElementById('transcript').value = e.results[0][0].transcript;
recognition.stop();
var data = e.results[0][0].transcript;
$.post("http://localhost:5000/news_urls", { "data": data },
function (response) {
document.getElementById('loader').hidden = true;
data = response;
document.getElementById("output").value = data["urls"];
}).error(function (response) {
document.getElementById('loader').hidden = true;
if (response.status == 400)
text = jQuery.parseJSON(response.responseText)["original_exception"];
else
text = "I'm sorry. I did not get that.";
document.getElementById("output").value = text;
});
};
recognition.onerror = function (e) {
recognition.stop();
console.log("Recognition had an error");
window.alert(10 + 6);
}
}
}
function btnClick() {
synth.cancel();
var utterThis = new SpeechSynthesisUtterance(document.getElementById("output").value);
utterThis.voice = synth.getVoices()[0];
utterThis.pitch = 1.0;
utterThis.rate = 0.8;
utterThis.onerror = function(e) { console.log("Something went wrong with utterance."); };
synth.speak(utterThis);
}
</script>
<style>
.speech {
border: 0px solid #DDD;
width: 600px;
padding: 0;
margin: 0;
font-family: "Calibri";
}
.speech input {
border: 1;
width: 240px;
display: inline-block;
height: 30px;
}
.speech img {
float: right;
width: 40px;
}
</style>
</head>
<body bgcolor="#e2e2e2">
<h1 style="font-family: Calibri;">Delbot</h1>
<div class="speech" ><i>It understands your voice commands, searches news and knowledge sources, and summarizes and reads out content to you.</i></div>
<br /><i class="speech"><font color="gray">Only tested on Windows PCs. Not tested on other PCs or mobile devices.</font></i>
<div class="speech">
<textarea style="width: 600px;font-family: Calibri;font-size:x-large" name="q" id="transcript"
placeholder="Your query will appear here after you speak." rows="2" readonly="True"></textarea>
<br>
<input id="btn_query" type="button" onclick="startDictation()" value="Query"
style="font-family: Calibri;" />
<img src="static/loader.gif" width="100px" align="left" style="float: left" hidden="True" id="loader" />
<br><br>
<h2 class="speech">Results</h2>
<textarea style="width: 600px;font-family: Calibri;font-size:x-large" id="output" rows="2" placeholder="Results will appear here."
readonly="True"></textarea>
<input id="btn_speak" type="button" value="Speak" onclick="btnClick()" style="font-family: Calibri;" />
</div>
</body>
</html>
It seems you are running into the browser with a local file path.
For e.g. file://xyz/ss/ss/test.html
Try to host this HTML file on the server and check you will get the appropriate result.
Check this and this. As chrome does not support to allow microphone with a local file path. You can forcefully do it but it is not recommended. With the really dangerous --disable-web-security (strongly not recommended, especially if you use this instance of Chrome for normal browsing as well, which can put your device in danger) and --allow-file-access-from-files (also not recommended).
Debug:
I am getting the same error by accessing the local file.
But while host the index.html file and access http://localhost:1111 it's working perfectly.
Note:- Some editors load plain HTML into the browser. Try below editors where they host your file and run perfectly. Just C+V your code to an editor and run. Try with below editors.
https://www.tutorialspoint.com/online_javascript_editor.php
https://www.w3schools.com/tryit/tryit.asp?filename=tryhtml_default
Update=============
I am getting a return of undefined. I don't even know what to do. So lost...
html
<!DOCTYPE html>
<html>
<head>
<!--Jquery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!--Local files attached-->
<script type="text/javascript" src="CountryList.js"></script>
<link rel="stylesheet" type="text/css" href="CountryList.css" />
</head>
<body>
<div id="wrapper">
<!--Header-->
<h1>Country Information</h1>
<!--input box-->
<form>
<label for="countryInput">Input Country Name : </label>
<input type="text" id="countryInput"></input>
</form>
<br>
<br>
<!--Containing divs for lists-->
<div id="wrapper2">
<!--countries will load here-->
<div id="countryList">
Countries:
<div id="actualList">
</div>
</div>
<!--country info will load here-->
<div id="countryInfo">
Country Info:
<div id="actualInfo">
</div>
</div>
</div>
</div>
</body>
<div id="footer">
<!--Link to page-->
</div>
</html>
css
body{
margin-top:3%;
background-color:white;
text-align:center;
}
h1 {
}
h2 {
font-size:14pt;
}
#header {
color:white;
text-align:center;
padding:5px;
}
#footer {
color:white;
text-align:center;
padding:5px;
}
#countryList {
text-align:center;
overflow:auto;
width: 10%;
height: 400px;
border: 1px solid black;
display: inline-block;
float:left;
margin-left:20%;
}
#countryInfo {
text-align:center;
overflow:auto;
width: 49%;
height: 400px;
margin-right: 20%;
border: 1px solid black;
display: inline-block;
float:right;
}
button {
margin-left:15px;
margin-top:10px;
padding:5px;
margin-bottom:10px;
}
Javascript:
$(document).ready( function(){
var fieldInput = "";
var countrylist = "";
var countryinfo = "";
var countryjson = "getCountryListAsJSON.php";
$( "#countryInput" ).keyup(function( event ) {
fieldInput = $(this).val();
// show that something is loading
$('#actualList').html("<b>Loading response...</b>");
$.ajax({
type: 'GET',
url: countryjson,
data: fieldInput,
dataType: "json"
})
.success(function(data){
alert("success");
countrylist =data;
console.log(countrylist[1]);
$('#actualList').html(countrylist);
})
.done(function(data){
})
.fail(function() {
// just in case posting your form failed
$('#actualList').html("Failed to find countries.");
});
});
$( "#countryInput" ).focus(function() {
$("#countryInput").val("");
$("#actualInfo").html("");
$("#actualList").html("");
fieldInput="";
});
});;
the php script that was provided
<?php
// Name: getCountryListAsJSON.php
// Desc: Gets a sorted list of country names from the world DB which
// begin with the specified letters
// Params: country - beginning string of letters to match
// Outputs: JSON encoded array of country names (strings)
//get argument if provided
if(isset($_GET['country']))
$country = $_GET['country'];
else
$country = "no country specified!"; //will match nothing
//connect to database
$con = mysqli_connect("localhost", "worlddemo", "worldpass", "world")
or die("Some error occurred during connection " . mysqli_error($con));
//run query
$query = "SELECT * FROM country WHERE Name LIKE '$country%' ORDER BY name";
$results = mysqli_query($con, $query);
//build an array of strings (country names) from results
$countryList = array();
while($row = mysqli_fetch_array($results))
{
$countryList[] = htmlentities($row['Name'], ENT_COMPAT, 'UTF-8');
//note: special characters caused problems, hence htmlentities
}
//finish up
mysqli_close($con);
echo json_encode($countryList);
?>
I only get it returned as an undefined.
So I am trying to pass whatever is put in the text input to php.
For each key it is supposed to return a list of countries from a Database (hosted on my localhost xampp)
Im not sure whether its a problem with my teachers PHP or if I am just missing something in my code. I have been trying to just get it to write out in the console to see if I am getting a proper return, but the only thing that seems to be happening is it is returning undefined.
link to the world db http://downloads.mysql.com/docs/world.sql.zip
Access "getCountryListAsJSON.php" file directly from your browser (http://your-server/getCountryListAsJSON.php) and see what happens. If its all ok on the server side, you should see something like this on the page: ["country1", "country2", "country3", ... ]
Another thing you can try is change your success callback to something like this:
.success(function(data){
//alert("success");
var countrylist = data;
var html = "";
for( var i in countryList ){
html += countryList[i];
}
$('#actualList').html(html);
})
The HTML code for image file input:
<input type="file" autocomplete="off" name="background-image" accept="image/*" />
The destination div block where I want to dynamically set the background image:
<div class="clock"></div>
The jQuery function I'm currently using for setting image file uploaded as div background image:
$(".background>div>input[type=file]").change(function () {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.jpeg','.jpg', '.png', '.gif', '.bmp' formats are allowed.");
}
else {
$(".clock").css("background-image",'url("' + $(".background>div>input[type=file]").val() + '")');
}
});
The issue is that the background-image is not being set. This may possibly be because when I checked with browser inspector, the file upload is not containing file url.
Note: The background-color of .clock is set to white initially.Also I'd not like to use a server since my intention is to keep it as client side only application.
This may solve your problem
JS FIDDLE
HTML
<input type='file' id='getval' name="background-image" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
PURE JAVASCRIPT
document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
var file = document.getElementById("getval").files[0];
var reader = new FileReader();
reader.onloadend = function(){
document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
}else{
}
}
It's small way to do this without using FileReader.
http://jsfiddle.net/PuneetChawla/vqn7r0nj/
HTML
<input type='file' id='getval' name="background-image" onchange="readURL(event)" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
JavaScript
function readURL(event){
var getImagePath = URL.createObjectURL(event.target.files[0]);
$('#clock').css('background-image', 'url(' + getImagePath + ')');
}
Explanation - The URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter.
var loadFile = function(event) {
var output = document.getElementById('output');
output.style.backgroundImage= "url("+URL.createObjectURL(event.target.files[0])+")";
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="file" accept="image/*" onchange="loadFile(event)">
<div style="width: 500px;height: 500px;" id="output"></div>
</body>
</html>
I want to implement the concept site visitor can upload multiple files click on submit then compress files are upload on server xampp. I am using PHP scripting language.
You can do this in HTML5 supported browser with the help of Canvas API [for images only]. Here is a good example
http://makeitsolutions.com/labs/jic/
HTML5 canvas refrences:
http://diveintohtml5.info/canvas.html
http://www.html5canvastutorials.com/
Below is dummy code:
HTML [Check jQuery path]
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<style type="text/css">
.img_button{ height: 100%; width:100%}
.img_submit{ border: 1px saddlebrown solid; height: 30px; margin-top: 100px}
.box{ float: left; margin: 10px; width: 20%; height: 250px}
.label{ float: left; background: #333; color: #fff; width: 100%; padding-left: 10px }
img{float:left;}
</style>
</head>
<body>
<div class="box" id="box1">
<input class="filename" type="file" id="1" style="display:none" />
<input class="img_button" id="btn1" type="button" onclick="$('#1').trigger('click'); return false;" value="Image-1" />
</div>
<div class="box" id="box2">
<input class="filename" type="file" id="2" style="display:none" />
<input class="img_button" id="btn2" type="button" onclick="$('#2').trigger('click'); return false;" value="Image-2" />
</div>
<div class="box" id="box3">
<input class="filename" type="file" id="3" style="display:none" />
<input class="img_button" id="btn3" type="button" onclick="$('#3').trigger('click'); return false;" value="Image-3" />
</div>
<input class="img_submit" type="button" value="Upload" onclick="uploadFile();" />
<script type="text/javascript">
var imgCount = 1;
$('.filename').change(function(){
var file = this.files[0];
var id = this.id;
var reader = new FileReader();
reader.onload = function(event) {
var i = document.createElement('img');
i.src = event.target.result;
i.id = 'img'+id;
i.onload = function(){
image_width=$(i).width(),
image_height=$(i).height();
if(image_width > image_height){
i.style.width="320px";
}else{
i.style.height="300px";
}
//i.style.display = "block";
}
$('#img'+id).remove();
$('#box'+id).append(i);
$('#box'+id).prepend('<span class="label">'+$('#btn'+id).val()+'</span>');
$('#btn'+id).hide();
$(document).on('click', '#img'+id, function(){$('#'+id).trigger('click')});
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(file);
});
function uploadFile(){
var img_data = [];
if(imgCount){
var quality = 0.3;
for(var i=1; i<=3; i++){
if(document.getElementById('img'+i)){
var source_img_obj = document.getElementById('img'+i);
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL("image/jpeg", quality);
var img_name = $('#btn'+i).val();
img_data.push({index:i, name: img_name, image_data :newImageData});
}
}
var xhr = $.ajax({
url: 'a.php',
type: 'POST',
data: {post_data:img_data},
dataType: 'json'
});
xhr.success(function(response){
console.log(response);
});
}
}
</script>
</body>
</html>
PHP
<?php
$arr = $_POST;
if(isset($arr) && isset($arr['post_data'])){
$arrImageData = $arr['post_data'];
if(is_array($arrImageData)){
for($i=0; $i<count($arrImageData); $i++){
if($arrImageData[$i]['image_data'] != ''){
$varImageData = preg_replace('/^data:image\/(png|jpg|jpeg);base64,/', '', $arrImageData[$i]['image_data']);
$varImageData = base64_decode($varImageData);
$varImageIndex = $arrImageData[$i]['index'];
$varImageName = preg_replace('/[^a-zA-Z0-9]/', '-', $arrImageData[$i]['name']);
$varFileName = $varImageName.'-'.$varImageIndex.'.jpg';
$file = fopen($varFileName, 'wb');
fwrite($file, $varImageData);
fclose($file);
}
}
}
}
Client-side compression (before upload) can only be done via a Java Applet, as far as I know.
Server-side compression (after upload) can be done via PHP ZipArchive class. An example can be found here.
EDIT: In addition to Java Applets, client-side file compression can also be implemented in Flash or Silverlight, but if I understand correctly, this will compress data per file for quicker sending and not create a file archive.