简体   繁体   中英

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?

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.

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: private");
header("Content-Type: application/pdf");
header("Content-Length: " . mb_strlen($pdf, "8bit"));
header(Helpers::buildContentDispositionHeader("inline", "output.pdf"));
echo $tmp;
flush();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM