I created a Chrome extension which scans the page and creates a list of h1-h6 tags of a current page in a popup window. This is how this list looks like for main StackOverflow page:
h1 | All Questions
h3 | XmlElement has a list as attribute but its items aren't separated by comma
h3 | Eclipse, Easily remove/fix all #Override due to Java version change
...
I'd like to have an "Export" button, which would give me an ability to save this report in CSV format. Is it possible?
You can use data URI scheme to create a URI storing the CSV content. Then you can create a A element with a download attribute set to the desired file name.
If your CSV is really big, you should use BlobBuilder and webkitURL.createObjectURL instead of data URI scheme to create the link href.
Here is an example using data URI scheme:
var link = document.createElement("a");
link.textContent = "Save as CSV";
link.download = "file.csv";
link.href = "data:text/csv,h1;All Questions\n"
document.body.appendChild(link);
When the user will click the link, the "file.csv" will be automatically saved in the default Download folder.
Based on #check_ca answer, I've coded the following to return a csv link element for array data:
function getCSVLinkElement(arr){
var link = document.createElement("a");
link.textContent = "Save as CSV";
link.download = "file.csv";
var csv = arr.map(function(v){return v.join(',')}).join('\n');
link.href = encodeURI("data:text/csv,"+csv);
return link;
}
var el = getCSVLinkElement([['num','sq'],[2,4],[3,9]]);
document.body.appendChild(el);
Related
UPDATE:
Creating a Blob from a base64 string in JavaScript
I am trying to implement click a button and download file from its DataURL.
Currently, since the Chrome has restricted the old way such as building <a> link which throws error like:
Not allowed to navigate top frame to data URL: ....
The solution I found is open new window with iframe and set the DataURL as its src
let jpgWindow = window.open("", "_blank")
var html = "<html><body><iframe width='100%' height='100%' src='data:application/jpeg;base64, "+ theDataURL+"'></iframe></body></html>";
jpgWindow.document.write(html)
When I click the button, the download works, but the picture is downloaded with filename "download", there is no way I can specify what file name I want it default to.
Any thought?
Look into window.URL.createObjectURL https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
const blob = new Blob(['array of data in your file'], {type : 'text/rtf'});
const anchor = document.createElement('a');
anchor.href = window.URL.createObjectURL(blob);
anchor.download = 'the-file-name.txt';
anchor.click();
I'm building a page for my angular2 web application where a user can select customers from a list and print off letters to mail them. These letters were uploaded as PDFs and are stored as varbinary in the database.
In the case of multiple selections, I'm simply appending byte[]'s so the user will print one document containing all of the letters to send to customers.
I'm able to pull the blob successfully from the API and return it with the content type application-pdf but then I don't know what to do with it from there.
Here's my Angular2 Component API Call:
this.printQueueService.getPrintContent(printRequests) //customers to receive letters
.subscribe((data: Blob) => {
var element: HTMLIFrameElement = <HTMLIFrameElement>document.getElementById('printFile');
element.innerText = data + ""; //what do I do with the blob?
element.contentWindow.print();
});
HTML Element:
<iframe id="printFile" style="display:none"></iframe>
I know I can just download the PDF and prompt the user to print using a PDF Viewer, but I'd rather not force users to go through extra steps.
I'd also rather not try to render the PDF in the browser and print because it assumes users have the proper plugins and browsers support it.
What options do I have for printing a blob in the browser?
As per suggestions from Daniel A. White, I solved this issue. I decided not to use an IFrame because these print files could be massive and the print() function includes the page name as footnotes.
Instead, I chose to open the generated PDF in a new tab as follows:
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(data, "PrintedLetters.pdf"); //IE is the worst!!!
}
else {
var fileURL = URL.createObjectURL(data);
var a: HTMLAnchorElement = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
document.body.appendChild(a);
a.click();
}
I use javascript to generate a file and download it.
It seems, that depending on the version of chrome, the download file names can be auto renamed to 'download'. Is there a way to avoid it?
this is my code:
var link = document.createElement("a");
link.setAttribute("href", 'data:application/octet-stream,' + 'file content here');
link.setAttribute("download", 'file1.txt');
link.click();
This is not a duplicated question, because I'm using the latest Chrome and the previously suggested hyperlink is exactly what I'm using. I think, Chrome v34 works fine, but once my Chrome auto updated to v35, it went back to 'download' file name.
It seems to be linked to this bug/feature. Status: Wontfix.
Use HTML5 download attribute. This attribute will tell browser that virtual link we created is aimed for download only. It will download file from link's href to file with name specified as download attribute's value. This great feature works in Chrome.
window.downloadFile = function(sUrl) {
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
if (link.download !== undefined){
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click' ,true ,true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
var query = '?download';
window.open(sUrl + query);
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
Demo Link: http://pixelscommander.com/polygon/downloadjs/#.U4gyDPmSwgS
I'm trying to create a download link in an angular app that makes data in a model downloadable as a CSV file. I have it all working except for the actual download link. Using filesaver.js is blowing up unit tests in Karma so I'm exploring just doing it manually.
Below is what I have. In the controller:
var blob = new Blob([data.join('\n')], {type: 'text/csv;charset=utf-8'});
$scope.downloadUrl = URL.createObjectURL(blob);
In the view, I have:
<a ng-href="{{downloadUrl}}" download="ttester.csv" id="download">Download</a>
The issue is this opens a new page in Firefox 20 with the URL "unsafe:blob:af775c64-dcb1-864a-8eaa-adebe7f101a7", notice the "unsafe:" prefix. Removing that prefix downloads the data correctly, but without the filename I want.
What am I missing in my hyperlink to make it work? I expect it to open a download dialog with the filename tester.csv for the file.
Really appreciate any help
You could use the following code that will create the blob, a fake link and will dispatch a click event on this fake link. Note that no new page should be opened but you will be directly prompted with the save dialog box.
var blob = new Blob([data.join('\n')], {type: 'text/csv;charset=utf-8'});
var url = window.URL || window.webkitURL;
var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
link.href = url.createObjectURL(blob);
link.download = 'teams.csv'; // whatever file name you want :)
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, false);
link.dispatchEvent(event);
You can see a working Fiddle here
Is there any link for exporting the datas to notepad?
I have some fields like
Name,
Age, and
WorkingStatus
These are text and textarea...
I want to insert this datas to the notepad.Is there any demos or code available?
I don't know of any way to have the browser open notepad, but you can use HTML5 features to save a file as text, and then open it on your own inside notepad. Depending on the browser, you may need to trigger saving the file on the user side. Here's two references, which I'll summarize:
http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/
http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side
Basically, you want to create and save a blob with your text. It should look something like this:
var arrayOfStuff = [];
arrayOfStuff.push("Name Age Working status");
arrayOfStuff.push("-----------------------------------------------");
arrayOfStuff.push(document.getElementById("name").value);
// etc
var blob = new Blob(arrayOfStuff, {type:'text/plain'});
// (the rest is copied directly from the wordpress link)
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked programmatically.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
downloadLink.click();
}
else
{
// Firefox requires the user to actually click the link.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
document.body.appendChild(downloadLink);
}
If notepad isn't a big deal, you should also be able to open this blob in an iframe as .txt, and then right-click and saveAs, if you prefer.
Edit
Ok, this was actually new for me to play with, so some of my older information wasn't quite right. Here's the javascript from the working fiddle:
var arrayOfStuff = [];
arrayOfStuff.push(document.getElementById("name").value + "\n");
arrayOfStuff.push(document.getElementById("email").value);
arrayOfStuff.push("\n");
arrayOfStuff.push(document.getElementById("phone").value);
arrayOfStuff.push("\n");
arrayOfStuff.push(document.getElementById("comments").value);
arrayOfStuff.push("\n");
alert(arrayOfStuff);
var blob = new Blob(arrayOfStuff, {type:'text/plain'});
var link = document.getElementById("downloadLink");
link.download = "details.txt";
link.href = window.URL.createObjectURL(blob);
The fiddle is at http://jsfiddle.net/xHH46/2/
There are a few lessons learned:
If you're on firefox, it gives you the option to open the .txt immediately in Notepad. However, notepad isn't paying attention to the linefeeds, whether they're \n or \n\r, appended to the immediate string or added separately, so I'd recommend using Wordpad instead. Or, you can save the file.
More importantly, realize that the link you display is based on whatever value is in the text when you create the blob. If you don't have defaults, you'll get an empty file, because all the fields are empty. The wordpress solution fixes this (and discusses using it within the past week), but the fix is ugly. Basically, you'd have to click on a button, and the button would then make a link appear, and that link would give you the good file.
You won't be able to do this with purely javascript. You need to generate the file server side and send it to the client.