编辑:已解决(他们更改了他们的文档,但我没有正确执行)。
我正在尝试使用docx NPM包在JavaScript中创建docx文件。我已经将文档复制并粘贴为“入门”,并且返回的“ doc.addParagraph”不是函数处理程序中每一行的函数。根据文档,docx包可以在前端和后端上运行,因此我已经将文档入门工具包复制并粘贴到我的react Web应用程序中,但是无法正常工作。
以下是文档:https://docx.js.org/#/
以下是前端docx的浏览器示例:https://codepen.io/anon/pen/dqoVgQ
这是我的React Web应用程序中的代码:
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));