使用Ajax响应在浏览器中显示FPDF

时间:2020-01-01 09:46:05

标签: javascript ajax cakephp fpdf

this答案和this放在一起,我正在尝试使用Ajax响应将生成的pdf加载到新窗口中:

JavaScript

$.ajax({
  type: "GET",
  headers: { 'X-CSRF-Token': <?= json_encode($this->request->getParam('_csrfToken')); ?> },
  url:  '<?php echo Router::url(['controller' => 'DeliveryNotes', 'action' => 'pdf']);?>',
  data: { 'type': result },
  success: function(response) {
    var w = window.open('about:blank');
    w.document.open();
    w.document.write(response);
    w.document.close();
  }
});

控制器

public function pdf($id = null)
{
    if ($this->request->is(['ajax', 'get'])) {
        $type = $this->request->getData('type');

        require_once(ROOT . DS . 'vendor' . DS . 'fpdf' . DS . 'fpdf' . DS . 'original' . DS . 'fpdf.php');
        $this->response = $this->response->withType('pdf');
        $this->response = $this->response->withHeader('Content-Disposition', 'inline; filename="some.pdf"');
        $this->layout = 'pdf';
        $this->set('fpdf', new FPDF('P', 'mm', 'A4'));
        $this->set('type', $type);
        $this->render('pdf');
    }
}

布局

<?php
    echo $content;

查看

<?php
    $fpdf->AddPage();
    $fpdf->SetFont('Arial','B',16);
    $fpdf->Cell(40,10, $type);
    $this->set('content', $fpdf->Output('S'));

它将打开一个新窗口,但显示原始内容,而不是实际的pdf。 相反,如果我仅调用控制器动作(没有Ajax请求,如链接的第一个答案),它将起作用。

也许标题没有转移到新窗口?

Here有一个可能的解决方案,但据我了解,它需要在服务器上创建实际的pdf文件。相反,我不想创建这样的文件:我想将pdf内容直接传递到浏览器。

更新

在没有Ajax的情况下实现相同目标的解决方法如下:

JavaScript

let url = new URL('<?= Router::url(['controller' => 'DeliveryNotes', 'action' => 'pdf'], true); ?>');
let params = new URLSearchParams();
params.append('type', result);
params.append('id', id);
window.open(url + '?' + params, '_blank');

控制器

public function pdf()
{
    $type = $this->request->getQuery('type');
    $id = $this->request->getQuery('id');

    require_once(ROOT . DS . 'vendor' . DS . 'fpdf' . DS . 'fpdf' . DS . 'original' . DS . 'fpdf.php');
    $this->response = $this->response->withType('pdf');
    $this->response = $this->response->withHeader('Content-Disposition', 'inline; filename="some.pdf"');
    $this->layout = 'pdf';
    $this->set('fpdf', new FPDF('P', 'mm', 'A4'));
    $this->set('id', $id);
    $this->set('type', $type);
    $this->render('pdf');
}

这不是最佳解决方案,因为在新窗口中,控制器的操作和查询参数(typeid)都是可见的。但是至少可以。

任何使用Ajax进行相同操作的建议都值得赞赏!

0 个答案:

没有答案