Use wkhtmltopdf to print html into pdf (PHP level)


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

Wkhtmltopdf (http://code.google.com/p/wkhtmltopdf/) is a open source html to pdf converter. This snippet shows how to use it in a php script.


Copy this code and paste it in your HTML
  1. // content var
  2. $content = 'content';
  3.  
  4. // generate pdf from contents
  5. $file_name = 'example.pdf';
  6.  
  7. $descriptorspec = array(
  8. 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
  9. 1 => array("file", "./generated/$file_name", 'a'), // stdout is a pipe that the child will write to
  10. );
  11.  
  12. // wkhtmltopdf must be in PATH var!
  13. $process = proc_open('wkhtmltopdf - -', $descriptorspec, $pipes );
  14.  
  15. if (is_resource($process)) {
  16. // $pipes now looks like this:
  17. // 0 => writeable handle connected to child stdin
  18. // 1 => readable handle connected to child stdout
  19. // Any error output will be appended to /tmp/error-output.txt
  20.  
  21. fwrite($pipes[0], $content);
  22. fclose($pipes[0]);
  23.  
  24. // echo stream_get_contents($pipes[1]);
  25. // fclose($pipes[1]);
  26.  
  27. // It is important that you close any pipes before calling
  28. // proc_close in order to avoid a deadlock
  29. $return_value = proc_close($process);
  30.  
  31. echo "command returned $return_value\n";
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.