Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 mikehaertlwkhtmltoPdf; 

$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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...