简体   繁体   English

Node.js 二进制文件到 PDF

[英]Node.js binary to PDF

I have got a express server, which creates a pdf file.我有一个快速服务器,它创建一个 pdf 文件。

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我收到一个 body.text 像

 %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?如何从数据创建 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:我只是让浏览器使用 html 锚标记处理下载:服务器:

 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>

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

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

readFile returns a Buffer which is a wrapper around bytes. readFile返回一个Buffer ,它是围绕字节的包装。 You're sending Buffer back to the client which is logging them to the console. 您正在将Buffer发送回客户端,然后将其记录到控制台。

The body.text you see is to be expected. 您看到的body.text是预期的。

You will need to write these bytes to a file using fs.writeFile or similar. 您将需要使用fs.writeFile或类似文件将这些字节写入文件。 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 . 您可能需要试验缓冲区编码,默认为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. 您可能要考虑的另一种选择是在服务器上生成PDF,然后只需向客户端发送链接即可下载该链接。

The result is the string of the binary.结果是二进制的字符串。 We use base 64 to convert from binary to pdf我们使用base 64从二进制转换为pdf

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM