【问题标题】:Meteor: Dynamic pdf generation with pdfKit and FlowRouterMeteor:使用 pdfKit 和 FlowRouter 生成动态 pdf
【发布时间】:2016-08-20 09:13:14
【问题描述】:

我在我的流星应用程序上使用 pdfKit 和 FlowRouter。我想生成一个 pdf 文件而不将其保存在服务器上。在文档中有一个例子:

Router.route('/getPDF', function() {
 var doc = new PDFDocument({size: 'A4', margin: 50});
 doc.fontSize(12);
 doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
 this.response.writeHead(200, {
 'Content-type': 'application/pdf',
 'Content-Disposition': "attachment; filename=test.pdf"
 });
 this.response.end( doc.outputSync() );
 }, {where: 'server'});

但这是用于 Iron Router 的。由于我使用的是 FlowRouter,我不知道如何在不将文件保存在服务器上的情况下直接向用户显示/下载 pdf。

【问题讨论】:

    标签: meteor pdf-generation flow-router


    【解决方案1】:

    使用来自 meteorhacks picker 的服务器端路由器。然后类似于

    Picker.route('/generate/getPdf', function(params, req, res, next) {
        var doc = new PDFDocument({size: 'A4', margin: 50});
        doc.fontSize(12);
        doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=test.pdf'
        });
        res.end(doc.outputSync());
    });
    

    更新:现在 outputSync 已弃用,请使用:

    Picker.route('/generate/getPdf', function(params, req, res, next) {
        var doc = new PDFDocument({size: 'A4', margin: 50});
        doc.fontSize(12);
        doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=test.pdf'
        });
        doc.pipe(res);
        doc.end();
    });
    

    【讨论】:

    • 如果我在浏览器中输入localhost:3000/generate/getPdf,效果会很好。但是,如果我使用指向同一目标的链接,则会收到错误消息,即路线不存在(单击链接)。单击后,我必须刷新才能获取文件。我不明白。
    • 试试这个:<a href="/generate/getPdf" download="">
    • outputSync() 方法似乎已被弃用(我猜它使用起来太方便了),我无法理解我们如何使用它 nom :(
    • 正如上面提到的 fabien,outputSync 已经不复存在了。我们现在怎么做?
    • 我从未使用过 pdfKit。你应该使用什么方法来代替outputSync?是基于承诺还是回调?
    【解决方案2】:

    现在 outputSync() 已被删除,以下是如何执行此操作:

    Picker.route('/generate/getPdf', function(params, req, res, next) {
        var doc = new PDFDocument({size: 'A4', margin: 50});
        doc.fontSize(12);
        doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=test.pdf'
        });
      doc.pipe(res);
      doc.end(res);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-18
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2017-06-14
      相关资源
      最近更新 更多