Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BLOB into PDF file in the Node environment?

I have a Node Js server, in it, I am fetching a blob data from another web service (which is for a PDF file), now after receiving blob, I want to convert it again into PDF file.

Anyone, who knows how to achieve this please help.

Here is my code block I have tried so far:

const fetch = require('node-fetch');
const Blob = require('fetch-blob');
const fs = require('fs');

fetch(url, options)
   .then(res => {
      console.log(res);
      res.blob().then(async (data) => {

         const result = data.stream();
         // below line of code saves a blank pdf file
         fs.createWriteStream(objectId + '.pdf').write(result);
      })
   })
   .catch(e => {
      console.log(e);
   });
like image 541
Mayank yaduvanshi Avatar asked Sep 01 '25 04:09

Mayank yaduvanshi


1 Answers

Modification points:

  • For fs.createWriteStream(objectId + '.pdf').write(data), please modify res.blob() to res.buffer().
  • Please modify .then(res => {res.blob().then() to .then(res => res.buffer()).then(.

Modified script:

fetch(url, options)
  .then(res => res.buffer())
  .then(data => {
    fs.createWriteStream(objectId + '.pdf').write(data);
  })
  .catch(e => {
    console.log(e);
  });

Note:

  • In this modification, it supposes that the fetch process using url and options works fine.

References:

  • node-fetch
  • write()
like image 56
Tanaike Avatar answered Sep 02 '25 19:09

Tanaike