Node.js二进制文件转换为PDF

3
我有一个Express服务器,可以创建PDF文件。
我正在尝试将此文件发送给客户端:

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

在客户端,我想要下载它:

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

    console.log(response);
  };

我收到一个类似于 body.text 的文本

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

但是我无法实现下载。

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

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 返回一个 Buffer,它是原始字节。你将这些原始字节发送回客户端,客户端将其记录到控制台。你会看到 body.text,这是预期的。你需要使用 fs.writeFile 或类似的方法将这些字节写入文件中。 - timothyclifford
请参考以下链接:https://dev59.com/7Ww05IYBdhLWcg3wXAmF - Chandrakant Thakkar
3个回答

1
结果是二进制字符串。我们使用base64将其转换为pdf。

var buffer = Buffer.from(result['textBinary'], 'base64') fs.writeFileSync('/path/to/my/file.pdf', buffer)


0

您可以通过设置正确的content-disposition头来提示浏览器下载文件:

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

0

readFile 返回一个 Buffer,它是字节的包装器。您将 Buffer 发送回客户端,客户端将其记录到控制台。

您看到的 body.text 是预期的结果。

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

_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

请注意!

另一个选择是在服务器上生成PDF文件,然后向客户端发送下载链接。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接