Download a PDF file in Javascript - javascript

I'd like to download a pdf file with javascript.
The file content will be encoded in base64.
Please help me to investagate why I can't download the pdf file.
index.php:
<?php
$file_content = base64_encode(file_get_contents("1.pdf"));
?>
<!DOCTYPE>
<html>
<head>
<title>Download PDF </title>
</head>
<body>
<div>Hello World!</div>
<input type="button" onclick="download()" value="download"/>
<script>
function download() {
var str = "<?php echo $file_content;?>";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var data = window.atob(str);
var blob = new Blob([data], {type: "application/pdf"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "download.pdf";
a.click();
window.URL.revokeObjectURL(url);
}
</script>
</body>
</html>

Based on this Medium post, here's a solution that uses the base64 string directly:
function download() {
var a = document.createElement("a");
a.style = "display: none";
a.href = "data:application/pdf;base64,<?= $file_content ?>";
a.download = "download.pdf";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Further reading: Data_URIs

download attribute will help you to download the file.
var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
Another possible solution:
If you want to download it using blob content than return response must be declared as arraybuffer
Example:
$http.post('/postmethod',{params}, {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
Open the PDF file into new window from where you can save it.

Related

Javascript: How to download csv file from a url

I have a url which has csv file. i want to download that file by JavaScript. during download i will provide file name and by that name file will be download in client pc. i tried below code which is not working. where i made the mistake. please give me hint.
function downloadFile(fileName, urlData) {
var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = fileName;
aLink.href = urlData;
aLink.dispatchEvent(evt);
}
downloadFile('Test.csv', 'https://testsite.com/targeting/Export/aa.csv');
Use
aLink.click();
instead of the Dispatch-event
I found code which worked. here is the code which i am following now.
var url = 'https://testsite.com/targeting/Export/aa.csv';
var a = document.createElement("a");
a.href = url;
fileName = url.split("/").pop();
alert(fileName);
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();

PDF Blob not saving with content

I have this code:
$.post('/pdf/render', params, function (data) {
var blob = new Blob([data], {type: 'application/pdf'});
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "results.pdf";
document.body.appendChild(a);
a.click();
}):
Once my PDF downloads, the clicked URL and blob saves my PDF with the correcct number of pages, but there is nothing in the PDF. Am I doing something wrong with my blob? Why would there be no content when I am getting the content from the backend?
For clairfication, I checked with cURL and got a proper PDF with content.

how to generate html and css file dynamically using javascript for download by the user from string?

I have a css code and html code in a string and want to create a .html and .css file for download. Is it actually possible?
I've used this example but it prints all code exactly as string and not as real css/html code
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
http://jsfiddle.net/koldev/cW7W5/
Wow ok, I found the solution. Just remove first and last quotations. tada...
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var parsed = data.replace(/^['"].*['"]+/g, ''),
blob = new Blob([parsed], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
http://jsfiddle.net/cW7W5/1356/

Read data from BLOB URL in Javascript

I have a BLOB URL, and I want to recreate it as a second BLOB URL, so that it is downloaded by default.
var blob1 = new Blob(["Hello world!"], { type: "text/plain" });
url1 = window.URL.createObjectURL(blob1);
blob2=new Blob([url1], {type: 'application/octet-stream'});
url2 = window.URL.createObjectURL(blob2);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url2;
a.click();
window.URL.revokeObjectURL(url);
See in JSFiddle:
https://jsfiddle.net/7spry3jn/
But this only creates a text file containint the first URL. How can I Read data from the first BLOB URL in Javascript and feed it to create the second BLOB?
You can use the download attr in anchor element, that force the download and you dont need to reate another blob.
But you need to pay attentio about browser support, see here all the browsers that accept the downloadattr: Can I Use
var blob1 = new Blob(["Hello world!"], { type: "text/plain" });
url = window.URL.createObjectURL(blob1);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.setAttribute("download","Any name");
a.click();
window.URL.revokeObjectURL(url);
And to read the content from a Blob you can use FileReader like this:
var myBlob = new Blob(["Hello"], {type : "text/plain"});
var myReader = new FileReader();
//handler executed once reading(blob content referenced to a variable) from blob is finished.
myReader.addEventListener("loadend", function(e){
document.getElementById("text").innerHTML = e.srcElement.result;//prints a string
});
//start the reading process.
myReader.readAsText(myBlob);
<p id="text"></p>

Download the source code in html of a form generated with angularjs

Is it possible by angularjs download a piece of code generated by a form?
Add a simple code:
http://jsbin.com/nufixiwali/edit?html,js,output
I would generate an .html to download only the code generated after the html tag.
Thank you
something like
function downloadAsFile(filename, type, data) {
window.URL = window.URL || window.webkitURL;
var a = document.createElement("a");
var blob = new Blob([data], {type: type});
var url = window.URL.createObjectURL(blob);
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
downloadAsFile('myfile.html', 'text/html', myData)

Categories

Resources