6

I am getting the attachment body using the Rest API.

var config = {
                method: 'get',
                url: '<Domanin>/services/data/v48.0/sobjects/Attachment/00PD000000HQD68MAH/Body',
                headers: {
                    'Authorization': `Bearer ${
                        accessToken
                    }`,
                    'content-type':'application/pdf'
                },
            };

       let rawData = await axios(config);
       rawData = rawData.data


I am getting the PDF data in this format

%PDF-1.5
%ÓôÌá
1 0 obj
<<

In the client side I am trying to make this as a downloadable file but I am getting blank pdf. The actual pdf contains 2 pages the downloaded pdf contains two pages as well but they are blank.

Client Side Code:

 var downloadLink = document.createElement('a');
            downloadLink.target = '_blank';
            downloadLink.download = 'test.pdf';

            // convert downloaded data to a Blob
            var blob = new Blob(([rawData]), {type: 'application/pdf'});

            // create an object URL from the Blob
            var downloadUrl = URL.createObjectURL(blob);

            // set object URL as the anchor's href
            downloadLink.href = downloadUrl;

            // append the anchor to document body
            document.body.append(downloadLink);

            // fire a click event on the anchor
            downloadLink.click();

Please let me know what is wrong with the above logic

Amaresh S M
  • 2,936
  • 2
  • 13
  • 25

1 Answers1

0

Please specify responseType: 'arraybuffer' in request config. Modify your config object to

{
                method: 'get',
                url: '<Domanin>/services/data/v48.0/sobjects/Attachment/00PD000000HQD68MAH/Body',
                headers: {
                    'Authorization': `Bearer ${
                        accessToken
                    }`
                },
                'responseType': 'arraybuffer'
            };
vishesh
  • 2,007
  • 6
  • 32
  • 67