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

2

17

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');
Chlorella answered 17/2, 2015 at 18:44 Comment(3)
Instead of using a bunch of extra streams, why not just do res.write(fileBase64String, 'base64') ?Wendelin
Yeah, thanks, updated the question :) I can see the response status OK on the client side, but file is never being saved.Chlorella
If that's all you are writing, use res.end(fileBase64String, 'base64'), which will both write the data and close the response.Wendelin
T
20

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.

Terrilynterrine answered 6/3, 2017 at 13:2 Comment(0)
P
0

Just a reference for Express. This answer is based on ofhouse's answer.

This solution is downloading a png file. I was missing the "Content-Disposition" part, which makes the browser not display the png, but download it. png is a Buffer-object.

app.get("/image", (req, res) => {
    getPng()
      .then((png) => {
        res.writeHead(200, {
          "Content-Type": png.ContentType,
          "Content-Length": png.ContentLength,
          "Content-Disposition": 'attachment; filename="image.png"',
        });
        res.end(png.Body);
      })
      .catch(() => {
        res.send("Couldn't load the image.");
      });
});
Pyrometer answered 3/3, 2021 at 18:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.