PHPMaker v2024.5I created buttons to “Print to PDF” in my List page for each row where when they click this button, I want to generate a PDF using DOMPDF and able to view/download by user.I read in documentation that it’s not advisable to directly access the php file. It is possible to do this using custom file with route_action or api_action to output the PDF to view or download when user click on the button?Need advise to point me to the right direction to implement this. Thanks!
You may use Page_Load server event to add your custom action, see Example 3.
I managed to do it via Api_Action and call it using /api/getPDF/{id}Below is sample code if anyone need a reference. I can’t seem to get external .css file to work so I declare my css in the tag.
$app->get('/getPDF/{id}', function ($request, $response, $args) {
$id = RemoveXSS(Stripslashes($args['id']));
//do whatever you want with your parameter and construct your html below
$html = <<<EOD
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body {
font-family: 'Helvetica';
font-size: 0.75em;
}
</style>
</head>
<body>
Hello World. My ID is $id
</body>
</html>
EOD;
$filename = "MyPDF_".date("YmdHis").".pdf";
// Instantiate and use the dompdf class
$tmp = sys_get_temp_dir();
$pdf = new \Dompdf\Dompdf([
'logOutputFile' => '',
// authorize DomPdf to download fonts and other Internet assets
'isRemoteEnabled' => true,
// all directories must exist and not end with /
'fontDir' => $tmp,
'fontCache' => $tmp,
'tempDir' => $tmp,
'chroot' => $tmp,
]);
$pdf->set_option('defaultFont', 'sans-serif');
// Load HTML content
$pdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$pdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$pdf->render();
// Output the generated PDF to Browser
$content = $pdf->output();
$response = $response
->withHeader("Content-Type", "application/pdf")
->withHeader("Content-Disposition", "attachment; filename=\"$filename\"");
$stream = fopen('php://memory', 'w+');
fwrite($stream, $content);
rewind($stream);
$response->getBody()->write(fread($stream, (int)fstat($stream)['size']));
return $response;
});