【问题标题】:express.js - create a new pdf and force the download, without saving it on serverexpress.js - 创建一个新的 pdf 并强制下载,而不将其保存在服务器上
【发布时间】:2015-07-15 13:01:58
【问题描述】:

我将 express.js 与 pdfkit 一起使用来生成 pdf 并强制下载给用户。为此,我使用了属于 express.js 的 res.download 函数。我也可以pipe 将pdf 转为res,但是下载不会开始。

好的,我的问题是什么:是否有可能以某种方式在服务器上创建 pdf 并将其存储在“内存中”或类似的东西?目前,我必须定义创建 pdf 的特定位置,然后从该位置读取并将其提供给用户。基本上,我想“跳过”保存到磁盘和从磁盘读取,但仍然强制用户下载。

也许我在这里不理解一些概念,所以任何形式的解释都非常感谢!

代码如下:

router.get('/pdf/:id', function(req, res) {
    Order._getById(req.params.id).
    then(function(order) {
        if (order !== null) {
            var doc = new PDFDocument();
            var result = order.toJSON();

            var products = result.products;
            var user = result.user;
            var comments = result.comments;

            doc.registerFont('arial', path.join(__dirname, '../fonts', 'arial' , 'arial.ttf'));         

            for (var i in products) {
                var product = products[i];
                doc.font('arial').text(product.name);
                doc.image(path.join(__dirname,'../uploads','thumb', product.picture), {scale: 1.0});
                doc.font('arial').text(product.price + ' €');
            }

            var r = doc.pipe(fs.createWriteStream(path.join(__dirname, '../uploads', 'out.pdf')));
            doc.end();

            r.on('finish', function(){
                //the response is a "forced" download of a file I had to save on the disk
                res.download(path.join(__dirname, '../uploads', 'out.pdf'));
            });

        } else {
            res.json(false);
        }
    });
});

同样,如果我不保存文件而只是这样做:doc.pipe(res); pdf 将在新选项卡中打开,而不是强制下载。

【问题讨论】:

    标签: node.js express pdf-generation


    【解决方案1】:

    我认为这就是答案...我可以将结果pipe 发送给客户端,但需要设置标题,即:

            res.writeHead(200, {
                'Content-Type': 'application/pdf',
                'Access-Control-Allow-Origin': '*',
                'Content-Disposition': 'attachment; filename=out.pdf'
            });
    

    【讨论】:

    • 同意,保存我使用 'res.setHeader('Content-type', 'application/pdf');'设置标题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多