How i can convert to excel an object `HTMLImageElement` - javascript

I have a problem, i want to export in excel my chart,but when i convert my chart as an object HTMLImageElement and I apply
document.body.appendChild(newImg);
I use the asp classic function:
<%
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition","filename=""ExcelExport.xls"""
%>
the exel file don't convert the new img.how i can see the new img in the excel file?can i use another type of conversion for the excel file, or i must convert the HTMLImageElement before?
Here's the .css and .js files:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.14.0/js/canvas-to-blob.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8 /FileSaver.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="utils.js"></script> <!--function for chart creation/mod-->
<style>
</style>
Html and javascript function
<prova></prova>
<button id="myButtonControlID"></button>
<div id="divTableDataHolder">
<div id="pagina">
<div style="width:75%;">`enter code here`
<canvas id="canvas"></canvas>
</div>
<img id"image">
<button id="Aimg">Aggiorna IMG</button>
</div>
</div>
<script>
//***************************************insert the chart creation here**************************************
$(function() {
setTimeout(assignSampleClick, 500);
});
function assignSampleClick () {
canvas.toBlob(function(blob) {
var newImg = document.createElement('img'),
url = URL.createObjectURL(blob);
newImg.onload = function() {
// no longer need to read the blob so it's revoked
// document.querySelector("#image").src = url;
URL.revokeObjectURL(url);
};
newImg.src = url;
document.body.appendChild(newImg);
alert(newImg)
// document.getElementsByTagName('prova')[0].innerHTML =url;
},'image/gif');
};
$("#Aimg").click(function() {
canvas.toBlob(function(blob) {
var newImg = document.createElement('img'),
url = URL.createObjectURL(blob);
newImg.onload = function() {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
alert(url)
newImg.src = url;
document.body.appendChild(newImg);
//document.getElementsByTagName('body')[0].innerHTML ="funziona?BOH SEMBRA DI SI";
},'image/gif');
});
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
$("[id$=myButtonControlID]").click(function(e) {
window.open('data:application/vnd.ms-excel,' + encodeURIComponent( $('div[id$=divTableDataHolder]').html()));
e.preventDefault(); //this is another type of conversion
});
</script>
Asp code to convert all html
<% Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "ContentDisposition", "filename=""ExcelExport.xls"""%>

When you say you "use the asp classic function" what you are really doing is sending the generated HTML to the client with a "non-standard" content type and disposition header. When I say non-standard I mean not the standard header for HTML output - these are the headers used when downloading a bona-fide Excel version 97-2003 binary format file. Most browsers will pass that file straight through to the Excel application; it just so happens Excel is lenient with HTML files that have an Excel extension on them and will attempt to parse them into a worksheet format.
To get more functionality you'd need to use a fully-featured library for Excel file generation, like ExcelJS - I do not know if it supports images, though.

look these page for datatable export
https://datatables.net/extensions/buttons/examples/initialisation/export.html

Related

Getting text from file using FileReader on Load

So, I've been working on a page that uses only local files (server is not an option, unfortunately. Not even a localhost. The struggle is real.) and I've come to a situation where I need to grab text from a .csv file and populate it to the page. I have this bit of code that works, but I need to have a file set within the function when a button is pressed. Looking up the file manually isn't an option (to visualize what I'm doing, I'm making a mock database file in the most annoying way possible (because I have to, not because I want to)).
In the page I would have something like:
<button id="myButton" onclick="getText()"></button>
<script>
var myFile = "dataset.csv";
...
</script>
The following bit of code works (in regards to having it pull the data from the csv file), but, as I said, I need to pull the text from the file when a button is pressed and just have the file name set in the script, not pulling it up manually.
<!DOCTYPE html>
<html>
<body>
<input type="file" id="fileinput" />
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
From what I can tell from the API, I would need to set the file attributes to a blob in order to pass it to FileReader. How I can do this without using an input box, I have no idea. There's also a 50% chance that I am completely wrong about this since I obviously don't know how to get this done.
If someone could show me how to achieve this with regards to what I'm looking for, it would be very much appreciated. I'm absolutely stumped.
Thank you.
Note: CORS restrictons will prevent this from working in most browsers. You can use FireFox Developer Edition, which disables CORS validation.
You can use an XMLHttpRequest to load a local file:
<!DOCTYPE html>
<html>
<body>
<button onclick="readSingleFile()">Click Me</button>
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile() {
let xhr = new XMLHttpRequest();
let url = "relative/path/to/file.txt;
if (!url) return;
xhr.onload = dataLoaded;
xhr.onerror = _ => "There was an error loading the file.";
xhr.overrideMimeType("text/plain");
xhr.open("GET",url);
xhr.send();
}
function dataLoaded(e){
var contents = e.target.responseText;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
</script>
</body>
</html>

How to resize an image on preview (no database)

I have script to preview input type=file (image), and generate it into pdf.
There's no problem for a small size of image. Then when i input with size 6Mb, the preview is OK, but when generate to pdf, its take very long time and finally stopped.
So, I want to resize the image size to 200x240px. But i don't know how to do it, because the script using javascript and I still newbie on it.
Please help how to resize it on my script.
Script:
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
//preview.src = reader.result;
$('#gen-template-frame').contents().find('.logo img').attr('src', reader.result);
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
HTML:
<!doctype html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/magang/front.css">
</head>
<body>
<div class="corpname" contenteditable>RUMAH SAKIT HARUM</div>
<div class="logosisma"><img src="https://sismadigroup.com/idcard/images/background/logo-id-card.png" width="219" height="70" /></div>
<div class="logo">
<!--<img src="resize/resize.php?src=https://sismadigroup.com/idcard/templates/images/avatar/3.jpg&scale=10&q=100">-->
<img src="https://sismadigroup.com/idcard/templates/images/avatar/3.jpg" width="200" height="240" />
</div>
<div class="name highlight" contenteditable>Maesyaroh</div>
<div class="position" contenteditable>Siswa Magang</div>
<div class="nik" contenteditable>SM-0035</div>
<div class="BBP">BENAR BAIK PANTAS</div>
<div class="BBPPoint" style="left:135px;"> . </div>
<div class="BBPPoint" style="left:203px;"> . </div>
</body>
</html>
Edit: PHP for PDF generation:
$frontPage = resolveDependency(stripslashes( $_POST[ "html" ] ));
$backPage = resolveDependency(stripslashes( $_POST[ "html2" ]) );
$frontPageCSS = getCSSFromHTML($frontPage);
$backPageCSS = getCSSFromHTML($backPage);
$mpdf = new mPDF('utf-8', array(75, 114.6), 0, '', 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($frontPageCSS, 1);
$mpdf->WriteHTML($frontPage, 0);
$mpdf->WriteHTML('<pagebreak>', 2);
$mpdf->WriteHTML($backPageCSS, 1);
$mpdf->WriteHTML($backPage, 0);
$mpdf->Output('card.pdf', 'I');
Since you are using PHP to generate the PDF you can resize the image with PHP before using it with mPDF. I don't see in your code how you load the image, so I suppose that you use the Image() function for loading the image from a file (in this example $fileName is the name of the input image, replace it with the variable that you use in your code):
// $fileName is the name of the input image
list($width,$height)=getimagesize($fileName); // size of input image
$tempFileName=tempnam(sys_get_temp_dir(),"img").".png";
$newWidth=200;
$newHeight=240;
$image=imagecreatefrompng($fileName); // load the input image
$newImage=imagecreatetruecolor($newWidth,$newHeight); //create an empty image
imagecopyresampled($newImage,$image,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagepng($newImage,$tempFileName,9); // saving the new image to disk
// here you create the PDF using the image saved in $tempFileName
unlink($tempFileName); // and finally we delete the temporal file
I solved the same problem on front-end, before uploading file. You can visit a link!
import imageSqResizer from './image-square-resizer.js'
let resizer = new imageSqResizer(
'image-input',
300,
(dataUrl) =>
document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);
//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;

Using blobs to store images as files via Javascript

I'm working on this project and ran into some complications using AWS S3 to host images. So I pivoted and decided to store the image as a Blob and let Javascript do the work of transforming the file into and out of the Blob, so I could then use AJAX and the API to store it in our DB. While this might be less than ideal, I'm still learning Javascript and hadn't worked with blobs a lot so I figured why not, time to learn.
My issue is that when I try to use a DataURI to show the image on the page it comes out as a string and not a DataURI, and therefore loads as a broken image. I haven't worked in ajax yet because I thought it better to take the image, turn it into an ascii string, put it in a blob, then get it back out before involving the API/server. Here is my html:
{% extends 'mp_app/base.html' %}
{% load staticfiles %}
{% block content %}
<div id="page-wrapper">
<pre id="fileDisplayArea"></pre>
<form id="picForm" method='post'>
{% csrf_token %}
<input type="file" id='imgFile' name="pic" accept="image/*">
<input type="submit" id='submitBtn'>
<input type="submit" id="showBtn">
</form>
<div id="imageDisplay"></div>
</div>
{% endblock %}
{% block javascript %}
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript" src="{% static 'js/blob.js' %}"></script>
{% endblock %}
and my Javascript
//js file to turn an image into a blob, then store the blob in our API.
// next: retrive the blob and put it on the page
function textToImg(text) {
//get ascii string into binary then into an array then into a blob.
//had some strange issues using ArrayBuffer()
var file = new
Array(atob(document.getElementById('fileDisplayArea').innerText));
file = new Blob(file, {type:'image/*'});
let displayArea = document.getElementById('imageDisplay')
//currently doesn't seem to be loading as a DataURL. It's type is string and
//shows up as a broken image.
var reader = new FileReader();
reader.onload = function(event) {
var content = event.target.result;
img = new Image();
img.src = content;
displayArea.append(img)
console.log(img);
}
reader.onerror = function(event) {
console.error('error, file could not be read: ' +
event.target.error.code);;
}
reader.readAsDataURL(file);
// TODO get data via ajax to our DB our restful API
}
//turns an image into a blob
function imgToText() {
// get file elem and get image
let file = document.getElementById('imgFile');
let img = document.getElementById('imgFile').files[0];
let displayArea = document.getElementById('fileDisplayArea');
//open a file reader and read in file, then turn it from binary to ascii
var reader = new FileReader();
reader.onload = function(event) {
let contents = event.target.result;
//turn to ascii string
let asciiContents = btoa(contents);
//add ascii string to form
let form = {
'file': asciiContents,
}
displayArea.append(form.file);
};
reader.onerror = function(event) {
console.error('error, file could not be read');
}
//read file as a bit string
reader.readAsBinaryString(img);
// TODO send data via ajax to our DB our restful API
};
//add click event so that image is processed upon submit
$('#submitBtn').click(function(event) {
event.preventDefault();
imgToText();
});
$('#showBtn').click(function(event) {
event.preventDefault();
textToImg();
})
The img src reads as the blob string makes me think the something is wrong with the DataURI, perhaps it isn't getting the file in the proper format. I couldn't post a screen shot because I need a better reputation. Sorry this is so verbose but I wanted to try and make a quality post. Thank you!
I solved the issue. Will post here for future learners who may need this option.
textToImg() already has the string it needs, so all you need to do is get the string, add it to the file input element, (I added it as a 'value' attr), then let image.src = 'data:image/*;base64, + value attr. And you're good to go.

File reader Javascript

currently i am choosing a file and converting to base64 string and displaying in html page.see the below code.
But i want in such a way that while loading the function it will automatically fetch the file from the location where the image saved and convert to base64 and display. I just want to skip the manual way of choosing..please help
<html>
<body>
Choose File: <input id="imageToLoad" type="file" onchange="displayImage();" />
<p>Image encoded</p>
<textarea id="base64TextArea" style="width:550;height:240" ></textarea>
<img id="myImg" width="218" height="300" src="" />
<script type="text/javascript">
function displayImage()
{
var filesSelected = document.getElementById("imageToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
base64TextArea.innerHTML = fileLoadedEvent.target.result;
document.getElementById("myImg").src = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
</body>
</html>
You can't fetch arbitrary files on a client's computer with JS. Using most browsers, the client must manually choose a file to be processed by the script.
If you think about it, it would be a major security flaw if any website could access any file on your computer.
I'm not sure why Base64 is an important aspect here. Please give some details if converting the image to text is a specific requirement of your needs, but if you only want to display and reference the image, you can start with this:
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
document.getElementById("myImg").src = URL.createObjectURL(fileToLoad);
}
This will use an "object URL" which is a shorthand way of referring to a file that has been drag/dropped, or picked from an <input>

To display text from a txt file using javascript

How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "#":
output=output.split("\n").filter(/./.test, /\#/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\#/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\#/.test(l); // Starting with #
return l.indexOf('#') > -1; // Containing #
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\#/.test.bind(/\#/)).join("\n");
The second arguments passed to the .filter method is the context:
array.filter(callback[, thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\#/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Demo

Categories