Node.js binary to PDF

假如想象 提交于 2021-02-19 06:48:13

问题


I have got a express server, which creates a pdf file.

I am trying to send this file to the client:

const fs = require('fs');

function download(req, res) {
  var filePath = '/../../myPdf.pdf';

  fs.readFile(__dirname + filePath, function(err, data) {
    if (err) throw new Error(err);
    console.log('yeyy, no errors :)');

    if (!data) throw new Error('Expected data, but got', data);
    console.log('got data', data);

    res.contentType('application/pdf');
    res.send(data);
  });
}

On the client I want to download it:

  _handleDownloadAll = async () => {
    console.log('handle download all');
    const response = await request.get(
      `http://localhost:3000/download?accessToken=${localStorage.getItem(
        'accessToken'
      )}`
    );

    console.log(response);
  };

I recieve an body.text like

%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Producer (��Qt 5.5.1)↵

but I can't achieve a download.

How can I create a PDF from the data OR directly download it from the server?

I've got it working: The answer was pretty simple. I just let the browser handle the download with an html anchor tag: server:

function download(req, res) {
  const { creditor } = req.query;
  const filePath =  `/../../${creditor}.pdf`;

  res.download(__dirname + filePath);
}

client:

<a href{`${BASE_URL}?accessToken=${accessToken}&creditor=${creditorId}`} download>Download</a>

回答1:


You can prompt the browser to download the file by setting the correct content-disposition header:

res.setHeader('Content-disposition', 'attachment; filename=myfile.pdf');



回答2:


readFile returns a Buffer which is a wrapper around bytes. You're sending Buffer back to the client which is logging them to the console.

The body.text you see is to be expected.

You will need to write these bytes to a file using fs.writeFile or similar. Here's an example:

_handleDownloadAll = async () => {
  console.log('handle download all');
  const response = await request.get(
    `http://localhost:3000/download?accessToken=${localStorage.getItem(
      'accessToken'
    )}`
  );

  // load your response data into a Buffer
  let buffer = Buffer.from(response.body.text)

  // open the file in writing mode
  fs.open('/path/to/my/file.pdf', 'w', function(err, fd) {  
    if (err) {
        throw 'could not open file: ' + err;
    }

    // write the contents of the buffer
    fs.write(fd, buffer, 0, buffer.length, null, function(err) {
      if (err) {
        throw 'error writing file: ' + err;
      }
      fs.close(fd, function() {
          console.log('file written successfully');
      });
    });
  });
};

You may need to experiment with the buffer encoding, it defaults to utf8.

Read this!

The other option you may want to consider is generating the PDF on the server and simply sending the client a link to where it can download this.



来源:https://stackoverflow.com/questions/47713857/node-js-binary-to-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!