PHP 使用 TCPDF 创建 PDF 并将其发送到 Angular 前端

问题描述

我在 Angular 中向 PHP 后端发出 POST 请求。后端应创建一个 PDF 并将其发送到前端。 PDF 文件不应保存在后端。

这就是我创建 PDF 的方式:

header('Content-type: application/pdf');
        header('Content-disposition: inline; filename="myfile.pdf"');
        header('Content-transfer-encoding: binary');
        header('Accept-Ranges: bytes');
        $pdf = new TCPDF(); 
        $pdf->SetCreator('Test');
        $pdf->SetAuthor("Test test");
        $pdf->SetTitle("My testtitle");
        $pdf->SetSubject("Testsubject");
        $pdf->SetKeywords("TCPDF,PDF,example,test,guide");
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetMargins(10,10,10);
        $pdf->SetAutopageBreak(TRUE,PDF_MARGIN_BottOM);
        $pdf->setimageScale(PDF_IMAGE_SCALE_RATIO); 
        $pdf->setLanguageArray($l); 
        $pdf->AliasNbPages();
        $pdf->AddPage();
        $pdf->SetFont("freesans","BI",20);
        $pdf->writeHTML('<div>Test</div>',true,false,'');
        $pdf->Output("myfiles.pdf","I");
        exit();

这就是我在 Angular 中打开它的方式:

const thefile = new Blob([response],{ type: "application/pdf" });
    let url = window.URL.createObjectURL(thefile);
    window.open(url);

这是 Angular 中的请求头:

const headers = new HttpHeaders().set('Content-Type','application/pdf');
    headers.append('Content-disposition','inline; filename="myfile.pdf"');
    headers.append('Content-transfer-encoding','binary');
    headers.append('Accept-Ranges','bytes');
    headers.append('Access-Control-Allow-Origin','*');
    headers.append('Access-Control-Allow-Methods','POST');
    headers.append('Access-Control-Allow-Credentials','true');
    headers.append('Access-Control-Allow-Headers','Content-Type');

我总是返回一个空的 PDF 文件

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)