How to convert buffer to file when downloading on React side
P粉006847750
P粉006847750 2023-09-01 23:23:15
0
1
613
<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粉006847750
P粉006847750

reply all(1)
P粉020556231

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template