I'm using pdfKit in my express server to generate a pdf with images (one image per page), I'm sending the Buffer pdfKit generates to the frontend so it can be downloaded, this is the handler for my /genpdf route:
res.setHeader('Content-Disposition', 'attachment; filename=mypdf.pdf');
res.setHeader('Content-Type', 'application/octet stream');
res.status(200).send(pdfBuffer) // this is the buffer generated by pdfKit
If I visit that route (/genpdf) directly on the navigator it works just fine, it opens the pdf (with the images, one per page) in a new tab.
However the issue comes when I want to make a downloadable url with that pdf buffer in my react app.
const res = await axios.get('/genpdf');
const url = window.URL.createObjectURL(new Blob([res.data]));
This generates a url, when I visit that url it opens a new tab with the pdf but all the pages are blank, so let's say I generated a pdf with 5 images, well it opens a pdf with 5 pages but they are all blank.
EDIT:
A detail I didn't realize is that if I open the console for the tab where the pdf with blank pages is open I can see theses messages from pdf.worker.js
Warning: Invalid absolute docBaseUrl: "blob:http://localhost:3000/3b38c310-f7a6-4950-b16b-e92369ddc810".
Warning: Indexing all PDF objects
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
and this one from viewer.js
PDF 538c033f41b7213bc8cc8e2c7c937518 [1.3 PDFKit / PDFKit] (PDF.js: 2.14.290)
and this one from from pdf.js
mozCurrentTransform is deprecated and will be removed in the future. Use CanvasRenderingContext2D.getTransform() or CanvasRenderingContext2D.setTransform() instead.
What I'm missing here?
CodePudding user response:
So assuming that what we are sending to the client is a Buffer (not an array buffer) and that we are using axios, we handle it this way:
const requestDocument = async () => {
const response = await axios.get('/getdocument', {
responseType: 'blob',
headers: {
'Content-Type': 'application/pdf'
}
})
const blob = new Blob([response.data], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
}
I didn't have to set special headers when sending the buffer, as I mentioned in my question the Buffer I send to the client is the one that pdfKit generates.