Access PDF from Buffer stream using Next.js without any library
I am going to explain how to access a PDF from a buffer stream without any external libraries.
In my case, the buffer stream is coming from the API end and processing the PDF stream in Next.js code.
I have created the below handler function to process PDF stream data from the API.
I have passed required parameters to the separate API services file and set up required response headers.
The above one is my API services file, and I passed the required params and Axios response type added as ArrayBuffer because in my case, the PDF response type is ArrayBuffer, and if the response is Blob, then we need to set it as Blob as the Axios response.
I updated my API file header content-type as ‘application/pdf and response type as ‘arraybuffer’ like below:
Then I set up my handler function header and response types like below:
I updated content-type to ‘application/pdf’ andupdated the file name. I used the Buffer.from() method and passed the API buffer stream, and the Buffer.from() method creates a new buffer filled with the specified string, array, or buffer.
Finally, I called the created handler in my PdfDocument.tsx file like below with the required header and response type.
Once the response is received from the API, then a new blob is created with the required response data.
I used an iframe to display the PDF in the browser as shown below:
Finally, a browser window opens up with the PDF we expected.
So, without any PDF library, we can show PDFs to use this way!