pdfstream.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. /*!
  3. * Canvas - PDFStream
  4. */
  5. /**
  6. * Module dependencies.
  7. */
  8. var Stream = require('stream').Stream;
  9. /**
  10. * Initialize a `PDFStream` with the given `canvas`.
  11. *
  12. * "data" events are emitted with `Buffer` chunks, once complete the
  13. * "end" event is emitted. The following example will stream to a file
  14. * named "./my.pdf".
  15. *
  16. * var out = fs.createWriteStream(__dirname + '/my.pdf')
  17. * , stream = canvas.createPDFStream();
  18. *
  19. * stream.pipe(out);
  20. *
  21. * @param {Canvas} canvas
  22. * @param {Boolean} sync
  23. * @api public
  24. */
  25. var PDFStream = module.exports = function PDFStream(canvas, sync) {
  26. var self = this
  27. , method = sync
  28. ? 'streamPDFSync'
  29. : 'streamPDF';
  30. this.sync = sync;
  31. this.canvas = canvas;
  32. this.readable = true;
  33. // TODO: implement async
  34. if ('streamPDF' == method) method = 'streamPDFSync';
  35. process.nextTick(function(){
  36. canvas[method](function(err, chunk, len){
  37. if (err) {
  38. self.emit('error', err);
  39. self.readable = false;
  40. } else if (len) {
  41. self.emit('data', chunk, len);
  42. } else {
  43. self.emit('end');
  44. self.readable = false;
  45. }
  46. });
  47. });
  48. };
  49. /**
  50. * Inherit from `EventEmitter`.
  51. */
  52. PDFStream.prototype.__proto__ = Stream.prototype;