【问题标题】:Html to MS Word using JS without Header and Footer使用没有页眉和页脚的 JS 将 Html 转换为 MS Word
【发布时间】:2020-10-30 12:58:17
【问题描述】:

我正在尝试借助以下代码将 HTML 页面转换为 MS Word 文档文件。 我的问题是我不想要任何页眉和页脚。 我想创建没有页眉和页脚额外空格的 word 文件。内容应置顶。

我得到了结果,但我不想在其中包含页眉和页脚。

 function Export2Doc(element, filename = ''){
           
           var preHtml = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8"><title>Export HTML To Doc</title><style>body,html{margin-top: 0px !important;padding-top: 0px !important;padding-left: 0px !important;margin-left: 0px !important;font-size: 12px;margin-left: 0px !important;}.scheduledtxt{font-size: 14.5px;}table{margin: auto 0px !important;}</head><body>';
           
            var postHtml="</body></html>";
            var html = preHtml+document.getElementById(element).innerHTML+postHtml.trim();
            
            var blob = new Blob(['\ufeff', html], {
                type: 'application/msword'
            });
    
            // Specify link url
            var url = 'data:application/msword;charset=utf-8,' + encodeURIComponent(html);
            
            // Specify file name
            filename = "test.doc";
            
            // Create download link element
            var downloadLink = document.createElement("a");
        
            document.body.appendChild(downloadLink);
    
            if(navigator.msSaveOrOpenBlob ){
                navigator.msSaveOrOpenBlob(blob, filename);
            }else{
                // Create a link to the file
                downloadLink.href = url;
                
                // Setting the file name
                downloadLink.download = filename;
                
                //triggering the function
                downloadLink.click();
            }
            
            document.body.removeChild(downloadLink);
        }
<span id="exportContent">
     <h2 style="text-align: center;">Test Document</h2>
</span>
     
     <div style="text-align: center;">
        <button id="hiddenBtn" style="background: royalblue; color: white;padding: 10px; border-radius: 10px;" onclick="Export2Doc('exportContent', 'word-content');">Export as .doc</button>
      </div>      
        

【问题讨论】:

    标签: javascript html ms-word docx doc


    【解决方案1】:

    我已经通过以下链接实现了我的目标 css print mode: display header and footer only on first page of a generated word doc

    我只需要在下面添加 css 代码。 为了更好地理解,只需缩小整个代码并在转换为 word 文件时使用。

    @page {
            size: 2cm 2.7cmt;
            margin: 0.4cm 0cm 0cm 0cm;
            mso-page-orientation: portrait;
            mso-header: none;
            mso-footer: none;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-04
      • 2017-08-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多