如何在前端将缓冲区转换为pdf

2024-01-06

我使用 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");

The console.log缓冲区如下:


这在创建新的 Blob 时对我有用。我能够以这种方式使用 Shankar 的代码。

new Blob([new Uint8Array(this.props.resumePDF.data).buffer]);

// e.g. pass the array - new Blob([new Uint8Array([1,2,3,4]).buffer]);
const url = window.URL.createObjectURL(new Blob([new Uint8Array(this.props.resumePDF.data).buffer]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'yourcoolpdf.pdf');
document.body.appendChild(link);
link.click();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在前端将缓冲区转换为pdf 的相关文章

随机推荐