1

我试图让以下工作,我有一个 GET REST 请求命中一个运行的端点receipt。我从下面没有收到任何错误,但是当我检查返回的 blob 但没有显示我添加的文本时。

var PDFDocument = require('pdfkit');

// User Receipt
exports.receipt = function(req, res) {
    var guid = req.params.guid;
    console.log(guid);

    var doc = new PDFDocument();
    var stream = doc.pipe( res );

    doc.moveTo(300, 75)
       .lineTo(373, 301)
       .lineTo(181, 161)
       .lineTo(419, 161)
       .lineTo(227, 301)
       .fill('red', 'even-odd');  

    var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';  

    doc.y = 320;
    doc.fillColor('black')
    doc.text(loremIpsum, {
       paragraphGap: 10,
       indent: 20,
       align: 'justify',
       columns: 2
    });  

    doc.end();
    res.setHeader('Content-Type', 'application/pdf');

    stream.on('finish', function() {
        stream.pipe(res);
    });
};

客户端我有以下代码:

var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);

但是页面返回Failed to load PDF document.

4

1 回答 1

1

您应该在管道之前设置标题。此外,你应该只管res一次。

var PDFDocument = require('pdfkit');

// User Receipt
exports.receipt = function(req, res) {
    var guid = req.params.guid;
    console.log(guid);

    var doc = new PDFDocument();

    doc.moveTo(300, 75)
       .lineTo(373, 301)
       .lineTo(181, 161)
       .lineTo(419, 161)
       .lineTo(227, 301)
       .fill('red', 'even-odd');  

    var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';  

    doc.y = 320;
    doc.fillColor('black')
    doc.text(loremIpsum, {
       paragraphGap: 10,
       indent: 20,
       align: 'justify',
       columns: 2
    });
    doc.end();

    res.setHeader('Content-Type', 'application/pdf');
    return doc.pipe(res);
};
于 2016-11-14T20:13:08.557 回答