I have been hunting around on these forums to find some code which can download the HTML page AS IS (i.e. with added elements from other buttons, and essentially everything within my div's) so that it can be picked up another time with the data still there. I cannot for the life of me find anything which just downloads the page. Below is the closest I came to actually saving a html document at all, and even that (obviously) only displays the text written. Could I edit this to make it encapsulate the entire page?
With very little experience I can only apologize.
function save() {
var anchor = document.querySelectory('button');
anchor.setAttribute('download', 'index.html');
anchor.setAttribute('href', 'data:text/html;charset=UTF-8,<p>asdf</p>')
}
One solution is FileSaver.js
Follow the example on that page, and use document.innerHTML for your blob (what I've used) Actually, I forget if that excludes the header. If so, there's a solution I found to this (also on StackOverflow) but I don't have the code here locally to look at how I got around this (if I did, indeed, have to get around this)
You can try this
download html content
<script>
function myFunction() {
var content = document.documentElement.innerHTML;
download(content, "index", "txt")
}
function download(content, fileName, fileType) {
var link = document.getElementById("donwload-link");
var file = new Blob([content], {type: fileType});
var donwloadFile = fileName + "." + fileType;
link.href = URL.createObjectURL(file);
link.download = donwloadFile
}
</script>
https://jsfiddle.net/a9oLw1zv/13/
Related
As per the Chrome version >=60 the PDF view functionality by any top-frame navigations options like
<A HREF=”data:…”>
window.open(“data:…”)
window.location = “data:…”
has been blocked by Google for which the discussion can be found at Google Groups. Now the problem is how to display the PDF on web without explicitly or forcibly making PDF to download. My old code looked as below via window.open to view the PDF data
dataFactory.getPDFData(id, authToken)
.then(function(res) {
window.open("data:application/pdf," + escape(res.data));
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
In above I extract the PDF data from server and display it. But since window.open is blocked by Chrome and as suggested by one of the expert over here to use <iframe> to open the PDF data and I tried but it's not working. It always says Failed to Load PDF Data as below
The updated JS code for the <iframe> looks as below:
dataFactory.getPDFData(id, authToken)
.then(function(res) {
$scope.pdfData = res.data;
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
And the HTML looks as below:
<iframe src="data:application/pdf;base64,pdfData" height="100%" width="100%"></iframe>
How can I proceed and bring back the original PDF view functionality? I searched over other stack questions but out of luck on how to resolve this. May be I did something wrong or missed something with the iframe code but it's not working out.
After unable to find the desired result I came up with below approach to resolve the issue.
Instead of opening the PDF on new page what I did is as soon as user clicks on the Print button PDF file gets downloaded automatically. Below is the source for same.
//File Name
var fileName = "Some File Name Here";
var binaryData = [];
binaryData.push(serverResponse.data); //Normal pdf binary data won't work so needs to push under an array
//To convert the PDF binary data to file so that it gets downloaded
var file = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var fileURL = document.createElement("fileURL");
fileURL.href = file;
fileURL.download = serverResponse.name || fileName;
document.body.appendChild(fileURL);
fileURL.click();
//To remove the inserted element
window.onfocus = function () {
document.body.removeChild(fileURL)
}
In your old code :
"data:application/pdf," + escape(res.data)
In the new :
your iframe src is like "data:application/pdf;base64,pdfData"
Try to remove base64 from the src, it seems to be already present in the value of 'pdfdata'.
I'm trying to dynamically generate an anchor for a given content (documents and/or images stored on Cloudinary.io, in this case), but the documents I'm storing have a hash value rather than a filename (i.e.: c9eed62bd1534c382a3b89241b24b1ddd17b3793 instead of sample.pdf).
Here's the function I'm using to generate the anchor:
function download(url, download) {
if (url) {
var a = document.createElement('a');
if (a) {
a.href = url;
a.download = download || '';
a.target = '_blank';
a.click();
}
}
}
The problem I have is, when I execute the function, the browser downloads the file for me, but with the name in the href attribute rather than the download attribute.
This is the event I use to fire the download:
$('.link').on('click', function (e) {
download($(this).data('url'), $(this).data('name'));
});
And this is a sample HTML element containing the data to trigger the event:
<span class="link" data-url="http://res.cloudinary.com/dxsky7h00/raw/upload/v1483364241/627ec3e4afa08749ac4aff8d2917a38f586a5790" data-name="fs545554545454.xls"><i class="icon-file-o"></i>fs545554545454</span>
Maybe I understood the download attribute for the <a> element in a wrong way, but I thought, when specified, it forces the browser to download the resource rather than trying to open it on one hand and, on the other hand, if download="something" is used, the resource will be downloaded with the name being 'something' rather than what's in the href attribute.
What am I missing for this sample function to work?
EDIT I'm currently testing this on Chrome 55.0.2883.87 (64-bit), but as this entry on caniuse.com states, it's compatible
#tsh asked the right question. The problem lies in the fact the href attribute references an external resource, hence we're dealing with a cross-origin reference and the browser won't let me download it with another name.
I tested it with a local file and it worked, so the problem lies within my implementation. Thanks to all anyway :)
I need help. I have an angular app and by using DocRaptor want to generate PDF and save it as file. But I cant trigger the dialog to save file in Safari with any method what I have found on Stack Overflow. Those methods open file in current browser tab and replace site html or open file in new tab. No one cant shows the dialog. Here the examples what I have already tried to use. Environment MacOS - EL Capitan. Safari 9.0.3
Solution #1
var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
Example jsfiddle. Shows file in current tab. Replaces site. But works in Chrome.
Solution #2
<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Solution #3
<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>
and
$scope.saveJSON = function () {
$scope.toJSON = '';
$scope.toJSON = angular.toJson($scope.data);
var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',window.URL.createObjectURL(blob));
downloadLink.attr('download', 'fileName.json');
downloadLink[0].click();
};
Example Code Snippet. Shows the file content instead of document's html.
Solution #4
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
Example Code Snippet. Replace document with file content in Safari. Works in Chrome.
And similar Solution #5
function download(text, name, type) {
var a = document.createElement("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Also I have tried to use libraries like:
FileSaver - It opens file in Safari instead of document. So you should click Cmd+S. Example.
If we use type 'pplication/octet-stream' the name of file will be unknown or there was be an error 'Failed to load resource: Frame load interrupted'. Issue.
Second library Downloadify - doesnt work in Safari at all. Issue.
Angular library nw-fileDialog - instead of save as it shows choose file. Issue.
DocRaptor has own example with jQuery.
Example with angular in jsfiddle. It works in Chrome but in Safari example doesnt work be cause of error with SAMEORIGIN
Refused to display 'https://docraptor.com/docs' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
But if we reproduce it on server and change url on 'https://docraptor.com/docs.pdf' it works and open file in new tab and automatically download the file so you cant choose a folder and after download user see white empty screen tab in browser. If we specify form target="_self" it will work perfect, but console will have an error 'Failed to load resource:'.
I will appreciate any help with this problem.
Thanks.
Regards.
Try using Blob file for this:
// Buffer can be response from XMLHttpRequest/Ajax or your custom Int32 data
function download(buffer, filename) {
var file = new Blob([buffer], {
type: 'application/octet-stream' // Replace your mimeType if known
});
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var converted = e.target.result;
converted.name = filename;
converted.webkitRelativePath = filename;
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = converted;
};
fileReader.onerror = function(e) {
throw new Error('Something is wrong with buffer data');
};
fileReader.file = file;
fileReader.readAsDataURL(file);
}
It basically uses filebuffer and download that as an iframe content. Make sure to hook correct mime type so that safari security system will recieved analyse filetype.
Ideally, Solution #2 would be the answer, but the download attribute does not yet have cross-browser support.
So you have to use a <form> to create the download. As you noted, DocRaptor's jQuery example uses this technique.
The SAMEORIGIN error is actually because JSFiddle is running the code in an iFrame with their origin settings. If you run this straight from your Angular application, you shouldn't have any problems.
First of all let me clarify that what I'm trying to do is for locally use only, users will have direct access to the html page.
What I'm trying to do is basically append and save text to an HTML file.
This is what I have.
HTML (index.html)
<div id="receiver"></div>
<button id="insertButton">Insert</button>
JS
$(document).ready( function() {
$('#insertButton').click(function(){
$('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');
})
});
What I don't know is how to save the file (index.html) after the appending. Any idea how to do that? Is this even possible with Javascript or jQuery?
You could change your handler to do this:
$(document).ready( function() {
$('#insertButton').click(function(){
$('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');
// Save the page's HTML to a file that is automatically downloaded.
// We make a Blob that contains the data to download.
var file = new window.Blob([document.documentElement.innerHTML], { type: "text/html" });
var URL = window.webkitURL || window.URL;
// This is the URL that will download the data.
var downloadUrl = URL.createObjectURL(file);
var a = document.createElement("a");
// This sets the file name.
a.download = "source.htm";
a.href = downloadUrl;
// Actually perform the download.
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
});
You should take a look at the compatibility matrix and documentation of URL over at MDN. Notably URL is not available for IE 9 or earlier. Same for Blob.
If I understand it correctly, you need it on local machine and for temporary usage then you can store it in cookies.
So whenever you load the page, check if cookie available, if yes then load data from cookies or load the fresh data.
You can use this data, unless and until cookies are not cleared.
Hope this helps...
Don't need any javascript. After the html is appended, just press Ctrl+S to save the file locally with modified html.
This question already has answers here:
How to create a file in memory for user to download, but not through server?
(22 answers)
Closed 6 years ago.
Typically, HTML pages can have link to documents (PDF, etc...) which can be downloaded from the server.
Assuming a Javascript enabled webpage, is it possible to dynamically create a text document (for example) from within the user browser and add a link to download this document without a round trip to the server (or a minimal one)?
In other word, the user would click on a button, the javascript would generate randoms numbers (for example), and put them in a structure. Then, the javascript (JQuery for example) would add a link to the page to download the result as a text file from the structure.
This objective is to keep all (or at least most) of the workload on the user side.
Is this feasible, if yes how?
Here's a solution I've created, that allows you to create and download a file in a single click:
<html>
<body>
<button onclick='download_file("my_file.txt", dynamic_text())'>Download</button>
<script>
function dynamic_text() {
return "create your dynamic text here";
}
function download_file(name, contents, mime_type) {
mime_type = mime_type || "text/plain";
var blob = new Blob([contents], {type: mime_type});
var dlink = document.createElement('a');
dlink.download = name;
dlink.href = window.URL.createObjectURL(blob);
dlink.onclick = function(e) {
// revokeObjectURL needs a delay to work properly
var that = this;
setTimeout(function() {
window.URL.revokeObjectURL(that.href);
}, 1500);
};
dlink.click();
dlink.remove();
}
</script>
</body>
</html>
I created this by adapting the code from this HTML5 demo and messing around with things until it worked, so I'm sure there are problems with it (please comment or edit if you have improvements!) but it's a working, single-click solution.
(at least, it works for me on the latest version of Chrome in Windows 7)
By appending a data URI to the page, you can embed a document within the page that can be downloaded. The data portion of the string can be dynamically concatenated using Javascript. You can choose to format it as a URL encoded string or as base64 encoded. When it is base64 encoded, the browser will download the contents as a file. You will have to add a script or jQuery plugin to do the encoding. Here is an example with static data:
jQuery('body').prepend(jQuery('<a/>').attr('href','data:text/octet-stream;base64,SGVsbG8gV29ybGQh').text('Click to download'))
A PDF file? No. A txt file. Yes. With the recent HTML5 blob URIs. A very basic form of your code would look something like this:
window.URL = window.webkitURL || window.URL;
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
var file = new window.BlobBuilder(),
number = Math.random().toString(); //In the append method next, it has to be a string
file.append(number); //Your random number is put in the file
var a = document.createElement('a');
a.href = window.URL.createObjectURL(file.getBlob('text/plain'));
a.download = 'filename.txt';
a.textContent = 'Download file!';
document.body.appendChild(a);
You can use the other methods mentioned in the other answers as a fallback, perhaps, since BlobBuilder probably isn't supported very well.
Demo
Note: BlobBuilder seems to be deprecated. Refer to this answer to see how to use Blob instead of BlobBuilder. Thanks to #limonte for the heads up.