Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding PDF binary data to base64 not working with NodeJS

I'm trying to get a PDF stream return that comes from a API and parse it to base64 to embbed it in the client side, the body of the API request is returning something like this:

    %PDF-1.5
%����
4 0 obj
<<
/Type/XObjcect
/Subtype/Image
/Width 799
/Height 70
/ColorSpace/DeviceGray
/BitsPerComponent 8
/Filter/FlateDecode
/Length 5181
>>
stream
x���=H#�������A�&�)���B���4iba�&O8H
.
.
. 
(The rest was omitted)

I'm trying to parse to base64 this way:

console.log(typeof body); // STRING
const encoded = new Buffer.from(body).toString('base64'); //PDF NOT WORKING

But when I'm getting this base64 and embedding it on the html it says that the file can't be oppened, the same thing happens when I trying to save it as .PDF file.

When I try to parse to base64 the same pdf but this time from a downloaded pdf, the base64 code when embedded in the html works fine.

  fs.readFile('/home/user/downloaded.pdf', function (err, data) {
    if (err) throw err;

    console.log(typeof data); //OBJECT
    const pdf = data.toString('base64'); //PDF WORKS
  });

I'm using const request = require('request'); to make the requests.

like image 475
Loading... Avatar asked May 14 '17 19:05

Loading...


People also ask

Can you Base64 encode a PDF?

Base64 encoding is used to encode binary data, such as a PDF file, into an ASCII string format that is compatible with systems that can only handle text. For example, email attachments and binary uploads in HTML forms are converted and transmitted as Base64 encoded data.

Why is BTOA deprecated?

btoa(): accepts a string where each character represents an 8bit byte. If you pass a string containing characters that cannot be represented in 8 bits, it will probably break. Probably that's why btoa is deprecated.

Can Base64 encode binary?

Fundamentally, Base64 is used to encode binary data as printable text. This allows you to transport binary over protocols or mediums that cannot handle binary data formats and require simple text. [ Download now: A sysadmin's guide to Bash scripting. ] Base64 uses 6-bit characters grouped into 24-bit sequences.

Is BTOA same as Base64?

The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).


1 Answers

When you make your request you should set option encoding to null for getting Buffer instead of String.

request({
    method: 'GET',
    encoding: null,
    uri: 'http://youdomain.com/binary.data'
}, (err, resp, data)=>{
    console.log(typeof data) //should be an Object
    console.log(data.toString('base64'))
})
like image 183
h0x91B Avatar answered Oct 04 '22 02:10

h0x91B