使用Node.js中的远程图像提供动态生成的PDF

时间:2014-04-05 22:06:10

标签: javascript node.js express node-pdfkit

我正在尝试创建一个使用PDFKit即时生成PDF的节点服务器。 PDF是根据POST请求中的参数生成的(通过Express)。其中一个参数指定了一个图像URL,服务器将其下载并注入到PDF中。

现在,我有以下结构:

// Get dependencies
var express = require('express'),
http = require('http'),
fs = require('fs'),
pdfDocument = require('pdfkit');

// Get express started.
var app = express();

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

// Setup POST response
app.post('/post_pdf', function(req, res) {
    // Get the PDF initialized
    var doc = new pdfDocument();

    // Set some headers
    res.statusCode = 200;
    res.setHeader('Content-type', 'application/pdf');
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Header to force download
    res.setHeader('Content-disposition', 'attachment; filename=Untitled.pdf');     

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

    /**
     * Generate PDF contents
     */

    // Prepare write stream for image
    var image = fs.createWriteStream('image.jpeg');

    // Download image
    http.get("http://dummyimage.com/640.jpeg", function(response) {

        // Pipe response into image write stream
        // (because PDFKit needs to read from a saved file)
        response.pipe(image).on('close', function() {

            // Read data back, make sure there are no errors
            fs.readFile('image.jpeg', function(err, data) {
                if (err) throw err;

                /**
                 * Use `data` to get image info (width, height, etc.)
                 * ------------------
                 * Inject image
                 */

                // Close document and response
                doc.end();
                res.end();
                return;
            })
        });
    });
});

我有两个问题:

  • 是否有一种不那么混乱的方式来实现这一点,也许有更少的嵌套回调?我完全愿意增加另一种依赖,让生活更轻松。
  • 现在,上面的代码不起作用。它返回PDF,但PDF已损坏(根据预览)。关于为什么会发生这种情况的任何提示都是非常受欢迎的。

2 个答案:

答案 0 :(得分:7)

在调试此问题时,我发现了几件事:

PDFKit无需从文件中读取信息。它还会接受Buffer

doc.image(myBuffer); // You don't have to use a path string

将文件直接送入回复时,如果文件已经关闭,手动调用response.end()会导致问题

doc.pipe(res); // Pipe document directly into the response

doc.end(); // When called, this ends the file and the response

// res.end(); <-- DON'T call res.end()
//                The response was already closed by doc.end()
return;

Request是一个超级有用的NodeJS库,可以展平回调树


更新的代码:

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

// Start Express
var app = express();

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

// Setup POST response
app.post('/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;

        // Inject image
        doc.image(body); // `body` is a Buffer because we told Request
                         // to not make it a string

        doc.end(); // Close document and, by extension, response
        return;
    });
});

答案 1 :(得分:0)

{{1}}