KIKO Software
KIKO Software

Reputation: 16688

Prevent browser caching of PDF generated with Dompdf

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

// reference the Dompdf namespace
use Dompdf\Dompdf;

// 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?

Upvotes: 3

Views: 1654

Answers (2)

BrianS
BrianS

Reputation: 13914

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(\Dompdf\Helpers::buildContentDispositionHeader("inline", "output.pdf"));
echo $pdf;
flush();

Upvotes: 2

Moshe Gross
Moshe Gross

Reputation: 1395

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.

Upvotes: 1

Related Questions