javascript - Node.js 使用 officegen 创建和下载 word 文档

标签 javascript node.js ms-word

我想使用 officegen npm 模块创建一个 word (docx) 文件并下载它。过去我使用 tempfile 模块创建一个临时路径用于下载目的。这是我为 word 文档下载编写的代码:

var tempfile = require('tempfile');
var officegen = require('officegen');
var docx = officegen('docx');

router.post('/docx', function(req, res){
    var tempFilePath = tempfile('.docx');
    docx.setDocSubject ( 'testDoc Subject' );
    docx.setDocKeywords ( 'keywords' );
    docx.setDescription ( 'test description' );

    var pObj = docx.createP({align: 'center'});
    pObj.addText('Policy Data', {bold: true, underline: true});

    docx.on('finalize', function(written) {
        console.log('Finish to create Word file.\nTotal bytes created: ' + written + '\n');
    });
    docx.on('error', function(err) {
        console.log(err);
    });

    docx.generate(tempFilePath).then(function() {
        res.sendFile(tempFilePath, function(err){
            if(err) {
                console.log('---------- error downloading file: ' + err);
            }
        });
    });
});

但是它给了我一个错误提示

TypeError: dest.on is not a function

创建的总字节数也显示为 0。我做错了什么?

最佳答案

router.post('/docx', function(req, res){
    var tempFilePath = tempfile('.docx');
    docx.setDocSubject ( 'testDoc Subject' );
    docx.setDocKeywords ( 'keywords' );
    docx.setDescription ( 'test description' );

    var pObj = docx.createP({align: 'center'});
    pObj.addText('Policy Data', {bold: true, underline: true});

    docx.on('finalize', function(written) {
        console.log('Finish to create Word file.\nTotal bytes created: ' + written + '\n');
    });
    docx.on('error', function(err) {
        console.log(err);
    });

   res.writeHead ( 200, {
    "Content-Type": "application/vnd.openxmlformats-officedocument.documentml.document",
    'Content-disposition': 'attachment; filename=testdoc.docx'
    });
    docx.generate(res);
});

关于javascript - Node.js 使用 officegen 创建和下载 word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42243300/

相关文章:

C# 将 Excel 图表作为对象(而不是图片)导出到 Word

VBA 将文档从 .docm 保存(并转换)为 .docx

javascript - 如何隐藏一个元素并仍然能够转换它并且在其中有一些粘性的东西?

javascript - 从热图中隐藏列

node.js - 直接下载 OneDrive 文件的链接?

node.js - nodeS CORS 的问题

javascript - Node 预 gyp 安装 --fallback-to-build

javascript - 如何在 Javascript 中合并两个字典?

php - 通过电子邮件发送动态生成的调查页面的内容

javascript - API 返回数据,但在 undefined object 中。这是怎么回事?