Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get WKHTMLTOPDF to execute via PHP?

This has been asked to some degree before but there are no solutions or accepted answers and I'd like to try and be more comprehensive in my question so:

I'm trying to WKHTMLTOPDF up and running via PHP on a shared server (in this case it's MediaTemple (gs)). According to the host there is no reason this won't work and in fact it is working via SSH. So...

I've tried a variety of things, the most basic does nothing, just silently fails:

exec("/path/to/binary/wkhtmltopdf http://www.google.com pdf1.pdf"); 

- Source: Question on Stack Overflow

The full PHP bindings along with the following give me errors, which despite my best Googling I can't figure out:

Call:

$html = file_get_contents("http://www.google.com"); $pdf = new WKPDF(); $pdf->set_html($html); $pdf->render(); $pdf->output(WKPDF::$PDF_EMBEDDED,'sample.pdf'); 

- Source: WKHTMLTOPDF on Google Code

Error:

Fatal error: Uncaught exception 'Exception' with message 'WKPDF didn't return any data. <pre>Loading pages (1/6) [> ] 0% [======> ] 10% terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc </pre>' in /path/to/wkhtmltopdf.php:206 Stack trace: #0 /path/to/index.php(8): WKPDF->render() #1 {main} thrown in /path/to/wkhtmltopdf.php on line 206 

And once I got this (below is an extract as I can't reproduce it now):

Qt Concurrent has caught an exception thrown from a worker thread. This is not supported, exceptions thrown in worker threads must be caught before control returns to Qt Concurrent. 

I've also tried a few other options but with the same results; no PDF. So what do I do now, how do I figure out what's wrong? My PHP level is on the basic side but I'll do my best.

like image 857
Jamie Avatar asked Apr 14 '11 13:04

Jamie


People also ask

How do I use Wkhtmltopdf command line?

Open a command prompt window. The syntax for using the tool is fairly simple, enter the name wkhtmltopdf, followed by the URL of the web page, and the name of the PDF that you want to create, like so.


1 Answers

You can also try my project here. It provides a clean OO interface to the command line utility:

https://github.com/mikehaertl/phpwkhtmltopdf

Usage is very simple:

<?php use mikehaertl\wkhtmlto\Pdf;   $pdf = new Pdf;  // Add a HTML file, a HTML string or a page from a URL $pdf->addPage('/home/joe/page.html'); $pdf->addPage('<html>....</html>'); $pdf->addPage('http://google.com');  // Add a cover (same sources as above are possible) $pdf->addCover('mycover.html');  // Add a Table of contents $pdf->addToc();  // Save the PDF $pdf->saveAs('/tmp/new.pdf');  // ... or send to client for inline display $pdf->send(); 
like image 173
Michael Härtl Avatar answered Oct 04 '22 11:10

Michael Härtl