最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download pdf file from server response - Stack Overflow

programmeradmin1浏览0评论

So, I am creating a docx with php laravel, then converting to pdf and save it in my public server folder. Finally, I am sending a response to my client with the file.

Now, in client side, I am tryng to download it.

It's half working, because I can download a file (with exact same page number) but the file and all the page are blank page.

Here, server side sending my file to client side

    $docx->transformDocument($fileName . '.docx',  $fileName . '.pdf');

return response()->file(public_path($fileName . '.pdf'));

What I have tried client side

export const generateDocx = (offerData) => async () => {
  await axios({
    method: 'post',
    url: `${process.env.REACT_APP_API_URL2}offer/generate/docx`,
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json', 
      responseType: 'arraybuffer',
    },
    data: offerData,
  }).then((res) => {
    console.log(res); 
    // Create blob link to download
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `FileName.pdf`);
 
    document.body.appendChild(link);
 
    link.click();
 
    link.parentNode.removeChild(link);
  });
};

what my console.log (res) contain :

I have also tried this :

    let fileName = 'aaa.pdf';
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
 
      window.navigator.msSaveOrOpenBlob(
        new Blob([res.data], {
          type: 'application/pdf',
          encoding: 'UTF-8',
          responseType: 'blob'
        }),
        fileName
      );
    } else {
      const url = window.URL.createObjectURL(
        new Blob([res.data], {
          type: 'application/pdf',
          encoding: 'UTF-8',
        })
      );
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
    console.log(res.data);
  });

And with file-saver package

   var blob = new Blob([res.data], {
      type: 'application/pdf',
    });
    saveAs(blob, 'hello world.pdf');
  });

what my blob console.log contain :

So, I am creating a docx with php laravel, then converting to pdf and save it in my public server folder. Finally, I am sending a response to my client with the file.

Now, in client side, I am tryng to download it.

It's half working, because I can download a file (with exact same page number) but the file and all the page are blank page.

Here, server side sending my file to client side

    $docx->transformDocument($fileName . '.docx',  $fileName . '.pdf');

return response()->file(public_path($fileName . '.pdf'));

What I have tried client side

export const generateDocx = (offerData) => async () => {
  await axios({
    method: 'post',
    url: `${process.env.REACT_APP_API_URL2}offer/generate/docx`,
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json', 
      responseType: 'arraybuffer',
    },
    data: offerData,
  }).then((res) => {
    console.log(res); 
    // Create blob link to download
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `FileName.pdf`);
 
    document.body.appendChild(link);
 
    link.click();
 
    link.parentNode.removeChild(link);
  });
};

what my console.log (res) contain :

I have also tried this :

    let fileName = 'aaa.pdf';
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
 
      window.navigator.msSaveOrOpenBlob(
        new Blob([res.data], {
          type: 'application/pdf',
          encoding: 'UTF-8',
          responseType: 'blob'
        }),
        fileName
      );
    } else {
      const url = window.URL.createObjectURL(
        new Blob([res.data], {
          type: 'application/pdf',
          encoding: 'UTF-8',
        })
      );
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
    console.log(res.data);
  });

And with file-saver package

   var blob = new Blob([res.data], {
      type: 'application/pdf',
    });
    saveAs(blob, 'hello world.pdf');
  });

what my blob console.log contain :

Share Improve this question edited Nov 23, 2022 at 15:39 Elodie Muller asked Nov 23, 2022 at 14:32 Elodie MullerElodie Muller 2151 gold badge6 silver badges22 bronze badges 7
  • I don't know, what $docx->transformDocument() does. But if you have a PDF document that can be opened by a PDF reader and has the correct amout of pages (even if they are blank) the chances are high, that the error is not on the client but on the server side. Do you have any other way to access the transformed document directly on the server, to check if it's correctly transformed? – derpirscher Commented Nov 23, 2022 at 14:47
  • Hello derpirscher, Well in fact I save my pdf file in server side first so when i open my pdf in server side public folder I am able to see the correct pdf with all my data. – Elodie Muller Commented Nov 23, 2022 at 14:53
  • 1 Can you try using for example curl or Postman to execute that request and check if the file is downloaded correctly? – derpirscher Commented Nov 23, 2022 at 14:58
  • 2 One thing I see, you are sending an Accept: applicaton/json header, yet the result you are expecting is application/pdf. A strict server might send an error, because, it wouldn't be able to satisfy the request. But I don't think, that's the issue here. – derpirscher Commented Nov 23, 2022 at 15:02
  • 1 @MalwareMoon No, "getting" data with a post request is not unusual at all when that request has to send data to the server and that request is creating some sort of item in the backend which is then returned ... – derpirscher Commented Nov 23, 2022 at 15:06
 |  Show 2 more ments

1 Answer 1

Reset to default 3

After some test it's working

export const generateDocx = (offerData) => async () => {
  await axios({
    method: 'post',
    url: `${process.env.REACT_APP_API_URL2}offer/generate/docx`,
    responseType: 'blob',
    headers: {
      Accept: 'application/pdf',
    },
    data: offerData,
  }).then((res) => {
    var blob = new Blob([res.data], {
      type: 'application/pdf',
    });
    saveAs(blob, 'test.pdf');
  });
};

thank you all for your help

发布评论

评论列表(0)

  1. 暂无评论