Puppeteer:生成后发送PDF供下载



因此,使用puppeteer,我将在服务器中生成pdf,它运行正常,但我还想添加另一个功能,在生成pdf后,我将文件发送回用户,并通过API开始下载。

这是我的功能:

function createPdf async (req, res) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://localhost:3000', {
timeout: 10000,
waitUntil: ['load', 'domcontentloaded', 'networkidle0', 'networkidle2'],
});
await page.pdf({
path: `./invoices/${Math.random()}.pdf`,
landscape: false,
format: 'A4',
margin: {
top: '0px',
right: '0px',
bottom: '0px',
left: '0px',
},
});
await browser.close();
if (page)
res.status(200).send({
success: true,
});
},

我该怎么做?

在您的服务器中暴露这个端点

app.post(“/downloadPdfHere”, async (req, res, next) => {
res.contentType("application/pdf");
try {
const pdf = await yourGenerator()
res.send(pdf);  //This will generate a array buffer stream
} catch (error) {
console.error(error);
}
});

在您的UI中,尝试使用以下命令启动下载

downloadFile = async (url, headers, body ) => {
const response = await axios.request({
method: 'post',
url,
data: body,
headers,
responseType: 'arraybuffer'
});
const downloadurl = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = downloadurl;
// TODO for naming the response can have wins in headers
link.setAttribute('download', 'file.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
};

this.downloadFile( '/downloadPdfHere', headers, body).then(()=>{
//do anything
});

最新更新