diegomura / diegomura/react-pdf
renderToStream: NodeJS.ReadableStream will not complete, end event will not fire.
- Dominant language
- TypeScript
- Stars
- 16.8k
- Forks
- 1.3k
- Avg merge
- 5h 6m
- Merged PRs (30d)
- 52
Description
**Describe the bug**
I am trying to create a pdf file on my backend and then serve it to my front end for download. Since renderToString has been deprecated, I am forced to use renderToStream. Then convert the stream to a buffer to send back in the response. I've tried sending the stream back directly in the response object but it throws an error.
```
export const renderPDF = async () => {
// all the code that builds the pdf guts. "PDFComponent" is a react component that actually makes the pdf dom.
const pdfGuts = { ... };
const rootElemComponent: any = React.createElement(PDFComponent, pdfGuts);
return ReactPDF.renderToStream(rootElemComponent);
};
export const renderToBuffer = (stream: NodeJS.ReadableStream) => {
return new Promise(function (resolve, reject) {
const chunks: any[] = [];
stream.on("data", function (chunk: any) {
return chunks.push(chunk);
});
stream.on("end", function () {
return resolve(buffer.Buffer.concat(chunks));
});
stream.on("error", function (error: any) {
return reject(error);
});
});
};
@Get(":id/billOfLading")
@HttpCode(HttpStatus.OK)
@Header("Content-Type", "application/pdf")
@Header("Response-Type", "arraybuffer")
@Header("Response-Encoding", "binary")
async getDocument(@CurrentUser() user, @Param("id") id, @Res() res) {
const data: NodeJS.ReadableStream = await renderPDF();
// convert the stream to an array bufferl
const buffer = await renderToBuffer(data); // <-- Boom! never returns anything... just freezes.
// send the document to the client.
res.send(buffer);
}
```
in my renderToBuffer function, the "data" event triggers just fine for each chunk, however, when it's finished, the "end" event never fires. Nor does the "finish" event.
I have tried several different ways of reading the stream, I have tried renderToFile as well and it too freezes up. (I'm assuming it's the same problem internally when writing the file, reading the stream never triggers and end event.)
Any thoughts?
**To Reproduce**
See code above.
**Expected behavior**
I expect that the readable stream will actually finish when all the data has been read.
**Desktop (please complete the following information):**
- OS: Linux/PopOS
- Browser: Chrome, but this is internal to a NodeJS backend server
- React-pdf version: 3.4.2
- Node Version: v18.20.1
Contributor guide
Assessment
This issue has not been assessed yet.