PDF Export Snippet Using WKHTMLTOPDF Binary "cgi-bin"


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. //name the snippet as download_pdf, and then reference to it as [[!download_pdf]]
  4. if(isset($_REQUEST["pid"])){
  5. ini_set('zlib.output_compression','0');
  6. function generate_name($resname){
  7. $rndname = chr(rand(65,90)).chr(rand(97,122)).chr(rand(48,57)).chr(rand(65,90)).chr(rand(97,122)).chr(rand(48,57));
  8. $pdffilename = "/home/berlinp/public_html/beta/html2pdf/pdftmp/".$resname.$rndname.".pdf";
  9. if(file_exists($pdffilename))
  10. return generate_name($resname);
  11. else
  12. return $pdffilename;
  13. }
  14. $resId = mysql_escape_string($_REQUEST["pid"]);
  15. $url = "http://".$_SERVER['HTTP_HOST']."/beta/html2pdf/".$modx->makeUrl($resId);
  16. $name = $modx->getObject('modResource', $resId)->get('alias');
  17. $pdffilename = generate_name($name);
  18. $cmd = "/home/berlinp/public_html/beta/cgi-bin/wkhtmltopdf -q --footer-center '[page]/[topage]' --page-size Letter $url $pdffilename";
  19. shell_exec($cmd);
  20. //WAIT UP TO 20 SEC IF FILE IS NOT CREATED
  21. for($i=1;$i<20;$i++){
  22. sleep(1); //wait to finish
  23. if(file_exists($pdffilename) && filesize($pdffilename)>10) break;
  24. }
  25. //WAIT UP TO 20 SEC IF FILE IS NOT CREATED
  26. if(!file_exists($pdffilename)) die("Sorry, an error ocours while downloading your pdf file. Please try again later.");
  27. header('Content-Type: application/pdf');
  28. header('Content-Disposition: inline; filename="'.$name.'.pdf"');
  29. header('Expires: 0');
  30. header('Cache-Control: must-revalidate');
  31. header('Pragma: public');
  32. header('Content-Length: '.filesize($pdffilename));
  33. ob_clean();
  34. flush();
  35. readfile($pdffilename);
  36. unlink($pdffilename);
  37. exit();
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.