NodeJS从模板创建pdf,为下载提供服务然后删除文件

时间:2018-03-13 13:57:33

标签: node.js express

我按照标题中描述的步骤遇到了问题。我正在使用Express和dynamic-html-pdf从HBS模板生成pdf。

    var html = fs.readFileSync('./app/pdf/template.html', 'utf8');

    router.post("/download", function (req, res) {
        var config = req.body;
        var options = {
            format: "A4",
            orientation: "portrait",
            border: "5mm"
        };
        var document = {
            template: html,
            context: {
                options: {
                    brand: config.brand,
                    imgSrc: config.img,
                    modelName: config.modelName,
                    modelDescription: config.modelDescription
                }
            },
            path: "assets/output/"+fileName+".pdf"
        };

        var hostedFile = "/assets/output/"+fileName+".pdf";

        pdf.create(document, options).then(function() {
            res.download(hostedFile, fileName + '.pdf', function() {
                fs.unlink(hostedFile, function (err) {
                    if (err) {
                        console.error(err.toString());
                    } else {
                        console.warn(hostedFile + ' deleted');
                    }
                });
            });
        });
     });

这有什么问题?它返回给我这个控制台堆栈,浏览器显示Download failed (No file)

[Tue Mar 13 2018 13:41:47 GMT+0000 (UTC)] "GET /assets/output/my_file.pdf" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"
[Tue Mar 13 2018 13:41:47 GMT+0000 (UTC)] "GET /assets/output/my_file.pdf" Error (404): "Not found"

提前谢谢!

0 个答案:

没有答案