For a project I need to save some text into a word document. I do this using this function:
function saveText(text) {
var data = new Blob([text], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
However, there is one problem. Whenever I try to open it it shows this error message:
The file is corrupt and cannot be opened.
(Sorry I couldn't embed the image; I don't have enough reputation yet)
So, I have a feeling that the problem is that I need to format my text differently because right now I am just calling the function like this: saveText("Test");. In an rtf file it does have lots of stuff at the start so I thought maybe word needs this as well. However, I have looked a lot 'round the internet and couldn't find a solution. Thanks for taking the time to read (and maybe answer) this :D
function saveText(text) {
var data = new Blob([text], {type: 'application/msword'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
I simply changed application/vnd.openxmlformatsofficedocument.wordprocessingml.document to application/ms-word and everything worked :)
Related
I am making a Chrome extension so you can download images when clicking on them. The problem is that it is a bit buggy, so any help would be awesome. Here is the Javascript:
var myImg = document.querySelector('img');
myImg.addEventListener("click", () => {
var a = document.createElement('a');
a.href = myImg.src;
a.download = myImg.src;
document.body.appendChild(a);
a.click();
});
I would assume that maybe you should add an id to the image that the user clicks on, then download the value of the id. But I am not sure how to do that.
If you want to click on any img, you will want to use querySelectorAll to capture ALL images on the page, querySelector just grabs one.
var myImgs = document.querySelectorAll('img');
myImgs.forEach(function(img) {
img.addEventListener("click", (el) => {
var a = document.createElement('a');
a.href = el.target.src;
a.download = el.target.src;
document.body.appendChild(a);
a.click();
});
});
I have a web page where there is a button that when clicked, generates a (by doing a conversion from json) csv file that is downloaded by the browser. It essentially uses the logic from this jsfiddle. This all works in chrome, but in IE, nothing happens.
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
The issue seems to be that the download attribute of an anchor tag doesn't exist in Internet Explorer. I've been looking at numerous articles and SO posts, but I haven't found a coherent solution that I can use in the page.
How can the code from the jsfiddle be implemented in IE?
This is what I have used in the past. This handles IE and non-IE.
var filename = "file.txt";
var data = "some data";
var blob = new Blob([data], { type: 'text/csv' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
I have tried so many examples but none of them works
t
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
<textarea id="textbox">Type something here</textarea>
<button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
here is a code which is working good but i need to download automatically without using link
is it possible?
You could use the following script to create and save automatically a file from the browser to your operating system. This code works only on latest version of Chrome.
What the script does?
It creates a temporary URL containing the specified File object or Blob object - Programmatically click the link just created so the file will be download by the browser.
Immediately after remove the link from the page.
var saveDataToFile = function (data, fileName, properties) {
window.URL = window.URL || window.webkitURL;
var file = new File(data, fileName, properties),
link = document.createElement('a');
link.href = window.URL.createObjectURL(file);
link.download = fileName;
document.body.appendChild(link);
link.click();
var timer = setTimeout(function () {
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
clearTimeout(timer);
}, 100);
};
If you deconstruct this problem, there's a few key points:
Initially, when the user hasn't typed text into the textarea, the button should not be visible. (I may be wrong here though)
When the user starts typing, the button has to appear.
Whatever is inside the textarea after that, has to be downloadable per click on the button.
So, it's a matter of two event listeners.
The first one is "focus": when the textarea received focus, its value is an empty string, and the button appears. The user hasn't yet started typing, but there's actually no need to force them to.
The second one is "change": per every change in the field, we need to update the value of href attribute of the link, so that when the user clicks that element, file download happens, and the content is precisely what's inside the textarea. Good thing, a function passed to "change" event listener is executed with the first argument instance of Event, which means you can do event.target.value to get the new value per every change. It means, the whole text from within textarea.
Summing up, it's
<textarea id="textbox" placeholder="Type something here"></textarea>
<a download="info.txt" id="create" href="#" style="display: none;">Create file</a>
and
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create');
var textbox = document.getElementById('textbox');
textbox.addEventListener('focus', function (event) {
create.style.display = 'block';
create.href = makeTextFile(''); // initially, the text is empty.
});
textbox.addEventListener('change', function (event) {
create.href = makeTextFile(event.target.value); // per every change, update value of href attribute of #create
});
})();
Take note that only a element can have href assigned with Blob value. Using a button element would be a little bit more complicated, so it might be easier to just make the a element look like a button.
See the Codepen to make sure it works as you expect, or feel free to edit it otherwise.
For some reason this seems easier in IE than Chrome/FF:
$scope.download = function() {
Restangular.one(myAPI)
.withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {
//IE10 opens save/open dialog with filename.zip
window.navigator.msSaveOrOpenBlob(response, 'filename.zip');
//Chrome/FF downloads a file with random name
var url = (window.URL || window.webkitURL).createObjectURL(response);
window.location.href = url;
});
};
Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?
As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click
var myBlob = new Blob(["example"],{type:'text/html'})
var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();
Download attribute compatibility
Just use https://www.npmjs.com/package/angular-file-saver
Browser Support table can be seen here: https://github.com/eligrey/FileSaver.js/
I know this may seem simple, I thought so myself when I first tried it, but it turns out i'm having issues with it. This is a Userscript and I am wanting it to check if the URL is "http://orteil.dashnet.org/cookieclicker", then do one thing (but don't refresh) but if the URL is "http://orteil.dashnet.org/cookieclicker/beta" the do this other thing (also don't refresh). Here is the code that I have so far, I am just wanting to get "linkb" to run when "http://orteil.dashnet.org/cookieclicker" and "linkc" to run when "http://orteil.dashnet.org/cookieclicker/beta".
var link = document.createElement('a');
link.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
link.target = 'blank';
link.appendChild(
document.createTextNode('Cookie Clicker Classic')
);
var add = document.getElementsByTagName('div')[1];
add.insertBefore(document.createTextNode('| '), add.lastChild);
add.insertBefore(link, add.lastChild); // all the code so far will load on both pages
var linkb = document.createElement('a');
linkb.setAttribute('href', 'beta');
linkb.target = 'blank';
linkb.appendChild(
document.createTextNode('Try the beta!') //this block will load if the URL is "http://orteil.dashnet.org/cookieclicker"
var linkc = document.createElement('a');
linkc.setAttribute('href', '../');
linkc.target = 'blank';
linkc.appendChild(
document.createTextNode('Live version') // and this will load if the URL is "http://orteil.dashnet.org/cookieclicker/beta"
I have tried:
if (window.location = "http://ortei.dashnet.org/cookieclicker/") {
var linkb = document.createElement('a');
linkb.setAttribute('href', 'beta');
linkb.target = 'blank';
linkb.appendChild(
document.createTextNode('Try the beta!')
);
}
else {
var linkc = document.createElement('a');
linkc.setAttribute('href', '../');
linkc.target = 'blank';
linkc.appendChild(
document.createTextNode('Live version')
);
}
I have tried this but with alert()'s and when you push ok on the popup, it refreshes the page and does the alert again. I just want it to check what URL it is and do the corresponding code.
If anyone could come up with some ideas, or even possibly a solution, it would be much appreciated.
Thanks, Daniel
Is should be if (window.location == "http://ortei.dashnet.org/cookieclicker/") (double =), otherwise you're assigning the URL to the window.location, thus forcing a reload