【问题标题】:Issues with open PDF files from my server从我的服务器打开 PDF 文件的问题
【发布时间】:2020-05-13 00:42:32
【问题描述】:

在打开/下载来自我的后端 (express) 的 pdf 时遇到问题。如果我手动转到 chrome (localhost:5000/test) 中的端点,它会打开并按应有的方式显示 PDF。如果在客户端中选择“保存并下载”,邮递员也可以正常工作。

来自后端的响应如下所示,据我了解,它是一个 PDF 流?如何从前端查看/下载它?我正在使用 React 和 Next。

%PDF-1.4
%����
1 0 obj
<</Creator (Chromium)
/Producer (Skia/PDF m79)
/CreationDate (D:20200127154327+00'00')
/ModDate (D:20200127154327+00'00')>>
endobj
3 0 obj
<</ca 1
/BM /Normal>>
endobj
5 0 obj
<</Type /XObject
/Subtype /Image
/Width 135
/Height 23
/ColorSpace /DeviceRGB
/SMask 6 0 R
/BitsPerComponent 8
/Filter /FlateDecode
/Length 69>> stream
x���
 ���7
���:���7)AR��I �$%HJ�� )AR��I    �$%HJ���7`�˫��
endstream
endobj
6 0 obj
<</Type /XObject
/Subtype /Image
/Width 135
/Height 23
/ColorSpace /DeviceGray
/BitsPerComponent 8
/Filter /FlateDecode
/Length 51>> stream

..... a lot more like this

PDF 文件已损坏,并显示错误 - 尝试打开 PDF 文件时无法加载 PDF 文档。我尝试将其转换为 base64 字符串,但打开它们时出现相同的错误。

前端功能由 onClick 运行

   const config: AxiosOptions = {
      route: 'test',
      method: 'GET'
    };
    const res = await makeAxiosRequest(config);
    console.log('res', res.data);

    const link = document.createElement('a');
    link.setAttribute('href', 'data:"application/pdf;' + res.data);
    link.setAttribute('download', 'bp.pdf');

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

后端(快递)

 const filename = __dirname + '/test.pdf';

    const readStream = fs.createReadStream(filename);
    const stat = fs.statSync(filename);

    res.setHeader('Content-Length', stat.size);
    res.setHeader('Content-type', 'application/pdf');
    res.setHeader(
      'Content-Disposition',
      'attachment; inline=test.pdf');

    // This will wait until we know the readable stream is actually valid before piping
    readStream.on('open', () => {
      // This just pipes the read stream to the response object (which goes to the client)
      readStream.pipe(res);
    });

    // This catches any errors that happen while creating the readable stream (usually invalid names)
    readStream.on('error', (err) => {
      res.end(err);
    });

【问题讨论】:

    标签: reactjs express pdf fs


    【解决方案1】:

    事实证明,我毕竟需要将 pdf 转换为 base64 字符串。 在后端做了这个

     const filename = __dirname + '/test.pdf';
     const base64PDF = fs.readFileSync(filename, { encoding: 'base64' });
    

    然后在前端这样做

    const link = document.createElement('a');
      link.setAttribute('href', 'data:"application/pdf;base64,' + res.data.base64PDF);
      link.setAttribute('download', res.data.name);
    
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 2014-01-03
      • 2012-01-24
      • 2019-02-10
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      相关资源
      最近更新 更多