【问题标题】:how to convert a buffer to pdf on front end如何在前端将缓冲区转换为 pdf
【发布时间】:2021-06-24 18:16:48
【问题描述】:

我使用 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 缓冲区如下:

【问题讨论】:

    标签: javascript node.js reactjs puppeteer


    【解决方案1】:

    这在创建新 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();
    

    【讨论】:

    • 您的解决方案也对我有用。非常感谢:)
    【解决方案2】:

    在前端,您可以创建可以使用下载的 ObjectURL

    const 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();
    

    【讨论】:

      猜你喜欢
      • 2021-01-14
      • 2023-03-02
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      相关资源
      最近更新 更多