doc.createParagraph 不是函数 - docx

doc.createParagraph not a function - docx

编辑:已解决(他们更改了他们的文档,而我没有做正确)。

我正在尝试使用 docx NPM 包在 JavaScript 中创建 docx 文件。我已将文档复制并粘贴到 "get started",它返回一个 "doc.addParagraph" is not a function for each line for the function handler.根据文档,docx 包在前端和后端都可以是 运行,所以我已经将文档 starter-kit 复制并粘贴到我的 React Web 应用程序中,但它无法正常工作。

这是文档:https://docx.js.org/#/

这里是前端docx的浏览器示例:https://codepen.io/anon/pen/dqoVgQ

这是我的反应网络应用程序中的代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';

import * as fs from 'fs';
import { Document, Packer, Paragraph, TextRun } from 'docx';

class Template1 extends Component {

    constructor (props) {
        super(props);
        this.state = {
            errors: {}
        }
        this.onGenerate = this.onGenerate.bind(this);
    }

    onGenerate = (e) => {
        const doc = new Document();

        doc.createParagraph('hello world').heading1();



        const paragraph = new Paragraph("Hello World");
        const institutionText = new TextRun("Foo Bar");
        const dateText = new TextRun("Github is the best")
        paragraph.addRun(institutionText);
        paragraph.addRun(dateText);

        doc.addParagraph(paragraph);

        const packer = new Packer();

        packer.toBuffer(doc).then((buffer) => {
            console.log(buffer);
            // saveAs(blob, "example.docx");
            fs.writeFileSync('example.docx', buffer);
            console.log("Document created successfully");
        });
    }

    componentDidMount() {

    }


  render() {

    const { errors } = this.state;


    return (
        <div>
            <section id="testing-download-docx-button">
                <div className="row">
                    <div className="col-xl-12 col-lg-12 col-md-12 col-sm-12">
                        <button onClick={this.onGenerate.bind(this)} className="button text-center red-outline-button d-inline-block">Download DocX</button>
                    </div>
                </div>
            </section>
      </div>
    )
  }
}

Template1.propTypes = {
    errors: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
    errors: state.errors
});

export default connect(mapStateToProps, {  })(withRouter(Template1));

文档 class 中没有任何 addParagraph 方法。 实际上应该使用 addSection.

添加

喜欢

doc.addSection({
    children: [
        new Paragraph({
            children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello 
                      World")],
            }),
    ],
});