Created
April 30, 2024 17:45
-
-
Save brunoinds/836f0ea1f69fdd87fc93df1330bb468c to your computer and use it in GitHub Desktop.
DomPDF Render with Progress Callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Dompdf\Dompdf; | |
$totalFramesToRenderCount = 0; | |
$finishedFramesToRenderCount = 0; | |
$onProgress = function($percentage, $framesRendered, $framesTotal){ | |
//This is the callback that will be called every progress change | |
var_dump($percentage, $framesRendered, $framesTotal); | |
}; | |
//Instatiate DomPDF | |
$dompdf = new Dompdf(); | |
$dompdf->setCallbacks([ | |
'begin_frame' => [ | |
"event" => "begin_frame", | |
"f" => function ($frame) use (&$dompdf, &$totalFramesToRenderCount){ | |
//This callback will be executed once, on the first PDF frame render, this will count how many frames needs to be rendered. | |
if ($totalFramesToRenderCount !== 0){ | |
return; | |
} | |
$reflection = new \ReflectionClass($dompdf); | |
$property = $reflection->getProperty('tree'); | |
$property->setAccessible(true); | |
$tree = $property->getValue($dompdf); | |
foreach ($tree as $frame) { | |
$totalFramesToRenderCount++; | |
} | |
} | |
], | |
'end_frame' => [ | |
'event' => 'end_frame', | |
'f' => function ($frame) use (&$finishedFramesToRenderCount, &$totalFramesToRenderCount, &$onProgress) { | |
//On every frame rendering, this callback will be executed | |
$finishedFramesToRenderCount++; | |
if ($totalFramesToRenderCount === 0 || $finishedFramesToRenderCount > $totalFramesToRenderCount){ | |
return; | |
} | |
$onProgress($finishedFramesToRenderCount / $totalFramesToRenderCount * 100, $finishedFramesToRenderCount, $totalFramesToRenderCount); | |
} | |
] | |
]); | |
$dompdf->loadHtml('<h1>Hello world</h1>'); | |
$dompdf->setPaper('A4', 'portrait'); | |
$dompdf->render(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment