文中所有数值都是这么换算的
举例页面是A4 页面边距是 2.54mm 1.91mm
(1 cm = 144 Twip 上边距(2.54 cm) = 2.54 × 144 = 365.76 Twip)

一、修改html-docx-js源代码

1、找到html-docx-js/dist/html-docx.js
2、找到 renderDocumentFile 这个方法替换(原本的尺寸是信纸)

  renderDocumentFile: function(documentOptions) {
    var templateData;
    if (documentOptions == null) {
      documentOptions = {};
    }
    templateData = _.merge({
      margins: {
        top: 1440,
        right: 1440,
        bottom: 1440,
        left: 1440,
        header: 720,
        footer: 720,
        gutter: 0,
        ...documentOptions.pageMargins
      }
    }, (function() {
      switch (documentOptions.orientation) {
        case 'landscape':
          return {
            width: documentOptions.pageSize?documentOptions.pageSize.width:12240,
            height:documentOptions.pageSize?documentOptions.pageSize.height: 15840,
            orient: 'landscape'
          };
        default:
          return {
            width: documentOptions.pageSize?documentOptions.pageSize.width:12240,
            height:documentOptions.pageSize?documentOptions.pageSize.height: 15840,
            orient: 'portrait',
            
          };
      }
    })(), {
      margins: documentOptions.margins
    });
    return documentTemplate(templateData);
  }

二、为了方便 定义一个数组 typesettingTypeOptions

 typesettingTypeOptions: [
        {
            label: '竖向',
            value: 1,
            orientation: 'portrait',
            pageSize: {
                width: 11906,
                height: 16976
            },
            pageMargins: {
                 top: 1440,
                bottom: 1440,
                left: 1084,
                right: 1084,
            }
        },
       
        {
            label: '横向',
            value: 2,
            orientation: 'landscape',
            pageSize: {
                width: 16976,
                height: 11906
            },
            pageMargins: {
                top: 1440,
                bottom: 1440,
                left: 1084,
                right: 1084,
            }
        }
    ],
// 将 HTML 转换为 Word Blob
 const converted = htmlDocx.asBlob('自己的html代码', {
         orientation: this.typesettingTypeOptions[this.typesettingType - 1].orientation,
         pageSize: {
             ...this.typesettingTypeOptions[this.typesettingType - 1].pageSize
         },
         pageMargins: {
             ...this.typesettingTypeOptions[this.typesettingType - 1].pageMargins
         }
     });
  // const converted = htmlDocx.asBlob(tableHtml); 
   // 触发文件下载
   const link = document.createElement('a');
   link.href = URL.createObjectURL(converted);
   link.download = 'table.docx';
   link.click()

更多推荐