禅道博客

分享专业技术知识,文章内容干货满满

Docx.js 创建word文档记录

2023-12-21 15:21:51
宋辰轩
原创 1313
摘要:本文将分享如何通过Docx.js创建word文档。

准备

Docx.js官方文档
Docx.js的github
Docx.js示例
Docx min.js下载地址
FileSaver.js下载地址

plotly图片转base64

请教了大佬,得知从这里找js文件

当然如果你的项目使用npm,直接下载即可,普通的项目需要外部引入这两个js文件:

一个可以直接粘贴运行的demo

<h1>DOCX browser Word document generation</h1>
<button type="button" onclick="generate()">Click to generate document</button>
<script src="https://unpkg.com/docx@7.1.0/build/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
function generate() {
  const doc = new docx.Document({
    sections: [
      {
        properties: {},
        children: [
          new docx.Paragraph({
            children: [
              new docx.TextRun("Hello World"),
              new docx.TextRun({
                text: "Foo Bar",
                bold: true
              }),
              new docx.TextRun({
                text: "\tGithub is the best",
                bold: true
              })
            ]
          })
        ]
      }
    ]
  });
  docx.Packer.toBlob(doc).then((blob) => {
    console.log(blob);
    saveAs(blob, "example.docx");
    console.log("Document created successfully");
  });
}


Docx.js 在生产环境中更可能采用的一种用法

常规的用法大概是进入一段逻辑,来判断需要加入一些什么东西:由于plotly导出图片接口是一个promise,因此异步,直接替换掉上面demo的js部分即可使用。



async function generate() 
{
    /* 当然,这里可以for循环将createSection()的返回值加入一个数组,在new docx.Document时直接传入该数组即可 */
    const section = await createSection();
    const doc = new docx.Document({ sections: [section] });
    docx.Packer.toBlob(doc).then((blob) => { saveAs(blob, "example.docx"); });
}
async function createSection() 
{
    var section = new Object();
    section.properties = new Object();
    section.children   = []; 
    
    /* 添加一个标题 */
    section.children.push(new docx.Paragraph({ text: '标题', heading: docx.HeadingLevel.HEADING_3, }));
    /* 添加一行空格 */
    section.children.push(new docx.Paragraph({ text: '' }));
    
    var tableRow   = [];
    var thChildren = [];
    
    /* 表格添加一行表头 */
    thChildren.push(new docx.TableCell({ children: [new docx.Paragraph('表头1')] }));
    thChildren.push(new docx.TableCell({ children: [new docx.Paragraph('表头2')] }));
    tableRow.push(new docx.TableRow({ children: thChildren}));
    /* 表格添加3行内容 */
    for(let i = 1; i <= 3; i ++)
    {
        var tdChildren = [];
        tdChildren.push(new docx.TableCell({ children: [new docx.Paragraph('td1')] }));
        tdChildren.push(new docx.TableCell({ children: [new docx.Paragraph('td2')] }));
        tableRow.push(new docx.TableRow({ children: tdChildren }));
    }
    section.children.push(new docx.Table({ rows: tableRow }));
    
    /* Docx.js 的image需要buffer,可以传入base64格式的图片,下面两行使用plotly接口得到了一个格式为base64的res
    const gd = await Plotly.newPlot('plotly_div', eval(item.data.data), eval(item.data.layout));
    const res = await Plotly.toImage(gd,{height:500,width:1000});
    
    var image = [];
    image.push(new docx.ImageRun({ data: res, transformation: { width: 400, height: 200, } }));
    section.children.push(new docx.Paragraph({ children: image }));
    */
    return section;
}


界面和得到的docx结果

暂时没有记录
评论通过审核后显示。