skip to Main Content

I’m generating a PDF document using DomPDF. The code looks something like this:

// reference the Dompdf namespace
use DompdfDompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('This is my HTML');

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

// Output the generated PDF to Browser
$dompdf->stream('My_file.pdf', ['Attachment' => false]);

In other words, completely standard. The problem I have is that, when I "stream" the PDF content to the client, it comes with the HTTP header:

Cache-Control: private

which means the document will probably be cached by the browser. This is apparent when I change the document and use the same link to open it again. I will see the old version. Pressing F5 (on Windows) solves this, but I would like to change the header to something like:

Cache-Control: no-cache, no-store, must-revalidate

If I set the header in PHP like this:

header('Cache-Control: no-cache, no-store, must-revalidate');

before streaming the PDF, it gets overwritten, and I obviously cannot change it once the streaming has been done.

I cannot find a way to do this.

Does anybody know how to change the HTTP header that DomPDF uses?

2

Answers


  1. There seems to be no way of changing the header which is being set in src/Adapter/CPDF.php on line 914

    header("Cache-Control: private");
    

    Maybe possible to extend the class and modify the stream function.

    Login or Signup to reply.
  2. Rather than relying on the built-in stream method you can manually stream the PDF. Borrowing from Dompdf’s internal logic:

    $dompdf = new Dompdf();
    $dompdf->loadHtml('...');
    $dompdf->render();
    $pdf = $dompdf->output();
    if (headers_sent()) {
        die("Unable to stream pdf: headers already sent");
    }
    header("Cache-Control: no-cache, no-store, must-revalidate");
    header("Content-Type: application/pdf");
    header("Content-Length: " . mb_strlen($pdf, "8bit"));
    header(DompdfHelpers::buildContentDispositionHeader("inline", "output.pdf"));
    echo $pdf;
    flush();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search