Skip to content

Instantly share code, notes, and snippets.

@vijaydeepak-tt
Last active March 17, 2020 09:59
Show Gist options
  • Save vijaydeepak-tt/bb7853d9bd8ff83119349d49ade1e1b5 to your computer and use it in GitHub Desktop.
Save vijaydeepak-tt/bb7853d9bd8ff83119349d49ade1e1b5 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
</head>
<body>
<form>
<input type="file" name="" id="file-input" /><br /><br />
<button id="download">Download</button>
</form>
<script>
var data = "";
document.getElementById("file-input").addEventListener(
"change",
event => {
fileToBase64(event).then(result => {
const txt = result.split(",")[1];
data = atob(txt);
});
},
false
);
// Convert file to base64 string
function fileToBase64(evt) {
return new Promise(resolve => {
var file = evt.target.files[0];
var reader = new FileReader();
// Read file content on file loaded event
reader.onload = function(event) {
resolve(event.target.result);
};
// Convert data to base64
reader.readAsDataURL(file);
});
}
document.getElementById("download").addEventListener("click", () => {
download("text.doc", data);
// var doc = new jsPDF()
// doc.text(data, 10, 10);
// doc.save('a4.doc');
});
function download(filename, text) {
var element = document.createElement("a");
element.setAttribute(
"href",
"data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
element.setAttribute("download", filename);
element.style.display = "none";
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// use this function for all file extensions
function download(name, content) {
var link = document.createElement("a");
link.style = "position: fixed; left -10000px;";
link.href = `data:application/octet-stream;base64,${encodeURIComponent(
content
)}`;
link.download = name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment