PDF Generation Results in ERR_INVALID_RESPONSE in Chrome

前端 未结 3 1085
囚心锁ツ
囚心锁ツ 2020-12-10 13:24

When generating a PDF in the browser programmatically (via PHP) the rendered PDF displays fine in both Firefox and Safari, but Chrome returns an ERR_INVALID_RESPONSE. It is

相关标签:
3条回答
  • 2020-12-10 13:47

    I want to thank everyone for their answers.

    It turns out this was not related to the headers. After attempting to change/remove headers in various ways (detecting encoding, trying with and without content-length, etc.) we decided to dig into the deeper httpd logs to see if anything was resolving differently for Chrome.

    It turns out that mod_sec on our server was flagging the request (only from Chrome for some reason) as an attempt at a file injection attack and was returning a 403 forbidden response. Chrome displayed this as the ERR_INVALID_RESPONSE rather than a 403.

    The hostname of the CDN was present in the request (we had ample checking at the endpoint to ensure that the file was indeed an allowed resource), and instead are building the URL out on the server instead.

    0 讨论(0)
  • 2020-12-10 13:55

    In my case I had to add these 2 parameters to headers because wordpress was sending 404 code as it didn't recognize the url of my php function:

    header("Content-type: application/pdf",true,200);
    

    as stated in this answer on wordpress.stackexchange.

    This forces the headers to replace (2nd param true) the 404 status code generated by wordpress as it does not recognize the custom url, and sets 200 OK (3rd param 200).

    So it ended being something like this:

    $pdf_name = "test.pdf";
    $pdf_file = "/absolute/path/to/my/pdfs/on/my/server/{$pdf_name}";
    header('Content-type: application/pdf',true,200);
    header("Content-Disposition: attachment; filename={$pdf_name}");
    header('Cache-Control: public');
    readfile($pdf_file);
    exit();
    
    0 讨论(0)
  • 2020-12-10 14:00

    Try this

    <?php
    $filename = 'Physical Path to PDf file.pdf';
    $content = file_get_contents($filename);
    
    header("Content-type:application/pdf");
    
    // It will be called downloaded.pdf
    header("Content-Disposition:inline;filename='".basename($filename)."'");   
    header('Content-Length: '.strlen( $content ));
    
    // The PDF source is in original.pdf
    readfile($filename);
    ?>
    
    <html>
    <body>
    ...
    ...
    ...
    

    Make sure that above header code is called before output of PHP script is sent to browser.

    0 讨论(0)
提交回复
热议问题