Node.js二进制转换为PDF [英] Node.js binary to PDF

查看:69
本文介绍了Node.js二进制转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个快递服务器,可以创建一个pdf文件.

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);
  };

我收到诸如

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

但是我无法下载.

如何从数据创建PDF或直接从服务器下载PDF?

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

我已经开始工作了答案很简单.我只是让浏览器使用html锚标记处理下载:服务器:

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);
}

客户端:

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

推荐答案

readFile 返回

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.

您所看到的body.text是预期的.

The body.text you see is to be expected.

您将需要使用 fs.writeFile 或类似方法将这些字节写入文件.这是一个示例:

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');
      });
    });
  });
};

您可能需要尝试使用缓冲区编码,默认为 utf8 .

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

阅读!

您可能要考虑的另一种选择是在服务器上生成PDF,然后只需向客户端发送链接即可下载该链接.

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.

这篇关于Node.js二进制转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆