我使用 Puppeteer 生成一个包含 pdf 信息的缓冲区并将其发送到前端。 这是后端api:
exports.getPDF = async (req, res) => {
const { content } = req.query;
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>HTML to PDF Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
${content}
</body>
</html>
`);
const buffer = await page.pdf();
await browser.close();
return res.apiResponse(buffer);
};
然后我尝试将缓冲区转换为pdf文件并打开它但失败了,它说无法加载PDF文档。
我在前端做了什么:
await dispatch({
type: 'resume/fetchResumePDF',
payload: {
content: resumeContent
}
});
console.log(this.props.resumePDF);
const file = new Blob(this.props.resumePDF.data, {
type: 'application/pdf'
});
const getFile = file && window.URL.createObjectURL(file);
window.open(getFile, "_blank");
console.log
缓冲区如下:
答案 0 :(得分:0)
在前端,您可以创建可以使用
下载的ObjectURLconst url = window.URL.createObjectURL(new Blob([this.props.resumePDF]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'yourcoolpdf.pdf');
document.body.appendChild(link);
link.click();