【问题标题】:Laravel, Vue.js | blank pdf getting downloaded via axios requestLaravel,Vue.js |通过axios请求下载空白pdf
【发布时间】:2019-06-13 09:03:01
【问题描述】:

我一直在尝试通过 axios 从我的 Laravel 应用程序下载 PDF,但下载的文件是一个空的 pdf。

我正在使用 DomPdf 创建 pdf 和 download.js 来下载它下面是我的代码。

注意:如果我尝试在没有 ajax 请求的情况下下载它,它就可以正常工作。

Laravel,

return PDF::loadView('print', compact('bill'))->download($bill->number.'.pdf'); Javascript

``axios.get(`/bills/${id}/print` {
responseType: 'blob',Accept: 'application/pdf'
})
.then(response => {
  const download = require('@/download');
  // @ is just an alias for my root js directory.
  download(response.data, `file.pdf`, 'application/pdf');
});``

【问题讨论】:

  • 您是否使用浏览器工具来确保您从 GET 请求中取回 PDF?如果您在浏览器开发工具中设置断点,您会在response.data 中看到 PDF 内容吗?
  • 奇怪的是问题与 axios 有关,我在 stackoverflow 上随机发现它。最后使用了其中一个建议使用 xlhttprequest 的答案,它起作用了。

标签: javascript laravel vue.js axios dompdf


【解决方案1】:

试试下面的代码:

在 Laravel 控制器中:

$pdf = PDF::loadView('finance.remainingFee', compact('fee', 'time'));
$pdf->setPaper('a4' , 'portrait');
return $pdf->output();

在 Vue 文件中:

  axios.get(APP_URL + `api/finance/remainingStudentFee/${fee_id}`, {responseType: 'blob'}).then(response => {

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'remaining_fee.pdf'); //or any other extension
    document.body.appendChild(link);
    link.click();

  })
  .catch(error => {
    console.log(error);
  })

【讨论】:

    猜你喜欢
    • 2019-03-04
    • 2021-09-01
    • 2013-12-14
    • 2020-08-07
    • 2015-04-22
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    相关资源
    最近更新 更多