Convert pdf stream into buffer

Viewed 378

I've a stream of pdf file which I need to convert into a buffer and I am tying to read the stream using stream.on but its not working and I keep getting error

UnhandledPromiseRejectionWarning: TypeError: stream.on is not a function

My stream starts looks like this

%PDF-1.3
%����
12 0 obj
<<
/BitsPerComponent 8
/ColorSpace /DeviceRGB
/Filter [/FlateDecode /DCTDecode]
/Height 117
/Length 2703
/Mask [ 253 255 253 255 253 255 ]
/Name /Obj0
/Subtype /Image
/Type /XObject
/Width 73
>>
stream

and it ends with

%%EOF

Here is my code

// api call
 instance.post(GENERATE_LABEL, strigifiedBody, { headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }, responseType: 'stream' } ).then(async (res) => {
      streamToString(res.data).then(async (strData) => {
          const stream = extractStreamFromResponse(res, strData);
        buffer = await getBuffer(stream);
        console.log(buffer);       
      });
    }).catch(err => {
        console.log(err);
    });

//function to extract stream from multipart/mixed data
  function extractStreamFromResponse(res, data) {
    let header = res.headers['content-type'];
    let boundary = header.split(' ')[1];
    boundary = boundary.split('=')[1];
    boundary = boundary.split('"')[1];
    const rawStream = data.split('--' + boundary)[2];
    const stream = rawStream.substring(100);
    return stream;
  }

  // function to get buffer from stream
  function getBuffer(stream) {
  const chunks = [];
  return new Promise((resolve, reject) => {
      stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
      stream.on('error', (err) => reject(err));
      stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
    })
  }

How can I create a buffer of this stream?

0 Answers
Related