Question

I am using PDFKit and socket.io in a node.js project to generate a pdf when a user clicks a button on the front end. How do I stream or otherwise send the resulting pdf to the end-user from here? I'd rather avoid saving the file to the file system and then having to delete it later if I can... hoping to stream it somehow.

socket.on('customerRequestPDF', function(){              
    doc = new PDFDocument;        

    doc.text('Some text goes here', 100, 100);

    //I could do this but would rather avoid it
    doc.write('output.pdf');

    doc.output(function(string) {
        //ok I have the string.. now what?

    });

});
Était-ce utile?

La solution

A websocket isn't really the appropriate mechanism to deliver the PDF. Just use a regular HTTP request.

// assuming Express, but works similarly with the vanilla HTTP server
app.get('/pdf/:token/filename.pdf', function(req, res) {
    var doc = new PDFDocument();
    // ...

    doc.output(function(buf) { // as of PDFKit v0.2.1 -- see edit history for older versions
        res.writeHead(200, {
             'Content-Type': 'application/pdf',
             'Cache-Control': 'private',
             'Content-Length': buf.length
        });
        res.end(buf);
    });
});

Now a word of warning: This PDF library is broken. As of version 0.2.1, the output is a proper Buffer, but it uses the deprecated binary string encoding internally instead of Buffers. (Previous versions gave you the binary-encoded string.) From the docs:

'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

This means that when node removes the binary string encoding, the library will stop working.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top