0

I am trying to download a pdf file from a API to a local file

The way i am doing it is by make an axios call for the pdf.

This is my request:

const axiosInstance = createAxios();
const response = await axiosInstance.get('https://www.getpdf.com',
{
    headers: {
        responseType: 'arraybuffer'
    },
})

here is some of the response i am getting

    %PDF-1.3
1 0 obj
[/PDF /Text /ImageB /ImageC /ImageI]
endobj
14 0 obj
<< /Length 3324 /Filter /FlateDecode >> stream 
X   �[ms۸�ޙ���v� �\;�I���^.��}��t���h��D�$e���O܇>x!ڒ3�,�ϳ�]�o��_g4��&yF�4�4�{[���|�K�~    *IXшĒJ6|��59��    c���D�o{GD��<���'%$�Hcn��9y���-ۢ������?��O����$H�/(J��'(�i�&�����#I?)噈()&p���ư9�,c��òxoQ)8��URb���q1��O��B)�[�%��RZ� VZ�z5n���x�:��1{��e'I�l&����d'�2��B���(�E�4�����$iF%ޕ柋Uy��$���YI2F3q���TN�,���-�ju�S�itȔ&"�t�$�d���L��piL�ڴ�Qv��TzdD��$?v��IF#�į>�7e{�"�<��Q'T�x�vLj(�U�^�p�S���1 f/��%��8��@�kn�۪����qQ�Ne��Td�)��Z���j���W?_�9ěL��ě̥Nz'xK�V3��u�2�$Rj�ͺ(�g�'=�(�H�D4Wx'ϭ5�<�Zb3;�����mj���`ʒI"��c"(sۏg&:*���44NIdRr�������e�oS����&4�����2íu��#�Y꒘&f۽�o�}T�aoG�8ɘ�,ۓ����F�{�=�P�M�#%�i.-W�X=y[.�ʮ
�%e�<��-��%�hf�UY��yFH�P`"ϰ>?I�]j�� ��W�UA~(ݦ#?]�n��   �"���>�
�o�U]�[%��=@d�gy:�"FS뵚�#D�\�Sy� ��'|"�"4=Y�����/���32a"f�E)�Rt�g�\*�]q$M$n�*��:��~qd���bH�P߄Go�D.�{�Rr�u���d|�a�̒�SgIt��rkMf�s�'���Ew���'q�҃<��o|ڡ^pT��Pl��w���vY-����q69M[�۬����_���q

Now i am trying to save this file. I tried every method i can like:

  fs.writeFileSync(__dirname+'/my.pdf', response.data);

or

fs.createWriteStream(__dirname+'/my.pdf').write(response.data);

or

  fs.writeFile(__dirname+'/temp/my.pdf', response.data, 'binary', function (err) {
      console.log(err);
  });

or

  fs.writeFile(__dirname+'/temp/my.pdf', response.data, 'base64', function (err) {
      console.log(err);
  });

The problem is the PDF is saving as a blank white document. I tried it on postman and the file saves properly, so i know its not that the response is corrupt.

Really would appreciate help

Mika
  • 31
  • 5

1 Answers1

0

The link you have provided is not to a .pdf file so I am using VSCode keyboard shortcut as an example.

I am also not using Axios but Node.js libraries directly.

This example downloads the shortcut pdf and saves it locally as output.pdf.

const fs = require('fs');
const https = require('https');


const url = 'https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf';

const output = fs.createWriteStream('output.pdf');
https.get( url, (res) => {
  // console.log('statusCode:', res.statusCode);
  // console.log('headers:', res.headers);

  res.pipe(output);

}).on('error', (e) => {
  console.error(e);
});
Hitesh Lala
  • 271
  • 1
  • 8
  • The url I posted is a fake link, but the real url returns a PDF like in the question. Though it’s not a url to an actual .pdf.. it’s a url to a endpoint which the endpoint response is content-disposition': 'attachment;filename=944883.pdf. I tried your solution in my case and it doesn’t work – Mika Dec 10 '21 at 06:40