Download a <div> to .doc or .docx using JS

末鹿安然 提交于 2019-12-11 02:44:19

问题


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!


回答1:


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.




回答2:


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.




回答3:


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)



来源:https://stackoverflow.com/questions/11810212/download-a-div-to-doc-or-docx-using-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!