Node.js |通过从DB(页面方式)读取数据生成pdf并将其作为单个可下载的pdf

时间:2016-01-06 11:30:45

标签: node.js pdf stream

我的数据库包含600000行。我必须从数据库页面明智地读取数据(1000条记录页面)。然后动态生成pdf并使用node.js

将其作为可下载的pdf流式传输

1 个答案:

答案 0 :(得分:1)

我在示例Hello世界代码中完成了它。

来自链接的想法: Serve dynamically generated PDF with remote images in Node.js

这是我的代码。

var express = require('express'),
  request = require('request'),
  expressJSON = require('express-json'),
  pdfDocument = require('pdfkit');

// Start Express
var app = express();

// Use JSON in POST body
app.use(expressJSON());

// Setup POST response
app.get('/post_pdf', function(req, res) {
  // Create PDF
  var doc = new pdfDocument();

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

  // Pipe generated PDF into response
  doc.pipe(res);

  // Process image
  request({
    url: 'http://dummyimage.com/640.jpeg',
    encoding: null // Prevents Request from converting response to string
  }, function(err, response, body) {
    if (err) throw err;
    var idx =0;

    var fource2Stream = function(){
      idx++;
      if(idx >= 10) {
        doc.end(); // Close document and, by extension, response
        return;
      }

      doc.addPage();
      // Inject image
      doc.image(body); // `body` is a Buffer because we told Request
                       // to not make it a string
      doc.addPage();
      doc.text ('Hello world!', 100, 100);

      doc.addPage();
      doc.text('Hello world!', 100, 100);

      doc.flushPages();
      setTimeout(fource2Stream, 5000);
    };

    fource2Stream();
    return;
  });
});

app.listen(8080);