PDF corrupted after download?

2

I am generating PDF's of the data I have in a table in my client, I send the data to the server and there the PDF is generated. After it is ready, the PDF is downloaded, 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 as in the table, that is, it is corrupting when I download it, follow the codes below: p>

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 ...

    
asked by anonymous 15.08.2017 / 20:19

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 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 this the PDF was even downloaded with the right name ...

    
16.08.2017 / 19:51