从js api返回的PDF为空

问题描述 投票:0回答:1

我正在使用 handlebars & puppeteer 在我的 express apiserver 端生成一个 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);

我不知道我哪里出了问题。由于失眠症接收PDF很好,我认为是其客户端处理的问题。请大家帮忙。

javascript reactjs pdf handlebars.js puppeteer
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.