javascript – Working with PDF files on NodeJS server

Question:

Hi,

I have a service that when I make a request via postman, for example, I receive a .pdf file

I'm calling this service from a new nodeJS service, but I'm not able to get the .pdf to be returned in one call.

I get a string with the content "%PDF-1.3 \n%���� \n1 0 obj \n<< \n/Type /Catalog \n/Pages 2 0 R \n/PageMode…"

I perform communication between services using nodeJS request

return new Promise( async (resolve,reject) => {          
          request({
              headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + token
              },
              url: url,
              method: 'GET',
            }, function (error, response, body) {                    
              if (error) {
                reject(error);
              } else {
                resolve(response.body);
              } 
            });
      });
    }

And in my service I add the information in the header

.then((result) =>{                
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'form-data; name="arquivo.pdf";     filename="arquivo.pdf"');
    res.status(200).send(result) }

How can I make my service just the middle of the field between the service that makes the .pdf available and an ajax call?

I prefer to display this .pdf in the browser, or download it.

Answer:

Solution: The text was still displayed in string format due to request encoding

I removed Promise and went straight to the function, which called it. Added 'encoding': 'null' to request and changed setHeader. The call went like this:

    try{
        request({
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + token
            },
            url: url,
            method: 'GET',
            encoding: null
            }, function (error, response, body) {                    
            if (error) {
                logger.error("ERROR: " + error);
            } else {
                res.contentType("application/pdf");
                res.send(response.body);
            } 
        });
    }

To display it in the browser, I used XMLHttpRequest() making the response turn into a blob, from that with the URL.createObjectURL I opened the pdf in a new tab

Scroll to Top