search

Home  >  Q&A  >  body text

How to convert buffer to file when downloading on React side

<p>I'm using<a href="https://www.npmjs.com/package/convert-html-to-pdf">https://www.npmjs.com/package/convert-html -to-pdf</a> to convert html to pdf in nodejs. I have a react frontend and nodejs backend. I want to convert the buffer into a file to be downloaded by the user on the react side. What should I do? I don't want to save the file on my server. </p>
P粉006847750P粉006847750518 days ago641

reply all(1)I'll reply

  • P粉020556231

    P粉0205562312023-09-02 19:51:17

    We can set the header Content-disposition attachment to indicate that the response is a downloadable file.

    Backend: Express Example

    const htmlToPDF = new HTMLToPDF(`
      <div>Hello world</div>
    `);
    
    const buffer = await htmlToPDF.convert();
    
    res.set("Content-Disposition", `attachment; filename="test.pdf"`);
    res.set("Content-Type", "application/pdf");
    
    res.send(buffer);

    Front end: React example

    const submit = () => {
      window.open("http://localhost:8000"); // 在此处填写您的端点
    };
    
    return (
      <button onClick={submit}>下载</button>
    );

    If the endpoint is a POST method, window.open will not work. We have to use a form:

    <form action="http://localhost:8000" method="POST">
      <button type="submit">下载</button>
    </form>

    reply
    0
  • Cancelreply