无法在 laravel 控制器中生成 pdf

Unable to generate pdf in laravel controller

我写了一些示例代码来在我的 laravel 控制器中生成 pdf。它获得 200 响应代码,但未生成 pdf。

下面是我的代码。

function exportPDF() {
    // instantiate and use the dompdf class
    $dompdf = new PDF();
    $dompdf->loadHtml('<h1>hello world</h1>');

    // (Optional) Setup the paper size and orientation
    $dompdf->setPaper('A4', 'landscape');

    // Render the HTML as PDF
    $dompdf->render();

    // Output the generated PDF to Browser
    return $dompdf->stream();
}

但是当我直接将代码包含在 web.php 文件中时,这是有效的。

Route::get('/generate-pdf', function () {
        $pdf = App::make('dompdf.wrapper');
        $pdf->loadHTML('<h1>Test</h1>');
        return $pdf->stream();
    });

已编辑

web.php

Route::post('/report-audit-export-pdf', 'ReportAuditController@exportPDF');

.js

window.exportPDF = function() {
  var hidden_category = $('#hidden_category').val();
  $.ajax({
      type: "POST",
      url: '/report-audit-export-pdf',
      data: {

      },
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      error: function(jqXHR, textStatus, errorThrown) {
          console.log("jqXHR : " + jqXHR + " and textStatus : " + textStatus + " and errorThrown : " + errorThrown);
      },
      success: function(content) {
        // alert("Success");
      }
  }); 
}

我可以知道问题出在哪里吗?

您无法通过 Ajax 生成 PDF,因为 Ajax 请求需要一个响应,默认情况下 Laravel 作为 JSON 发回。所以你可以做的是创建一个正常的 GET 路由来显示 PDF,例如:

Route::get('display-pdf', 'ReportAuditController@exportPDF');

由于您的 ajax 没有 POST 任何数据(您的数据对象为空),您可以绕过 ajax 请求并简单地使用锚点

<a href="/display-pdf">Display PDF</a>

如果出于某种原因,您仍想使用 Ajax,您可以像这样使用 ajax 请求的成功响应

$.ajax({
    type: "POST",
    url: '/data-url',
    data: {},
    success: function(content) {
        window.location.href = '/display-pdf';
    }
});