Yana Mazo
Yana Mazo

Reputation: 13

How to properly send pdf file generated on server-side to frontend

I have express app that serves the list of articles. My server generates pdf file for a selected article on a button click.

here is my backend code for making pdf-s

app.get("/generate-pdf/:articleHref", async (req, res) => {
  const articleHref = req.params.articleHref;
  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage();

  const { width, height } = page.getSize();

  page.drawText("HELLO", {
    x: 50,
    y: height - 50,
    size: 20,
    color: rgb(0, 0, 0),
  });
  const pdfBytes = await pdfDoc.save();

  const currentDate = DateTime.now().toFormat('yyyy-MM-dd'); 
  const fileName = `${articleHref}_${currentDate}`; 

  res.setHeader("Content-Type", "application/pdf");
  res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
  res.send(pdfBytes);
});

On the frontend side I listen button clicks and initiate pdf generation using this code

                const response = await fetch(`/generate-pdf/${articleHref}`, {
                    method: 'GET'
                });

                if (response.ok) {
                    const blob = await response.blob();

                    const url = window.URL.createObjectURL(blob);
                    const filename = response.headers.get('Content-Disposition').split('filename=')[1];
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = filename; // Use the filename received from the server

                    document.body.appendChild(link);
                    link.click();

                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);

I get the file to my "Downloads" folder with proper naming and type .pdf But I can't open it because it's broken.

I checked blob.type (application/pdf), content-type header (application/pdf, utf-8) I saved pdf file locally on the server side using fs.writeFileSync(filePath, pdfBytes) - it opened fine. But as soon as I'm trying to generate and get the file from my frontend - the file is broken.

What could be a reason? TIA

Upvotes: 0

Views: 522

Answers (1)

David R
David R

Reputation: 15667

Try passing the blob type that you receive in your await call by changing the below line,

const url = window.URL.createObjectURL(blob);

as

const blobObj = new Blob([blob], { type: blob.type });
const url = window.URL.createObjectURL(blobObj);

Upvotes: 0

Related Questions