Say I have dynamic content of a div :
//a button to click, or something
<button type="button">Download Content as a .doc</button>
//Div to be downloads as .div
<div class="gc"> //Generated content
<h1>A Header</h1>
<p>A Paragraph</p>
<ul><li>A</li><li>List</li><li>Here</li></ul>
</div>
What ways can you suggest approaching this without using server side help? I am open to JS, as I am currently learning this, and can access the div with Jquery, just looking either for a simple answer or a hint down the right direction to learn.
Hopefully it is as easy as the oppposite as showing a pdf in a div, like the this, but I don't know.
For my particular situation, the content can formatted or not, placed as an object within word or some other quirky workaround, or maybe using a common browser extension. Ultimately, I just want to be able to offer the user a .doc (potentially .docx) version of the content.
If I MUST use server side functionality, have any good links to help me meander through a solution? as I do not know AJAX or PHP, but am willing to learn!
This is not possible without some sort of serverside thing that will send the correct headers.
You can rename a .html file to .doc, and word will eat it, but you will still need some PHP, or whatever serverside language is your drug of choice to send a content-disposition download tag and a content-type application/vnd-ms-word header.
This is impossible with pure javascript, due to obvious security risks.
Part of this is possible with HTML5 using blob builders and object URLs. The hard part is generating a word-compatible file, left as an exercise to the reader:
// normalize vendor extensions
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
window.URL = window.URL || window.webkitURL;
// create the file and append contents to it
var blobthebuilder = new BlobBuilder();
blobthebuilder.append("some text");
// create a URL for the newly created file with a mime
// type and make the anchor point to it
anchor.href = window.URL.createObjectURL(blobthebuilder.getBlob("text/html"));
Webkit also supports a[download] which will automatically download the file instead of requiring left-click → Save As...
Demo on jsFiddle.
I dont think you can do this without some serverside scripting via AJAX.
If you use php it would be simple to send via AJAX and send back as a text file to download. Then you just need to find a script that can convert it to .doc file as this is a complex format.
However i'm not sure with HTML5 though.. Has a lot of new features.
Edit: ok i can see SchizoDuckie beat me to by 1 min lol :o)
Related
The only solution I've found it to grab the link with getElementsByClassName then inject it into an html snippet on the page, but it looks so fake, and is also unnecessary (I don't want all the links)
I want to right click the link (one at a time) and show it to the next tab. If I right click the link the server sends me a download prompt. How can I evade this?
I think the browser decides to download a file or display it based on its MIME type.
If the server is under your control, you should make sure you supply the correct Content-Type HTTP header (e.g. you have to call a library function in PHP, and there should be a similar way to do that in other languages).
Otherwise, for a purely client-side solution in JavaScript, you can fetch the file with an XMLHttpRequest (most JavaScript toolkits have wrappers around it). Then, you can convert it to base 64, prefix the result data:image/png;base64,, and use it as the src attribute of an img element (thanks https://stackoverflow.com/a/21508186/324969).
Note that for security aspects, grabbing arbitrary files and stuffing them in a data: URL might not be safe. I don't know if any cross-site scripting or CORS attacks could be built upon this. You'll have to ask a separate question to know if the client-side solution is unsafe. For the server-side, be careful not to set the wrong content-type for user-uploaded data, or for endpoints of your service (e.g. letting the client-side send you in the request the Content-Type that it would like, as tempting as it looks, is a big no-no).
To open the image in a new tab, you can use window.open as usual, but download the image beforehand (using XMLHttpRequest) and put the data:image/png;base64,… as the URL of the new tab.
Since you can already see the images by placing their URL in an img tag, you can paint that img on a , extract a PNG from the canvas, craft a data:image/png;base64,… URL from that, and then either automatically open many tabs with these URLS, or write in your page a series of links to data: URLs.
You could also have a link to a tiny web page with just the img tag that you currently use: link text.
I have a PDF file as a blob object. I want to serve to my users, and right now I'm doing:
html = '<iframe src="' + URL.createURL(blob) + '">';
That works fine for people that want to use their in-browser PDF tool.
But...some people have their browser set to automatically download PDFs. For those people, the name of the downloaded file is some random string based on the blob URL. That's a bad experience for them.
I know I can also do:
<a href="blobURL" download="some-filename.pdf">
But that's a bad experience for the people who want to use in-browser PDF readers, since it forces them to download the file.
Is there a way to make everybody have good file names and to allow everybody to read the PDF the way they want to (in their browser or in their OS's reader)?
Thanks
At least looking at Google Chrome, if the user disables the PDF Viewer (using the option "Download PDF files instead of automatically opening them in Chrome") then window.navigator.plugins will show neither "Chromium PDF Plugin" nor "Chromium PDF Viewer". If the option is left at the default setting, the viewer will show in the plugin list.
Using this method, one can utilize window.navigator.plugins to check if any of the elements' names are either of the aforementioned plugins. Then, depending upon that result, either display a <iframe> or a <a href="blobUrl" download="file.pdf">. For other browsers I imagine that different methods would have to be used. You can also check for a "Acrobat Reader" plugin, which some machines may have instead, or even just the word "PDF".
On a side note, it does look like it is possible to detect if the default Firefox PDF viewer is enabled by using http://www.pinlady.net/PluginDetect/PDFjs/ .
Try to append &filename=thename.pdf to the binary, metadata or http header:
Content-Disposition: attachment; filename="thename.pdf"
I have looked through the documentation of createObjectURL(blob), it will always return a unique and specific format of url. It is not possible to change the URL here.
The plugin thing is not consistent across browsers.
Now here is my radical idea
Find or create(if not available) a js library that can create and save PDF files to server from blob. (I looked through some of them like 'jsPDF','pdfkit' but none of them use blob)
Save the file to server with a valid name
use the above name in the iframe.
I am facing a situation in my application where i need to add a pdf download link on to my page, but i cannot refer to any relative or absolute path for the file, I need to host my pdf inside the html only.
Is there any way to do this, using basic HTML and JavaScript?
Details summary of situation is as below :
there is an application which owned by someone else, i am customizing if for a particular client.
we are given a provision to place some html(s) in a directory which are used in a few pages in the application.
these htmls are not used with href or include in the product application, but are picked up by the product's java code and are added in the response, thus keeping a PDF in the same folder as my HTML and providing relative URL wont work here.. and putting absolute URL is also not a solution as this needs to work across multiple environments.
You can always use data URI links:
download PDF!
Possibly together with the download attribute:
...
E.g. http://jsbin.com/gutahugoci/ (PDF is from here).
To encode in base64 use base64 -w0 my_file.pdf > my_file.pdf.b64
Disclaimer: Please notice that I said "you can use", not "you should use. This should only be a last resort thing to do for PDFs, because the HTML file will become exceedingly big and your client might ask if your are kidding them.
why don't you encode the url
/download_pdf.php?id=r4yhr4hrb4rd54hddb4
Where r4yhr4hrb4rd54hddb4 is and encoded id?
I'm trying to figure out how to call the File Save As Command in Firefox
(the one you get when you right click an image and save it) to save an image using JS (or if there is something else I can use, I would be grateful if you pointed me in that direction). I am looking for an example of how to open the Save As menu and pre-fill the file name field ... I've been searching furiously and have come up with zip. In my search I saw that you cannot directly save a file to disk, but is it impossible to call the save as function? Any suggestions would be greatly appreciated!
Edit:
I'm not looking to make this code available to everyone, and the java script is client side, I'm just writing a small script to make saving photos a little easier in terms of naming them.
-Will
No you can't do this, and really you are trying to find a solution in a way that does not embrace the internet and the way people interact with content. What you are trying to do is call on Operating System operation from Javascript. If there were anyway this would be possible, I don't think it is at all, it would be a very poor solution. Think about all the different Operating Systems Firefox is being used on. If you found a solution for Windows 7, what about an Apple Mac running Firefox?
What you should consider is that a User decides whether to Save something to their computer, not the programmer of the application. Provide a link to the file, most users know how to right click a link and select Save As. Add help tip explaining what to do as well.
To give a File a specific name or even start an automatic download when a User clicks or takes some kind of action, you can create a response from your server that is a PDF,Excel,Jpeg,Doc,Docx or many other files types. The server can load the file in memory and sent it as a response with the proper header information in the response.
For example to set a specific name for the file when the user downloads you can set your Response header with something like:
header('Content-Disposition: attachment; filename="downloaded.pdf"');
You can use the anchor element's download attribute to specify that a link is to be downloaded. Note that this is not implemented in all browsers, Chrome, Firefox, and Opera currently support it
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
HTMLAnchorElement.download
Is a DOMString indicating that the linked
resource is intended to be downloaded rather than displayed in the
browser. The value represent the proposed name of the file. If the
name is not a valid filename of the underlying OS, browser will adapt
it. The value is a URL with a scheme like http:, file:, data: or even
blob: (created with URL.createObjectURL).
Demo
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
var link = document.getElementById("link");
//Set href to the data url that you want downloaded
link.href = "http://placehold.it/350x350";
//set download to the default filename you want to use
link.download = "image.png";
<canvas id="canvas" width="150" height="150"></canvas>
Click to download
You can also specify a regular url to a file, but note that if the server sends a filename header: Content-Disposition ... filename... that it will overwrite whatever you have in the download attribute.
I have an app that uses Javascript to perform some calculations and then plot the data, but I'd like to add the option for the user to be able to actually download the data into a csv or xls file.
Is there a way in Javascript (or some other method) to have the user press a button, then it will prompt them for the name of the file to save it as, and it will then create a comma-delimited or excel spreadsheet?
Thanks!
EDIT:
Thanks for all the suggestions everyone. Wish I could mark you all as answers, but upboats will have to do for now
It's not hard to open a window and write the csv into it. But I don't know of any way for javascript to change the Content-Type: header. And without that it won't prompt to save or open.
You'll need assistance from the server to do this. You can send the data to the server in a form variable and have the server send it right back with the correct header Content-type: text/csv you may also want the Content-Disposition: header to give your file a name.
Yes, but you'll need to use server-side code as well. Use JavaScript to construct a link to a page that streams the csv data back as an attachment. The server output should contain a content-disposition header of attachment; filename="fileName.csv".
No, you can't create and/or save a file directly from JavaScript. On some browsers/platforms (IE/Windows), you could create and write to a file via ActiveX object:
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\temp\\Test.txt", true);
s.WriteLine('Hello');
s.Close();
}
Another solution is to use client-side JavaScript (inside a browser) to output CSV data into a separate window (or pop-up) and have a user to copy/paste it into Excel.
If you want to do it in a browser website style it might be hard. But Javascript is a good language to do this, but you will need to use .hta instead of a normal .html. Creating an .hta creates a stand alone application just like a normal .exe.
Here is what you want to look for ActiveXObject("Excel.Application")
In order to transform a html into an hta, here is the tag
<HTA:APPLICATION
id="SomeId"
border="thin"
borderStyle="normal"
caption="yes"
maximizeButton="yes"
minimizeButton="yes"
showInTaskbar="yes"
windowState="yes"
innerBorder="yes"
navigable="yes"
scroll="auto"
scrollFlat="yes"
singleinstance="yes"
/>
For futher reading on hta and the excel active X
You could certainly write a browser plugin (ActiveX control on IE, NPAPI on others) with FireBreath that would do this; you'd have to write it in C++. Honestly, I agree with others in suggesting that you do this server-side instead, but you can do it with a plugin and it wouldn't be too difficult.
I think that it would be possible to do this (up to a certain size limit) with data URIs