Skip to content

Instantly share code, notes, and snippets.

@abusedmedia
Forked from andrei-tofan/example.js
Created October 1, 2021 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abusedmedia/c19748bfac9ea2c6989ffd75d772f61f to your computer and use it in GitHub Desktop.
Save abusedmedia/c19748bfac9ea2c6989ffd75d772f61f to your computer and use it in GitHub Desktop.
node.js writable buffer stream (pdfkit example)
/**
* 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'));
});
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