Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export html table as word file and change file orientation

I have jquery function which exporting html table to word file. Function works great, but I need to rotate a word file to landsacpe orientation. Can somebody help me?

Here is js function:

    <SCRIPT type="text/javascript">
$(document).ready(function () {
    $("#btnExport").click(function () {
        var htmltable= document.getElementById('tblExport');
        var html = htmltable.outerHTML;
        window.open('data:application/msword,' + '\uFEFF' + encodeURIComponent(html));
    });
});
  Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.docx");

like image 772
Martynas Tumas Avatar asked Mar 31 '16 10:03

Martynas Tumas


Video Answer


1 Answers

Export HTML to Microsoft Word

You may set page orientation, paper size, and many other properties by including the CSS in the exported HTML. For a list of available styles see MS Office prefixed style properties Some styles have dependencies. For example, to set mso-page-orientation you must also set the size of the page as shown in the code below.

Updated:
Tested with Word 2010-2013 in FireFox, Chrome, Opera, IE10-11. Minor code changes to make work with Chrome and IE10. Will not work with legacy browsers (IE<10) that lack window.Blob object. Also see this SO post if you receive a "createObjectURL is not a function" error: https://stackoverflow.com/a/10195751/943435

     @page WordSection1{
         mso-page-orientation: landscape;
         size: 841.95pt 595.35pt; /* EU A4 */
         /* size:11.0in 8.5in; */ /* US Letter */
     }
     div.WordSection1 {
         page: WordSection1;
     }

To view a complete working demo see: https://jsfiddle.net/78xa14vz/3/

The Javascript used to export to Word:

 function export2Word( element ) {

   var html, link, blob, url, css;

   css = (
     '<style>' +
     '@page WordSection1{size: 841.95pt 595.35pt;mso-page-orientation: landscape;}' +
     'div.WordSection1 {page: WordSection1;}' +
     '</style>'
   );

   html = element.innerHTML;
   blob = new Blob(['\ufeff', css + html], {
     type: 'application/msword'
   });
   url = URL.createObjectURL(blob);
   link = document.createElement('A');
   link.href = url;
   link.download = 'Document';  // default name without extension 
   document.body.appendChild(link);
   if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11
       else link.click();  // other browsers
   document.body.removeChild(link);
 };

And the HTML:

<button onclick="export2Word(window.docx)">Export</button>
<div id="docx">
  <div class="WordSection1">

     <!-- The html you want to export goes here -->

  </div>
</div>
like image 140
Roberto Avatar answered Oct 17 '22 16:10

Roberto