How do I get WKHTMLTOPDF to execute via PHP?

后端 未结 7 1861
孤街浪徒
孤街浪徒 2020-11-29 00:28

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 tryin

相关标签:
7条回答
  • 2020-11-29 01:07

    Have a look at snappy, a PHP5 library allowing thumbnail, snapshot or PDF generation from a url or a html page. It's a wrapper for wkhtmltopdf/wkhtmltoimage.

    0 讨论(0)
  • 2020-11-29 01:07

    For Linux:

    exec('wkhtmltopdf http://somesite.com /home/user/file.pdf 2>&1');
    

    For Windows:

    <?php
    exec('C://abc//wkhtmltopdf http://google.html form1.pdf');
    
    echo "PDF Created Successfully";
    ?>
    
    0 讨论(0)
  • 2020-11-29 01:08

    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();
    
    0 讨论(0)
  • 2020-11-29 01:08

    And what happens when you run :

    $out = array();
    exec("/path/to/binary/wkhtmltopdf http://www.google.com pdf1.pdf", $out);
    print_r($out);
    

    My guess is that since you are not specifying any folder for the file, it will try to write it to the current working directory. It could be (well most probably this is the case) that the webuser doesn't have write permission on that folder. So you should by able to solve this by providing the full path to a folder that is writeable by the webuser.

    ie.

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

    Apart from that I'm not quite sure that wkhtmltopdf can work headless, it could be that it requires a running X server (on a server not running X you could solve this by installing Xvfb and using xvfb-run to run wkhtmltopdf).

    0 讨论(0)
  • 2020-11-29 01:16

    To create a pdf from php (on linux) you must use a wrapper.

    $cmd = '/usr/bin/xvfb-run --server-args="-screen 0, 1920x1080x24" /usr/bin/wkhtmltopdf http://google.com /tmp/google.pdf';
    
    exec($cmd);
    
    0 讨论(0)
  • 2020-11-29 01:16

    This worked for me as a way to pre-generate a PDF report then use a unique session ID to fetch it from the requesting page (of the same session).

    $cmd = "/usr/local/bin/wkhtmltopdf 'http://127.0.0.1/myApp/pdfReport.php?key=something' tmp_reports/report_".$_POST['sessionid'].".pdf";
    exec($cmd);
    
    0 讨论(0)
提交回复
热议问题