Export HTML to Word Document with JavaScript (different sections)

By: Luis De Pau | Asked: 08/10/2022
ForumsCategory: Code HelpExport HTML to Word Document with JavaScript (different sections)
Luis De PauLuis De Pau asked 2 years ago
I have a view that allows me to see all the entries made by a customer in the same page: John
-Text entry 1
-Text entry 2
-Text entry 3 And I want to download each text as a word document or as a pdf. In the pdf case I use the script recommended by @Victor Font: https://printjs.crabbly.com/ as each Div ID used to print can be associated to de entry ID.  In the html to doc case, I found this interesting scripts helps downloading a view as a word document and works perfect when there's just one entry.  (How to Export HTML to Word Document with JavaScript) The script is
<script> function exportHTML(){ var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' "+ "xmlns:w='urn:schemas-microsoft-com:office:word' "+ "xmlns='https://www.w3.org/TR/REC-html40'>"+ "<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>"; var footer = "</body></html>";
var sourceHTML = header+document.getElementById("source-html").innerHTML+footer; var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML); var fileDownload = document.createElement("a"); document.body.appendChild(fileDownload); fileDownload.href = source; fileDownload.download = 'document.doc'; fileDownload.click(); document.body.removeChild(fileDownload); } </script>
and the html in the view is
<div id="source-html"> content to print </div> <div class="content-footer"> <button id="btn-export" onclick="exportHTML();">Export to word doc</button> </div>
My questions are: I can add a value to de div id, for example "source-html-[key]".  Is there a way to include one script for each div in a view?  Or a way to make the script work for any source-html-[whateverthisis] ID? I hope this makes any sense. Thanks for any help!
Bobby Clapp replied 2 years ago

It can be dynamic like that if you insert the script into the body of the view just like that, but it can create some exhaustive HTML code if you have a bunch of entries.

Luis De PauLuis De Pau replied 2 years ago

Thanks Bobby!
I tried it but I must have done something wrong. Will retest. Thanks a lot.

1 Answers
Best Answer
Victor Font answered 2 years ago

Why not pass the div id as a parameter?

button id="btn-export" onclick="exportHTML("divID");

Change the function name to exportHTML( param ).

In the code, change "source-html" to param.

Luis De PauLuis De Pau replied 2 years ago

I will definitely try it,
Thanks a lot Victor!

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right