vamsi vamsi - 1 month ago 10
PHP Question

Print button for generated dompdf output

HTML

<p style="color:red;font-size: 30px;">sfsdfsdfdsfsdfdsfdsf</p>sdgfhgfhgfhg


PHP

<?php
// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

//to put same file html
/*$html1 =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';*/

// instantiate and use the dompdf class
$dompdf = new Dompdf();

//to put other html file
$html = file_get_contents('index.html');
$dompdf->loadHtml($html);
//$dompdf->loadHtml('<h1>Welcome to CodexWorld.com</h1>');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('Legal', 'Landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
//$dompdf->stream();

// Output the generated PDF (1 = download and 0 = preview)
$dompdf->stream("codex",array("Attachment"=>0));

//$output = $dompdf->output();
//file_put_contents("pdfs/file.pdf", $output);
?>


I am using dompdf to convert my html to pdf, what I want to do here is a Print button in index.html page, when I click on that print button the generated pdf should download to user's system.

How can I achieve that

Answer

This shoud work:

<?php
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

if (isset($_GET['action']) && $_GET['action'] == 'download') {

  // instantiate and use the dompdf class
  $dompdf = new Dompdf();

  //to put other html file
  $html = file_get_contents('index.html');
  $html .= '<style type="text/css">.hideforpdf { display: none; }</style>';
  $dompdf->loadHtml($html);

  // (Optional) Setup the paper size and orientation
  $dompdf->setPaper('Legal', 'Landscape');

  // Render the HTML as PDF
  $dompdf->render();

  // Output the generated PDF (1 = download and 0 = preview)
  $dompdf->stream("codex",array("Attachment"=>1));
}
?>


<a class="hideforpdf" href="generatepdf.php?action=download" target="_blank">Download PDF</a>

Edit: moved the use-part to the top of the code.
Edit 2: added a class to hide the download button.

Comments