【问题标题】:PDF returned from js api emptyjs api返回的PDF为空
【发布时间】:2020-06-06 22:12:54
【问题描述】:

我正在使用车把和 puppeteer 在我的 express api/服务器端生成 PDF 报告。使用 insomnia 触发 API,它返回一个完整的 PDF,完全符合我的预期。当我让客户端 React 应用程序下载它时,它会保存正确数量的页面,但为空。我尝试了多种下载文件的方法,API 端的标头。这是当前代码。

前端:

const res = await getDashboard(company, category, country, endDate, startDate);
const blob = new Blob([res], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'amazon.pdf';
a.click();

服务器端:

const pdf = await genReport(data);
res.contentType('application/pdf');
res.header('Pragma', 'public');
res.header('Cache-Control', 'max-age=0');
res.setHeader('Content-disposition', 'attachment;filename=AmazonReport.pdf');
res.type('application/pdf');
res.send(pdf);

我不确定我哪里出错了。由于 insomnia 收到 PDF 格式的罚款,我假设它的客户端处理。请帮忙。

【问题讨论】:

  • 发送文件总是很痛苦。您是否尝试过先在后端对其进行 base64 编码,然后在前端将其解码为二进制? stackoverflow.com/questions/51981473/…
  • @georgedum 我不得不费力地研究如何在 typescript 中转换为 base64,但这已经解决了!感谢您的帮助!

标签: javascript reactjs pdf handlebars.js puppeteer


【解决方案1】:

@georgedum 在这里为我指明了正确的方向,问题现已解决。这是更新/修复的代码: 客户端:

const res = await getDashboard(company, category, country, endDate, startDate);
const binaryString = window.atob(res);
const binaryLen = binaryString.length;
const bytes = new Uint8Array(binaryLen);
for (let i = 0; i < binaryLen; i++)
{
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
}
const blob = new Blob([bytes], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'amazon.pdf';
a.click();

服务器端:

const pdf = await genReport(data);
const encodedPdf = Buffer.from(pdf).toString('base64');
res.contentType('application/pdf');
res.header('Pragma', 'public');
res.header('Cache-Control', 'max-age=0');
res.setHeader('Content-disposition', 'attachment;filename=AmazonReport.pdf');
res.type('application/pdf');
res.send(encodedPdf);

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2017-08-30
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多