Git Product home page Git Product logo

phpwkhtmltopdf's Introduction

PHP WkHtmlToPdf

GitHub Tests Packagist Version Packagist Downloads GitHub license Packagist PHP Version Support

PHP WkHtmlToPdf provides a simple and clean interface to ease PDF and image creation with wkhtmltopdf. The wkhtmltopdf and - optionally - wkhtmltoimage command must be installed and working on your system. See the section below for details.

For Windows systems make sure to set the path to wkhtmltopdf.exe in the binary option. Alternatively you can add the wkhtmltopdf "bin" directory to the system PATH variable to allow wkhtmltopdf command available to Windows CMD.

Installation

Install the package through composer:

composer require mikehaertl/phpwkhtmltopdf

Make sure, that you include the composer autoloader somewhere in your codebase.

Examples

Single page PDF

<?php
use mikehaertl\wkhtmlto\Pdf;

// You can pass a filename, a HTML string, an URL or an options array to the constructor
$pdf = new Pdf('/path/to/page.html');

// On some systems you may have to set the path to the wkhtmltopdf executable
// $pdf->binary = 'C:\...';

if (!$pdf->saveAs('/path/to/page.pdf')) {
    $error = $pdf->getError();
    // ... handle error here
}

Multi page PDF with Toc and Cover page

<?php
use mikehaertl\wkhtmlto\Pdf;

$pdf = new Pdf;
$pdf->addPage('/path/to/page.html');
$pdf->addPage('<html>....</html>');
$pdf->addPage('http://www.example.com');

// Add a cover (same sources as above are possible)
$pdf->addCover('/path/to/mycover.html');

// Add a Table of contents
$pdf->addToc();

// Save the PDF
if (!$pdf->saveAs('/path/to/report.pdf')) {
    $error = $pdf->getError();
    // ... handle error here
}

// ... or send to client for inline display
if (!$pdf->send()) {
    $error = $pdf->getError();
    // ... handle error here
}

// ... or send to client as file download
if (!$pdf->send('report.pdf')) {
    $error = $pdf->getError();
    // ... handle error here
}

// ... or you can get the raw pdf as a string
$content = $pdf->toString();

Creating an image

<?php
use mikehaertl\wkhtmlto\Image;

// You can pass a filename, a HTML string, an URL or an options array to the constructor
$image = new Image('/path/to/page.html');
$image->saveAs('/path/to/page.png');

// ... or send to client for inline display
if (!$image->send()) {
    $error = $image->getError();
    // ... handle error here
}

// ... or send to client as file download
if (!$image->send('page.png')) {
    $error = $image->getError();
    // ... handle error here
}

Setting options

The wkhtmltopdf shell command accepts different types of options:

  • global options (e.g. to set the document's DPI or the default page options)
  • page options (e.g. to supply a custom CSS file for a page)
  • toc options (e.g. to set a TOC header)

Please see wkhtmltopdf -H for a full explanation. All options are passed as array, for example:

<?php
$options = array(
    'no-outline',           // option without argument
    'encoding' => 'UTF-8',  // option with argument

    // Option with 2 arguments
    'cookie' => array('name'=>'value'),

    // Repeatable options with single argument
    'run-script' => array(
        '/path/to/local1.js',
        '/path/to/local2.js',
    ),

    // Repeatable options with 2 arguments
    'replace' => array(
        'number' => $page++,      // Replace '[number]'
        'title' => $pageTitle,    // Replace '[title]'
    ),
);

Options can be passed to several methods for PDFs:

<?php
$pdf = new Pdf($globalOptions);         // Set global PDF options
$pdf->setOptions($globalOptions);       // Set global PDF options (alternative)
$pdf->addPage($page, $pageOptions);     // Add page with options
$pdf->addCover($page, $pageOptions);    // Add cover with options
$pdf->addToc($tocOptions);              // Add TOC with options

Note, that you can also use page options in the global PDF options. wkhtmltopdf will apply them to all pages unless you override them when you add a page.

For wkhtmltoimage there's only one set of options:

<?php
$image = new Image($options);   // Set image options
$image->setOptions($options);   // Set image options (alternative)

Wrapper options

The wrapper itself is configured by the following special options that can be passed to the constructor, set as object properties or via setOptions():

  • binary: Full path to the wkhtmltopdf command. Default is wkhtmltopdf which assumes that the command is in your shell's search path.
  • commandOptions: Options to pass to https://github.com/mikehaertl/php-shellcommand.
  • tmpDir: Path to tmp directory. Defaults to the PHP temp dir.
  • ignoreWarnings: Whether to ignore any errors if a PDF file was still created. Default is false.
  • version9: Whether to use command line syntax for older wkhtmltopdf versions.

In addition to the binary, commandOptions, tmpDir and ignoreWarnings options above, the Image class also has a type option:

  • type: The image type. Default is png. You can also use jpg or bmp.

commandOptions can be used to set environment variables for wkhtmltopdf. For example, if you want to pass UTF-8 encoded arguments, you may have to set the LANG environment variable.

<?php
$pdf = new Pdf(array(
    'binary' => '/obscure/path/to/wkhtmltopdf',
    'ignoreWarnings' => true,
    'commandOptions' => array(
        'useExec' => true,      // Can help on Windows systems
        'procEnv' => array(
            // Check the output of 'locale -a' on your system to find supported languages
            'LANG' => 'en_US.utf-8',
        ),
    ),
));

Passing strings

Some options like header-html usually expect a URL or a filename. With our library you can also pass a string. The class will try to detect if the argument is a URL, a filename or some HTML or XML content. To make detection easier you can surround your content in <html> tag.

If this doesn't work correctly you can also pass an instance of our File helper as a last resort:

<?php
use mikehaertl\tmp\File;
$options = [
    'header-html' => new File('Complex content', '.html'),
];

Error handling

send(), saveAs() and toString() will return false on error. In this case the detailed error message is available from getError():

<?php
if (!$pdf->send()) {
    throw new Exception('Could not create PDF: '.$pdf->getError());
}

$content = $pdf->toString();
if ($content === false) {
    throw new Exception('Could not create PDF: '.$pdf->getError());
}

Known Issues

Use under Windows

If you use double quotes (") or percent signs (%) as option values, they may get converted to spaces. In this case you can disable argument escaping in the command. There are also two interesting options to proc_open() that you may want to use on Windows:

<?php
$pdf = new Pdf(array(
    'commandOptions' => array(
        'escapeArgs' => false,
        'procOptions' => array(
            // This will bypass the cmd.exe which seems to be recommended on Windows
            'bypass_shell' => true,
            // Also worth a try if you get unexplainable errors
            'suppress_errors' => true,
        ),
    ),
    ...
));

But then you have to take care of proper argument escaping yourself. In some cases it may be neccessary to surround your argument values with extra double quotes.

I also found that some options don't work on Windows (tested with wkhtmltopdf 0.11 rc2), like the user-style-sheet option used in the example below.

Download Problems

There have been many reports about corrupted PDFs or images when using send(). They are often caused by the webserver (Apache, Nginx, ...) performing additional compression. This will mess up the Content-Length header which is added by this library. It's useful to let the browser show a progress bar.

To fix this there are two options:

  1. Exclude the download URL from compression in your Webserver. For example if your script is called pdf.php then for mod_deflate in Apache you could try to add this to your configuration:

    SetEnvIfNoCase REQUEST_URI ^/pdf.php$ no-gzip dont-vary
    

    For Nginx there are similar solutions to disable gzip for a specific location.

  2. Suppress the Content-Length header when you send a file (available since 2.5.0):

    <?php
    $pdf->send('name.pdf', false, array(
        'Content-Length' => false,
    ));
    $image->send('name.png', false, array(
        'Content-Length' => false,
    ));

Installation of wkhtmltopdf

It's recommended that you download the latest wkhtmltopdf from their website:

http://wkhtmltopdf.org/downloads.html

These versions should run out of the box.

If for some reason you can't do so, you may run into an issue with the dynamically linked version of wkhtmltopdf. This is what you get for example on Ubuntu 12.04 LTS if you install the wkhtmltopdf package. It will work, but to use all features it requires an X server which is usually not available on headless webservers.

We therefore provide two Xvfb based workarounds. You can either use

  • the built in Xvfb support or
  • a standalone Xvfb server.

Both require the Xvfb package to be installed on the system and both also have some drawbacks.

Built in Xvfb support

This wraps each call to wkhtmltopdf with xvfb-run. xvfb-run will run any given command in a X environment without all the overhead of a full X session. The drawback with this solution is, that there's still a new session fired up for each an every PDF you create, which will create quite some extra load on your CPU. So this setup is only recommended for low frequency sites.

To use the built in support you have to set enableXvfb in the commandOptions. There are also some options you can set.

<?php
$pdf = new Pdf(array(
    // Explicitly tell wkhtmltopdf that we're using an X environment
    'use-xserver',

    // Enable built in Xvfb support in the command
    'commandOptions' => array(
        'enableXvfb' => true,

        // Optional: Set your path to xvfb-run. Default is just 'xvfb-run'.
        // 'xvfbRunBinary' => '/usr/bin/xvfb-run',

        // Optional: Set options for xfvb-run. The following defaults are used.
        // 'xvfbRunOptions' =>  '--server-args="-screen 0, 1024x768x24"',
    ),
));

Standalone Xvfb

It's better to start a Xvfb process once and reuse it for all your PHP requests (thanks to Larry Williamson for the original idea). This requires that you have root access to your machine as you have to add a startup script for that process. We have provided an example init script for Ubuntu (thanks eusonlito). You can put it to /etc/init.d/xvfb and add it to your startup files with update-rc.d xvfb defaults 10.

If your system is based on systemd this config should help (thanks nkm).

If your Xvfb process is running, you just have to tell the class to use this X display for rendering. This is done via an environment variable.

<?php
$pdf = new Pdf(array(
    'use-xserver',
    'commandOptions' => array(
        // You can change ':0' to whatever display you pick in your daemon script
        'procEnv' => array( 'DISPLAY' => ':0' ),
    ),
));

Full example

For me wkhtmltopdf seems to create best results with smart shrinking turned off. But then I had scaling issues which went away after I set all margins to zero and instead added the margins through CSS. You can also use cm or in in CSS as this is more apropriate for print styles.

<?php
use mikehaertl\wkhtmlto\Pdf;

// Create a new Pdf object with some global PDF options
$pdf = new Pdf(array(
    'no-outline',         // Make Chrome not complain
    'margin-top'    => 0,
    'margin-right'  => 0,
    'margin-bottom' => 0,
    'margin-left'   => 0,

    // Default page options
    'disable-smart-shrinking',
    'user-style-sheet' => '/path/to/pdf.css',
));

// Add a page. To override above page defaults, you could add
// another $options array as second argument.
$pdf->addPage('/path/to/demo.html');

if (!$pdf->send()) {
    $error = $pdf->getError();
    // ... handle error here
}

demo.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>

    <div id="print-area">
        <div id="header">
            This is an example header.
        </div>
        <div id="content">
            <h1>Demo</h1>
            <p>This is example content</p>
        </div>
        <div id="footer">
            This is an example footer.
        </div>
    </div>

</body>
</html>

pdf.css

/* Define page size. Requires print-area adjustment! */
body {
    margin:     0;
    padding:    0;
    width:      21cm;
    height:     29.7cm;
}

/* Printable area */
#print-area {
    position:   relative;
    top:        1cm;
    left:       1cm;
    width:      19cm;
    height:     27.6cm;

    font-size:      10px;
    font-family:    Arial;
}

#header {
    height:     3cm;

    background: #ccc;
}
#footer {
    position:   absolute;
    bottom:     0;
    width:      100%;
    height:     3cm;

    background: #ccc;
}

Links

Also check out my php-pdftk wrapper around pdftk which brings the full power of pdftk to PHP.

phpwkhtmltopdf's People

Contributors

alexsnowb avatar ashkulz avatar danielwaghorn avatar darkside666 avatar das-peter avatar dredav avatar giansalex avatar h4cc avatar iansltx avatar igorw avatar iuliandide avatar jamesgol avatar jgornick avatar luissquall avatar merk avatar mikehaertl avatar rahxam avatar saada avatar syrok avatar timwsuqld avatar tivie avatar tomfotherby avatar wyrihaximus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpwkhtmltopdf's Issues

Added xvfb support (Commit: 4f0a3cb)

4f0a3cb Now you can set the xvfb usage with a simple function.

You only need to have xvfb-run into your system and phpwkhtmltopdf will set the needed command string to execute under xvfb.

Usage:

# Set xvfb auto detect executable xvfb-run location (only unix/linux)
$pdf->setXvfb(true);

and

# Set xvfb bin manually
$pdf->setXvfb('/usr/bin/xvfb-run');

rename(,.pdf): No such file or directory

Hi there,

I set this up in Laravel 4 through composer:
"require": {
"laravel/framework": "4.0.*",
"mikehaertl/phpwkhtmltopdf": "dev-master",
"h4cc/wkhtmltopdf-i386": "dev-master"
},

did composer update..

code it in my Controller:
public function getDownload() {
$pdf = new Pdf('http://google.com');
die(var_dump($pdf->saveAs(public_path().'/uploads/testtest.pdf')));
}

and I got this error:
rename(,.pdf): No such file or directory.

screen shot 2014-08-04 at 1 56 11 pm

Any idea where I could have done wrong?

I'm running on Mac OSX, php 5.4.19, XAMPP.

Thanks!

how to use wkhtmltopdf

hello i am beginner and wants to know all from scratch .
and how to do this "The wkhtmltopdf binary must be installed and working on your system".
i don't know how to install wkhtmltopdf on localhost on wamp/xampp and use your tool.

A proposed fix to wkhtmltopdf as it sometimes fails even generation is mostly successful

Hi, thanks for your wrapper, it's really great and easy to use.

As the title states, sometimes the wkhtmltopdf binary completes, prints "Done", then prints an error message stating

Exit with code 2 due to http error: 404 Page not found

As a result the wrapper fails to complete and the file is never moved from /tmp to the final destination, despite the file (probably) being okay.

I'm sure this is not a problem with your wrapper, and I'm pretty sure it's something I've done wrong, but it seems to appear to other people:
https://code.google.com/p/wkhtmltopdf/issues/detail?id=548

So I have a proposed "fix" (read: hack) to work around it for now.
I'm new to Git and GitHub, so I've made a patch but I don't know how to post it.

Below are the contents (please keep laughing to a minimum):


diff --git a/WkHtmlToPdf.php b/WkHtmlToPdf.php
index d2c6279..27f43de 100644
--- a/WkHtmlToPdf.php
+++ b/WkHtmlToPdf.php
@@ -307,7 +307,17 @@ class WkHtmlToPdf
             $result = proc_close($process);
 
             if($result!==0)
-                $this->error = "Could not run command $command:\n$stderr";
+            {
+                if ( (!file_exists($fileName)) || (filesize($fileName)===0) )
+                {
+                    $this->error = "Could not run command $command:\n$stderr";
+                }
+                else
+                {
+                    $this->error = 'Warning: an error occurred while creating the PDF, but some data was written';
+                    return true;
+                }
+            }
         } else
             $this->error = "Could not run command $command";

Corrupted PDF File generated using Windows wamp server

Hi,
I'm using laravel framework and installed on my local machine (windows OS with wamp server installed, AMD) the package together with the binary using composer.
I created a test class. Please see below:
use mikehaertl\wkhtmlto\Pdf;
class PDFConverter {

public function __construct() {

}

public function createPDF() {
    $pdf = new Pdf('http://gmail.com/');

    $pdf->binary = base_path(). '/vendor/bin/wkhtmltopdf-amd64';
    $pdf->saveAs(base_path()."/public/documents/sample.pdf");
    //$pdf->send();
    $pdf->send('sample.pdf');
    var_dump($pdf);

}

However, the generated pdf file was 0kb and my pdf reader showed an alert with this message, "format error, not a pdf or corrupted".
 I really don't know what caused this error.

Please help. It's been weeks since I've been searching for a good package that will convert html file to pdf with too many nested tables.

  Thank you!

Options

I cannot figure out how to get the options to work for me, rather it be global or page options.

Set page orientation per page?

Hello,

I'm wondering if it's possible to set the page orientation (portrait v landscape) on individual pages instead of globally. I have a need for individual pages to be different orientations across my document.

Thanks.

Unable to generate PDF: syntax error near unexpected token `newline`

I am getting the following error while generating PDF's:

Could not create PDF: Could not run command '/usr/bin/wkhtmltopdf' --no-outline 
--margin-top '0' --margin-right '0' --margin-bottom '0' --margin-left '0' 
/tmp/tmp_WkHtmlToPdf_Re96FH: sh: -c: line 0: syntax error near 
unexpected token `newline' sh: -c: line 0: `'/usr/bin/wkhtmltopdf' --no-outline 
--margin-top '0' --margin-right '0' --margin-bottom '0' --margin-left '0' '

I have setup the basic example as shown on the wiki page.

Footer and Header not working

When I try to add a footer using this code nothing shows up.

$footer = "<html><div style='height:2.54cm;width:100%;background:#cccccc;'>Hello how are you<br/>hhhh<br/>hhhh</div></html>";
$pdf->addPage($top.$specHtml.$modelHtml.$picHtml, array('footer-html' => $footer));

Everything else is generated fine.
When I use the same code but with header-html it show a small white space at the top of my pages but no other content is inserted.

toString() option?

Would a toString() option be a good addition? See below for code:

/**
 * Return the PDF as a string
 *
 * @return string of PDF
 */
public function toString()
{
    if (($pdfFile = $this->getPdfFilename())===false) {
        return null;
    }

    return file_get_contents($pdfFile);
}

PDF generation process fail

I have html date (table with 32 cols and 135 rows in it) on 6 pages of A4 page.

80% of my attempts trying to generate pdf file from this html - fails with an error:
Fatal error: Uncaught exception 'Exception' with message 'Could not create PDF: Could not run command '/var/www/site/bin/wkhtmltopdf-amd64' --footer-center '[page]/[topage]' --dpi '250' --orientation 'landscape' --user-style-sheet '/var/www/site/htdocs/css/pdf.css' --footer-font-size '9' --outline-depth '0' /tmp/tmp_WkHtmlToPdf_qX3Waz.html /tmp/tmp_WkHtmlToPdf_gi862w: ' in /var/www/site/includes/functions/system.php:122 Stack trace: #0 /var/www/site/htdocs/index.php(201): topdf('??? ?

I've commented __destructor() to keep tmp files alive and try to reproduce this error via console, but in console everything works perfect (I'm executing the same command, that shows in error)

With other html data your script works fine for me!

How to find where the problem is?

Style Sheets not being read

I'm trying to get wkhtmltopdf to use a stylesheet, but it doesn't seem to be reading it at all. I'm using:

$pdf->setPageOptions(array('user-style-sheet'=>'/css/layout.css'));

(I also did try to use the full url for the style sheet)

The content I am adding to the pdf is from html text - not from a url - so I also tried linking the style sheet as I would in a normal page:

<!doctype html><!html><!head><!meta charset="UTF-8"><!title>'.$doc['doc_name'].'<!/title><!link rel="stylesheet"href="/css/Layout.css"/><!/head><!body>.......content.........<!/body><!/html>

But it doesn't read this at all. All that it will read is if I put the style inline

<!div style="margin-bottom:2rem">....content....<!/div>

or if I put it in a style section in the html head

<!doctype html><!html><!head><!meta charset="UTF-8"><!title>'.$doc['doc_name'].'<!/title><!style>.divClass{margin-bottom:2rem;}<!/style><!/head><!body>........content........<!/body><!/html>

Any suggestions would be great!!

(obviously my code doesn't have all the ! in it - did that so it would be visible and not try to render it)

binary = __DIR__ . '/vendor/bin/wkhtmltopdf-i386'; $pdf->saveAs('/tmp/new.pdf'); ?>

I'm just trying a simple test but its only returning this in browser:

binary = __DIR__ . '/vendor/bin/wkhtmltopdf-i386'; $pdf->saveAs('/tmp/new.pdf'); ?>

I'm not quite sure why, here's my basic test code:

 <?
use mikehaertl\wkhtmlto\Pdf;

// You can pass a filename, a HTML string or an URL to the constructor
$pdf = new Pdf('/printRdy.php');

// If you installed the binary through composer, you need to configure
// the right path to the binary (modify to match your path/version):
$pdf->binary = __DIR__ . '/vendor/bin/wkhtmltopdf-i386';

$pdf->saveAs('/tmp/new.pdf');
?>

Warning: proc_open(): CreateProcess failed, error code - 2

First, thanks for taking to time to write this PHP wrapper class.

I'm in a bit of a bind and don't have a clue on how to fix this issue. My server is running Windows Server 2008 R2, PHP 5 and Tomcat Apache.

The error cites line 300 in the WkHtmlToPdf.php file:
$process = proc_open($command, $descriptors, $pipes, null, null,barray('bypass_shell'=>true));

I'm not quite sure what this error means, and after googling it there were no viable answers. I think this is more a Windows error than PHP error, but no idea how to resolve it. Any help is greatly appreciated.

Michael

PDF Files

Add pdf files is not working.
Returns :
Could not run command 'wkhtmltopdf/./wkhtmltopdf.app/Contents/MacOS/wkhtmltopdf' /wkhtmltopdf/tmp/rel.PDF /private/var/folders/47/z5_vl81j7hq082xscfv10sf40000gn/T/tmp_WkHtmlToPdf_AjBXBK: Loading pages (1/6) [> ] 0% [======> ] 10% [============================================================] 100% Error: Failed loading page http:///wkhtmltopdf/tmp/rel.PDF (sometimes it will work just to ignore this error with --load-error-handling ignore)

Some requests with patch

Hello, thanks very much for the wrapper.

I have a few requests for which I included a patch below:

  • add support for options with multiple values (--cookie and --custom-header)
  • add a method for returning the PDF as a string or FALSE on failure
  • tempname still uses the system's temporary directory if supplied custom directory does not exist or is not writeable (see http://php.net/tempnam)! I think this behaviour is undesirable/unexpected and a potential security issue, so I suggest to throw an exception when the directory is not writeable. I know is_writeable does not always work correctly, but for me it suffices.

Btw, what's the use for the setPageOptions()? I think it is redundant because the wkhtmltopdf manual states "Options for the page object can be placed in the global options and the page options areas.". So wkhtmltopdf already applies page options supplied globally to every page added.

Index: WkHtmlToPdf.php
===================================================================
--- WkHtmlToPdf.php (revision 56)
+++ WkHtmlToPdf.php (working copy)
@@ -152,6 +152,16 @@
     }

     /**
+     * Return the PDF as a string.
+     *
+     * @return mixed the PDF contents or false on error (triggers PDf creation)
+     */
+    public function getPdf()
+    {
+        return @file_get_contents($this->getPdfFilename());
+    }
+
+    /**
      * Set global option(s)
      *
      * @param array $options list of global options to set as name/value pairs
@@ -228,6 +238,7 @@

     /**
      * @return string path to temp directory
+     * @throws LogicException when the directory is not a directory or is not writeable
      */
     public function getTmpDir()
     {
@@ -235,6 +246,10 @@
             $this->tmp = sys_get_temp_dir();
         }

+        if (!(is_dir($this->tmp) && is_writeable($this->tmp))) {
+          throw new LogicException($this->tmp.' is not a writeable directory');
+        }
+
         return $this->tmp;
     }

@@ -341,6 +356,8 @@
         foreach($options as $key=>$val)
             if (is_numeric($key)) {
                 $out .= " --$val";
+            } else if (is_array($val)) {
+                $out .= " --$key ".implode(' ', $this->enableEscaping ? array_map('escapeshellarg', $val) : $val);
             } else {
                 $out .= " --$key ".($this->enableEscaping ? escapeshellarg($val) : $val);
             }

How should i include your files in my print file..

i am getting this error in my pdf.php
Fatal error: Class 'mikehaertl\wkhtmltopdf\pdf' not found in C:\xampp\htdocs\p\billPdf.php on line 6

binary = **DIR** . '/vendor/bin/wkhtmltopdf-i386'; $pdf->saveAs('/tmp/new.pdf'); ?>

and plz help me how should i convert a file to pdf on a click of a button..
and thanks for your project man it's helping a lot of people...

Add 0.12.0 support?

In case you're not aware, the new version is out:
http://wkhtmltopdf.org/downloads.html

Apparently, this version is "headless" and do not require a display or display service.

Meaning we can get rid of all the xvfb stuff. I'll give this a try within the next month and let you guys know if it works. If someone has time to test it earlier that'd be great.

bypass_cmd

it seems like you have to change
$process = proc_open($command, $descriptors, $pipes, null, null, array('bypass_cmd'=>true));
to
$process = proc_open($command, $descriptors, $pipes, null, null, array('bypass_shell'=>true));
to get this class working in windows
(http://php.net/manual/en/function.proc-open.php)

PDF Generation error, better catch.

Hello, first of all, thank you for your Wrapper, it's really usefull !

I have a problem with some pages like: http://gridster.net/

When i run this command directly with the tool, i get this error:

"Exit with code 1 due to network error: ContentNotFoundError"

But the pdf file is fully generated.. It's this function which catch the errors on generation:

  /**
     * @return mixed the temporary PDF filename or false on error (triggers PDf creation)
     */
    public function getPdfFilename()
    {
        if ($this->tmpFile===null) {
            $tmpFile = tempnam($this->getTmpDir(),'tmp_WkHtmlToPdf_');

            if ($this->createPdf($tmpFile)===true) {
                $this->tmpFile = $tmpFile;
            } else {
                return false;
            }
        }
        return $this->tmpFile;
    }

It's possible to make a better error catching ? For the moment, i just added, a filesize verification on the tmpFile generated and if it's not null, i send the file, i'm pretty sure that there is a better way.

Thank for reading

Fix for send() function

Tested with wkhtmltopdf 0.11.0 rc1 and PHP 5.4.15 Running Nginx web server.

$pdf->send() or $pdf->send('filename.pdf') did not work.

To fix this simply add this two lines inside send() function.

ob_clean();
flush();

(before readfile and after if, here is example)

        if($filename!==null)
            header("Content-Disposition: attachment; filename=\"$filename\"");

ob_clean();
flush();

        readfile($pdfFile);
        return true;

addTOC & addCover caused fatal php error

Using addTOC & addCover caused fatal php error.
Adding the leading "--" to the relevant lines in addTOC & addCover functions seemed to fix this error and PDF was successfully generated.

E.g:
$options[''input] = "--cover $input";
&
$options['input'] = "--toc";

Add License File

Hi,

I'm wondering what the licence is on this wrapper. MIT?

Thanks,
Pete

setOptions bug

The first option set without argument will not visible in the generated command string, because it's key is 0 and the in_array part of setOptions method will fail.

$options = array(
    'encoding' => 'UTF-8',  // option with argument
    'print-media-type',     // option without argument
    'no-outline',           // option without argument

);

'print-media-type' will not exist in command string.

in_array(0, array('bar', 'foo'));   // returns true

Affected code:
https://github.com/mikehaertl/phpwkhtmltopdf/blob/master/WkHtmlToPdf.php#L158

in_array should used with strict = true

Not able to render svg elements

I have been using wkhtmltopdf for a long time. It works great with html elements. But when svg elements come, though it generates the pdf but svg elements are not rendered.

Error on Windows when use javascript

Hi,
first great work, thanks :)
Now the issu :
I try to use phpwkhtmltopdf with somme javascript but i got error with no text error :
this is my error :
Could not run command "C:\inetpub\wwwroot\Communication\Appli\script\..\includes\wkhtmltopdf_x64.exe" --encoding "UTF-8" --orientation "Landscape" --margin-bottom "10mm" --margin-top "20mm" --header-spacing "10" "C:\inetpub\wwwroot\Communication\Appli\script\..\..\Donnees\crises\200\upload\temp\1404832841_tmp_file.html" "C:\Windows\Temp\tmp5E63.tmp":

and this is the content of 1404832841_tmp_file.html :
<!DOCTYPE html><html><head></head><BODY><div>foo</div><script type="text/javascript">document.write("bar");</script></BODY></HTML>

if i set the option disable-javascript, it generate the pdf but whithout "bar"

The same command in shell generate pdf.

what i tried get stdout and system() like you said here
whitout success :(

If you have some idea...
(sorry for my english )...

Wrapper not working when Header or Footer contains spaced Text

When the --header-* or --footer-* option is set with a string containing spaces, the wrapper does not output the result.

For example, this option is not working:
$pdf->setOptions(array('header-left'=>'"ABC A"', ));

Altering the nested quotes in any combination of single/double quotes is also not working. Also, escaping " with \ is not working. But the $command string created by the wrapper works fine when pasted directly at the command prompt.

In the Windows version, the error thrown is:
'C:\Program' is not recognized as an internal or external command, operable program or batch file.
where $bin is set to "C:\Program Files (x86)\wkhtmltopdf\wkhtmltopdf"

createPdf generated errror though command ran fine.

When I tried to generate pdf from google.com page, it won't work and the following error has been dumped out:
string(541) "Could not run command '/var/www/html/pdftext/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64' 'http://www.google.com.jp/' '/var/www/html/pdftext/app/storage/pdf/tmp/pdf_d5b63d348ddb0ae043a70a6d468a2875': Loading pages (1/6) [> ] 0% [======> ] 10% Error: Failed loading page http://www.google.com.jp/ (sometimes it will work just to ignore this error with --load-error-handling ignore) Exit with code 1 due to http error: 1003 "
When I ran the command using the above command, it did generate a file in tmp folder (with no pdf extension).
Please tell me where I did wrong!!
Thank you very much.

`send()` doesn't work for inline display!

I am trying to make the generated PDF be displayed in the user's browser instead of being downloaded, so I replaced $pdf->send('Voucher.pdf') with $pdf->send() but it still makes the file to be downloaded automatically instead of being viewed inside the browser!

send() and send($filename)

Hey! I've been trying for a while now but i can't seem to use both methods at the same time. I'll explain my needs and problems. :D

I have a script generating html strings containing varied info and I have no problem generating the document. But i'd like for users to be able to view the document on the browser window and, only if they want to, save the document. The problem is that when the pdf's save button is pressed, i'm prompted to save the php script instead of .pdf! So, my alternative would be forcing users to view AND save the document (which is wrong but would kind of solve it).

Is there a way to change the filename used to save the document or use both send() methods?

Thanks for your time. :)

PDF Generation Fine - Missing Content when downloading

I'm forcing a PDF download using the $pdf->send() method, as well as using header-html as an option (with a URL to another page). Debugging through it, if I open the file in /tmp the PDF displays fine with the header and body as it should be.

However the downloaded version (from the browser) does not include the header, only the body. I tried using file_get_contents instead of readfile with the exact same results.

I'm using version 1.1.5 - any ideas?

$disposition not used

header("Content-Disposition: $inline; filename=\"$filename\"");

Should be:

header("Content-Disposition: $disposition; filename=\"$filename\"");

External webpage issue

When I try to build a pdf from an external url I get this error.

PHP Fatal error: Uncaught exception 'Exception' with message 'Could not create PDF: Could not run command "wkhtmltopdf" --no-outline --margin-top "0" --margin-right "0" --margin-bottom "0" --margin-left "0" "http://google.com" --disable-smart-shrinking "C:\Windows\Temp\tmp58E1.tmp"

However when I run this command myself it works perfectly so I don't think it is a wkhtmltopdf issue. The error is thrown from line 334 which makes me think proc_close is passing an error along. The pdf file is also not created.

Error code 5 - Access Denied, Windows 7

I can't get the .exe to run from the php script. Has anyone got it working under Windows 7? ( the cmd command works fine) What/ where did you have to set permissions? I have changed permissions under Properties> Security for the bin folder, but no luck. I am a secondary user on the machine, and set as Administrator, the html is in Wamp. Please don't post links to windows list of errors or wkhtmltopdf - nothing helpful there.

Regex to detect HTML string

May i suggest another change, with regard to using HTML strings.

The wrapper checks for the presence of <html> tag in the regex. In my case, the <html> is declared in a common place for using in both web view and producing the pdf. And the tag is declared as <html lang="en">.

My suggestion is to check for the closing html tag </html> which will not contain any additional attributes/properties, implemented through a minor change:
const REGEX_HTML = '/<\/html>/i';

or maybe not just using strpos() instead of regex.

Problemas with header

I'm using version 1.10 and added the _headerHtml variable with its getter and setter. Also in the _getCommand function I added the line
command. = (mb_strlen ($ this-> getHeaderHtml ())> 0)? . "- Header-spacing 15 - header-html " "$ this-> getHeaderHtml ()" \ "": "",. However, the header is not shown, but shown footer
thanks

sometimes no phpwkhtmltopdf pdf creation, although wkhtmltopdf pdf creation ok

Hi,

Debian wheezy 7.3, localhost

  1. WkHtmlToPdf (0.11.0 rc1) command

wkhtmltopdf --use-xserver --disable-javascript --no-background --no-images --grayscale --header-left "[webpage]" --footer-center "[page]/[topage]" --footer-right "[date]" http://github.com/mikehaertl/phpwkhtmltopdf README.pdf

generates the pdf

  1. phpWkHtmlToPdf script (static version 1.2.1):

$pdf->addPage('http://google.com);
$pdf->send('README.pdf');

generates the pdf, however:

$pdf->addPage('http://github.com/mikehaertl/phpwkhtmltopdf');
$pdf->send('README.pdf');

does not generate the pdf

print_r($pdf) output:

WkHtmlToPdf Object ( [binPath:protected] => [binName:protected] => wkhtmltopdf [enableEscaping:protected] => 1 [version9:protected] => [options:protected] => Array ( [0] => grayscale [1] => no-images [2] => no-background [header-font-size] => 10 [header-left] => [webpage] [footer-center] => [page]/[topage] [footer-right] => [date] ) [pageOptions:protected] => Array ( ) [objects:protected] => Array ( [0] => Array ( [input] => http://github.com/mikehaertl/phpwkhtmltopdf ) ) [tmp:protected] => [tmpFile:protected] => [tmpFiles:protected] => Array ( ) [procEnv:protected] => [isWindows:protected] => [enableXvfb:protected] => [xvfbRunBin:protected] => [xvfbRunOptions:protected] => --server-args="-screen 0, 1024x768x24" [error:protected] => [localOptions:protected] => Array ( [0] => binName [1] => binPath [2] => tmp [3] => enableEscaping [4] => version9 [5] => procEnv [6] => enableXvfb [7] => xvfbRunBin [8] => xvfbRunOptions ) )

neither does
$pdf->addPage(""http://github.com/mikehaertl/phpwkhtmltopdf\"");
$pdf->send('README.pdf');
generate the pdf

Cheers,
Alan

wkhtmltopdf not rendering canvas and svg elements

I am converting HTML to PDF with wkhtmltopdf-i386 on Ubuntu 11.10 , Using PHP. With simple HTML and text it is working fine but But HTML script with SVG and Canvas render Blank result means PDF generating but blank.

Warning: proc_open(): CreateProcess failed, error code - 2

Hi,
I'm currently trying to use your wkhtmltopdf but I cannot get passed a Warning call saying :

Warning: proc_open() [function.proc-open]: CreateProcess failed, error code - 87 in Path/To/WkHtmlToPdf.php on line 325

I tried with a basic code given in the tutorial but it doesn't work.

$pdf = new WkHtmlToPdf;
$pdf->addPage('http://google.com');
$pdf->send();

The error code 87 stands for invalid parameter.
Anyone can help me ?

Thank you

Unable to add more than one page to a PDF Document

I am having problems adding multiple pages to a PDF document using the great PHP wkHTMLToPdf wrapper.

The following code just gives me a blank page.


require_once('phpwkhtmltopdf/WkHtmlToPdf.php');
$pdf = new WkHtmlToPdf;

$pdf->addPage('http://www.google.co.uk');
$pdf->addPage('http://www.google.co.uk');

$pdf->send('test.pdf');
exit();


but this works fine.


require_once('phpwkhtmltopdf/WkHtmlToPdf.php');
$pdf = new WkHtmlToPdf;

$pdf->addPage('http://www.google.co.uk');

$pdf->send('test.pdf');
exit();


Passing a binary string with spaces

I'm trying to get the binary string right because I keep getting this error:

'/..\..\..\Program' is not recognized as an internal or external command, operable program or batch file. 

And here's the getCommand():

"/..\..\..\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"/ --no-outline --margin-top "0" --margin-right "0" --margin-bottom "0" --margin-left "0" --disable-smart-shrinking "printRdy.php" "C:\Windows\Temp\tmpBA0B.tmp.pdf"

From this code:

<?php

require_once '/vendor/autoload.php';

use mikehaertl\wkhtmlto\Pdf;

$options = array(
    'no-outline',         // Make Chrome not complain
    'margin-top'    => 0,
    'margin-right'  => 0,
    'margin-bottom' => 0,
    'margin-left'   => 0,

    // Default page options
    'disable-smart-shrinking'
);

$pdf = new Pdf($options);
$pdf->binary ='"/..\..\..\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"/';
$pdf->addPage('printRdy.php');
$pdf->saveAs('print.pdf');
echo $pdf->getError();
echo "<br>", $pdf->getCommand();

?>

I know this is the right string path because I ran php-shellcommand with this string and the command executes just fine. Here's the string I ran in php-shellcommand:

'"/..\..\..\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"/ http://localhost/Ponudomat/printRdy.php print.pdf'

So the problem is created by "/ and the wired thing is that the same is in the s

I've closed the tread to move it to shellcommand as it does turn out to be a php-shellcommand problem

Error checking bug

Hi all, I'm using the following:

// Save the PDF
$pdf->saveAs('/home/path/images/PDFs/new2222.pdf');

if(!$pdf->saveAs())
    throw new Exception('Could not create PDF: '.$pdf->getError());

Which produces the following error although saves the file perfectly:

Warning: Missing argument 1 for WkHtmlToPdf::saveAs(), called in /home/path/testScreenshots/test.php on line 22 and defined in /home/path/testScreenshots/WkHtmlToPdf.php on line 172

Warning: copy() [function.copy]: Filename cannot be empty in /home/path/testScreenshots/WkHtmlToPdf.php on line 177

If I try reverse the error check I get the same

if($pdf->saveAs()) {
    echo 'ok';
}

Output above 6 pages is not working

I have noticed another issue. Output above 6 pages is not working.
I am trying to generate PDF through a string.

Example, i have created a table in html, which when output in A4 size would come to 8 pages. If the page is set to A3, the output is received (coming upto 6 pages), but on changing the paper size to A4, there is no output.

Typing the instruction, generated through the class, at the Windows command prompt works, with A4 output correctly being received in 8 pages, but doing the same in PHP produces no ouput.

Debugging hangs in this line:
$stdout = stream_get_contents($pipes[1]);

missing dependencies

Hi,

Great job with this tool.
I was trying to get this working but I think there are some files missing ( i downloaded through here the latest version).
For example mikehaertl\shellcommand\Command as BaseCommand is required.

Much appreciated

try to save PDFs but save the same pdf

i want to save diferent pdfs, but only save the same pdf
this is the code that i use
$pdf = new Wkpdf_Utility();
$x = 0;
foreach ($XMLs as $file) {
$this->view->data = $file;
$pdf->addPage($this->view->render("pdf.phtml"));
$pdf->saveAs(APPLICATION_PATH.'/../data/temp-pdf/'.$x.'.pdf');
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.