Reputation: 35
I have a PHP Page that is displaying a bunch of MongoDB documents information in a Table. What I want to do is to make a button that print the current PHP Page (basically all the Table with CSS Style and Database variables) into a PDF. But after trying a lot of code I still can't seem to make it work.
Here's my code right now
<?php
require 'vendor/autoload.php';
use Dompdf\Dompdf;
>>Here I have my code related to the MongoDB query
ob_start();
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Registre</title>
</head>
<body>
<form method="post" action="">
<input type="submit" name="pdf" id="pdf" value="PRINT">
</form>
<table class="tftable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<?php foreach ($r as $document):
$bson = MongoDB\BSON\fromPHP($document);
$json = json_decode(MongoDB\BSON\toJSON($bson));
?>
<tr>
<td><?php echo $var1 ?></td>
<td><?php echo $var2 ?></td>
<td><?php echo $var3 ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tr>
<td>
<form action="" method="POST">
<label for="var1">var1</label><br>
<input type="date" id="var1" name="var1">
</td>
<td>
<label for="var2">var2</label><br>
<input type="text" id="var2" name="var2">
</td>
<td>
<label for="var3">var3</label><br>
<input type="text" id="var3" name="var3">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Add Data"></form>
</td>
</tr>
</table>
</body></html>
<?php
if(isset($_POST["pdf"])) {
$html = ob_get_contents();
ob_end_flush();
$dompdf = new DOMPDF();
$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream('registre.pdf',array('Attachment'=>1));
}
?>
Right now when I click the print, my PHP page looks like it is reloading itself quickly but nothing else happens and no PDF get shown. If put the PHP part of the $dompdf before the HTML part, I get a blank PDF File.
PHP v8.0.5
dompdf v1.0.2
Thank you.
Upvotes: 2
Views: 1258
Reputation: 13914
The "headers already sent" error is caused by the call to ob_end_flush
. That tells the server to send the current buffer content to the browser. When you call $dompdf->stream()
afterwards, Dompdf attempts to set the headers, which it can not do. You should call ob_end_clean()
instead to ensure there is no content left in the buffer.
Upvotes: 3