How to Print the html output into Pdf using javascript - javascript

Here is my output image
Here is my code
let input = document.querySelector('input');
var textarea = document.getElementsByClassName('area')[0];
var txtreplace = document.getElementsByClassName('demo')[0];
window.addEventListener('load',
function () {
input.addEventListener('change', () => {
let files = input.files;
if (files.length == 0) return;
const file = files[0];
let reader = new FileReader();
const fruits = [];
reader.onload = (e) => {
const file = e.target.result;
const lines = file.split(/\r\n|\n/);
//console.log(lines.length);
textarea.value = lines.join('\n');
lines.forEach(function (arrayItem) {
//console.log(arrayItem.replace("\u001bE", ""));
var arr1 = arrayItem.replace("\u001bE", "");
var arr2 = arr1.replace("\u001bF", "");
fruits.push(arr2);
});
console.log(fruits.length);
if (parseInt(fruits.length) > 0) {
console.log(fruits);
txtreplace.innerHTML = fruits;
}
};
reader.onerror = (e) => alert(e.target.error.name);
reader.readAsText(file);
});
}, false);
function printDiv() {
var divContents = document.getElementsByClassName("demo").innerHTML;
var a = window.open('', '', 'height=500, width=500');
a.document.write('<html>');
a.document.write('<body > <h1>Print PDF <br>');
a.document.write(divContents);
a.document.write('</body></html>');
a.document.close();
a.print();
}
</script> </body>

You can take a look at https://github.com/parallax/jsPDF.
It's js library allow you to build pdf using Javascript.
Otherwise have some solutions to convert html page to pdf ( https://www.html2pdf.co.uk/ ), but I don't think it's what you are looking for.
Exemple of code using JSPDF :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.save('Test.pdf');
Hope it will helps you ;)

Related

How to Replace multiple strings using arrayItem in JAVASCRIPT

Here is my output
Here is my code, here i am changing arrayItem.replace("\u001bE", "") my problem is i want to change for another string also "\x1B-1" --> how to declare this in my code replacing multiple strings at a time.
const file = files[0];
let reader = new FileReader();
const fruits = [];
reader.onload = (e) => {
const file = e.target.result;
const lines = file.split(/\r\n|\n/);
//console.log(lines.length);
textarea.value = lines.join('\n');
lines.forEach(function (arrayItem) {
//console.log(arrayItem.replace("\u001bE", "<b>"));
var arr1 = arrayItem.replace("\u001bE", "<b>");
var arr2 = arr1.replace("\u001bF", "</b>");
fruits.push(arr2);
});
console.log(fruits.length);
if (parseInt(fruits.length) > 0) {
console.log(fruits);
txtreplace.innerHTML = fruits;
}
};
reader.onerror = (e) => alert(e.target.error.name);
reader.readAsText(file);
});
}, false);
Not sure if this is what you're asking but you can chain multiple calls to replace like this:
var arr1 = arrayItem.replace("\u001bE", "<b>").replace("\x1B-1", "<something>");

How to read first line of a file in JavaScript

In JavaSctipt the FileReader object doesn't seem to have support for just reading the first line of a file. (up to the CR '\n'). I dont want to read in the whole file to save memory.
Is there a way to do it?
My code (note that readLine() function does not exists):
self.loadFirstLineFromFile = function (options, callback) {
var hiddenElement = document.createElement('input');
hiddenElement.id = 'hidden-tsv-file-loader';
hiddenElement.type = 'file';
hiddenElement.accept = options.extension;
hiddenElement.style.display = 'none';
hiddenElement.addEventListener('change', function (event) {
var file = event.target.files[0];
var reader = new FileReader(file);
var firstLine;
firstLine = reader.readLine();
callback(firstLine);
});
document.body.appendChild(hiddenElement);
hiddenElement.click();
};
There's nothing builtin for that, but it's simple to implement:
var file = event.target.files[0];
var sliced = file.slice(0, 2048); // Pick a size that you're ok with
// NOTE: `await` keyword requires transpiling (Babel) for IE11,
// and to be inside an async function. An alternative is:
// sliced.text().then(function(text) { console.log(text); });
var text = await sliced.text();
console.log(text);
Here's an interface that reads the data from the Blob decoded as text and chunked by a delimiter:
async function* readLines (blob, encoding = 'utf-8', delimiter = /\r?\n/g) {
const reader = blob.stream().getReader();
const decoder = new TextDecoder(encoding);
try {
let text = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
text += decoder.decode(value, { stream: true });
const lines = text.split(delimiter);
text = lines.pop();
yield* lines;
}
yield text;
} finally {
reader.cancel();
}
}
We can use this to read a single line and discard the rest without reading the entire file:
hiddenElement.addEventListener('change', async function (event) {
const file = event.target.files[0];
for await (const line of readLines(file, 'utf-8', '\n')) {
callback(line);
return; // signals reader.cancel() to the async iterator
}
});
Since I use Javascript with Knockout I refactored Patricks solution into this:
self.loadStream = function (options, callback) {
var hiddenElement = document.createElement('input');
hiddenElement.id = 'hidden-tsv-file-loader';
hiddenElement.type = 'file';
hiddenElement.accept = options.extension;
hiddenElement.style.display = 'none';
hiddenElement.addEventListener('change', function (event) {
var file = event.target.files[0];
var reader = file.stream().getReader();
var decoder = new TextDecoder('utf-8');
var data;
var readNextChunk = function () {
data = reader.read();
data.then(function (result) {
if (!result.value) {
callback({ chunk: '', done: true, shouldStop: true }, file);
} else {
var chunk = decoder.decode(result.value, { stream: true });
var args = {
chunk: chunk,
done: result.done,
shouldStop: true
};
callback(args, file);
if (!result.done && !args.shouldStop) {
readNextChunk();
}
}
});
};
readNextChunk();
hiddenElement.remove();
});
document.body.appendChild(hiddenElement);
hiddenElement.click();
};

tf.browser.fromPixels returns all zeros from img element

I am using tensorflowjs to do some front-end image classification. I am trying to use tf.browser.fromPixels to convert an img element to a tensor. However, I am getting all zeros of shape [160, 160, 3]. I am using the FileReader api to read an image from the file system via the <input type="file"> element. Here's some of the code:
function getFiles(event) {
const files = event.target.files;
let tempStore = [];
for (let i = 0; i < files.length; ++i) {
tempStore.push(files[i]);
}
return tempStore;
}
const imageElement = document.getElementById("upload");
imageElement.addEventListener("change", event => {
const files = getFiles(event);
Promise.all(files.map(loadImg)).then(d => {
console.log("All done !!!", d);
});
});
const loadImg = imgFile => {
return new Promise((resolve, reject) => {
let reader = new FileReader();
let imgEl = document.createElement("img");
reader.onload = async e => {
imgEl.src = e.target.result;
imgEl.setAttribute("width", 160);
imgEl.setAttribute("height", 160);
document.body.append(imgEl);
const fromPixels = tf.browser.fromPixels(imgEl);
resolve(fromPixels);
};
reader.onerror = reject;
reader.readAsDataURL(imgFile);
});
};
The image gets appended to document body properly.
The imageElement is of the form:
<img src="data:image/jpeg;base64,....." width=160 height=160>
You are creating the tensor from the image when the img tag has not yet been loaded. Here is the way to go
imgEl.src = e.target.result;
imgEl.setAttribute("width", 160);
imgEl.setAttribute("height", 160);
document.body.append(imgEl);
im.onload = () => {
// create the tensor after the image has loaded
const fromPixels = tf.browser.fromPixels(imgEl);
resolve(fromPixels);
}

Load file and parse document

I have a code for displaying whole document in a HTML
<!DOCTYPE HTML>
<html>
<head>
<script>
let openFile = function(event) {
let input = event.target;
let reader = new FileReader();
reader.onload = function(){
let text = reader.result;
let node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0, 200));
};
reader.readAsText(input.files[0]);
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
</div>
</body>
</html>
I need to load a document then display only strings I need - names and url like:
Document example:
#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com
Display:
<a href=http://elis.com>Elis</a>
<a href=http://emma.com>Emma</a>
let openFile = function(event) {
let input = event.target;
let reader = new FileReader();
reader.onload = function() {
let text = reader.result;
let node = document.getElementById('output');
// node.innerText = text;
var resultText = "";
lines = reader.result.split(/\r\n|\r|\n/);
for (let i = 0; i < lines.length - 1; i += 2) {
var matches = lines[i].match(/\#NAME:([^:]+)/);
resultText += `${matches[1].trim()}\n`;
}
// innerText here only for demonstration purpose
// use innerHTML for working code instead
node.innerText = resultText;
// node.innerHTML = resultText
};
reader.readAsText(input.files[0]);
};
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
var str = `#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com`;
const makeUpHrefs = str => {
let arr = str.split(/\n#/);
arr = arr.map(row => '' + row.match(/NAME:(.*?):/)[1] + '');
return arr;
};
So, makeUpHrefs(str) will return array of html's:
Elis
Emma

Word count with javascript

I want to count words from below file types..
['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']/
currently my code reads text files only..
please help me for other file types..
Below is my code..
<script>
$('#file').change( function(event) {
var imgpath=document.getElementById('file');
if (!imgpath.value==""){
var ext = imgpath.value.split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']) != -1) {
var f = event.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var strings = "";
var contents = e.target.result; alert(contents);
var words = contents.match(/\S+/g).length;
$('#display_file_count').text(words);
}
r.readAsText(f);
}
}else{
alert('file type not supported.');
$('#file').val('');
}
}
});
</script>

Categories