Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js - how to download base64 string as PDF file?

I have pdf file encoded as base64 string. How to download this string to the browser as file in .pdf format?

What I have already tried:

res.set('Content-Disposition', 'attachment; filename="filename.pdf"');
res.set('Content-Type', 'application/pdf');

res.write(fileBase64String, 'base64');
like image 633
Tomas Avatar asked Feb 17 '15 18:02

Tomas


People also ask

Can PDF be Base64?

💻 Can I convert PDF to BASE64 on Linux, Mac OS or Android? Yes, you can use free Converter app on any operating system that has a web browser. Our PDF to BASE64 converter works online and does not require any software installation.


1 Answers

I ended up to decode the pdf first and then send it to the browser as binary as follows:

(For simplicity I use node-http here but the functions are available in express as well)

const http = require('http');

http
  .createServer(function(req, res) {
    getEncodedPDF(function(encodedPDF) {
      res.writeHead(200, {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment; filename="filename.pdf"'
      });

      const download = Buffer.from(encodedPDF.toString('utf-8'), 'base64');

      res.end(download);
    });
  })
  .listen(1337);

What drove me nuts here was the testing with Postman:
I was using the Send Button instead of the Send and Download Button to submit the request:enter image description here

Using the Send button for this request causes that the pdf file becomes corrupted after saving.

like image 164
ofhouse Avatar answered Sep 24 '22 05:09

ofhouse