-
-
Save abusedmedia/c19748bfac9ea2c6989ffd75d772f61f to your computer and use it in GitHub Desktop.
node.js writable buffer stream (pdfkit example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert PDFDocument to Base64 | |
*/ | |
const PDFDocument = require('pdfkit'); | |
const stream = require('./stream'); | |
// crate document and write stream | |
let doc = new PDFDocument(); | |
let writeStream = new stream.WritableBufferStream(); | |
// pip the document to write stream | |
doc.pipe(writeStream); | |
// add some content | |
doc.text('Some text!', 100, 100); | |
// end document | |
doc.end() | |
// wait for the writing to finish | |
writeStream.on('finish', () => { | |
// console log pdf as bas64 string | |
console.log(writeStream.toBuffer().toString('base64')); | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const stream = require('stream'); | |
/** | |
* Simple writable buffer stream | |
* @docs: https://nodejs.org/api/stream.html#stream_writable_streams | |
*/ | |
class WritableBufferStream extends stream.Writable { | |
constructor(options) { | |
super(options); | |
this._chunks = []; | |
} | |
_write (chunk, enc, callback) { | |
this._chunks.push(chunk); | |
return callback(null); | |
} | |
_destroy(err, callback) { | |
this._chunks = null; | |
return callback(null); | |
} | |
toBuffer() { | |
return Buffer.concat(this._chunks); | |
} | |
} | |
module.exports = { WritableBufferStream } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment