使用流输出pdf

时间:2016-06-14 15:41:40

标签: express pdfmake

如何使用expressjs输出pdf:

var fs = require('fs');
var PdfPrinter = require('pdfmake/src/printer');

app.get('/', function (req, res) {
    var printer = new PdfPrinter();

    var first = 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines';

    var dd = {
        content: [
            first,
            'Another paragraph'
        ]
    };
    var pdfDoc = printer.createPdfKitDocument(dd);
    pdfDoc.pipe(fs.createWriteStream('basics.pdf')).on('finish',function(){
        //success

    });
    pdfDoc.end();
});

1 个答案:

答案 0 :(得分:3)

您可以将输出传输到res(确保设置正确的Content-Type后):

app.get('/', function (req, res) {
  var printer = new PdfPrinter();
  var first   = 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines';
  var dd      = {
    content: [
      first,
      'Another paragraph'
    ]
  };

  // Make sure the browser knows this is a PDF.
  res.set('content-type', 'application/pdf');

  // Create the PDF and pipe it to the response object.
  var pdfDoc = printer.createPdfKitDocument(dd);
  pdfDoc.pipe(res);
  pdfDoc.end();
});

(虽然我不能说它为我提供了清晰的PDF,但是当运行独立的任何pdfmake示例时,代码也没有?