Corrupted PDF after download?

Asked

Viewed 556 times

2

I am generating PDF’s of the data I have in a table in my client, send the data to the server and there is generated PDF. After it is ready, the PDF download takes place, and it is at this stage of the process that it corrupts.

However, if before I download it I open it manually, it opens without any problems, with the same data that was in the table, IE, it is corrupting when I download, follow the codes below:

Server:

let filePath = "C:/Projetos/Relatorios/pdfs/Tabela.pdf"; 
let fileName = 'PDF.pdf'; 
res.download(filePath, fileName);

Client:

axios({
      method: 'post',
      url: '/server/gerarpdf',
      responseType: 'arraybuffer',
      data: this.pessoas
    })
    .then(function (response) {
      let blob = new Blob([response.data], {type: 'application/pdf'})
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'TabelaTeste.pdf'
      link.click()
    })

If anyone knows what is corrupting the PDF thank you...

1 answer

4


The problem that caused the PDF corruption was very simple: if it was an asynchronous function and the PDF was being sent even before it was ready, it follows code with the solution to the problem:

pdfMake = printer.createPdfKitDocument(docDefinition);
let stream = pdfMake.pipe(fs.createWriteStream('../pdfs/Tabela.pdf'));
pdfMake.end();

stream.on('finish', function() {
    if (fs.existsSync('C:/Projetos/Relatorios/pdfs/Tabela.pdf')) {
        let file = 'C:/Projetos/Relatorios/pdfs/Tabela.pdf';
        res.download(file);
    }
})

After that the PDF was even downloaded with the right name...

  • Vlw to share with! ;)

  • I’m happy to help, because I’ve already received a lot of help here, I just want to give back in the best way

Browser other questions tagged

You are not signed in. Login or sign up in order to post.