Convert Figma logo to code with AI

mikehaertl logophpwkhtmltopdf

A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface

1,597
238
1,597
3

Top Related Projects

4,377

PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage

Laravel Snappy PDF

10,446

HTML to PDF converter for PHP

4,147

Official clone of PHP library to generate PDF documents and barcodes

4,355

PHP library generating PDF files from UTF-8 encoded HTML

Quick Overview

phpwkhtmltopdf is a PHP wrapper for the wkhtmltopdf command line tool. It allows you to easily create PDF files from HTML content in your PHP applications. The library provides a clean and intuitive API for configuring and generating PDFs using wkhtmltopdf.

Pros

  • Easy to use and integrate into existing PHP projects
  • Supports a wide range of wkhtmltopdf options and configurations
  • Allows for both file-based and in-memory PDF generation
  • Actively maintained with regular updates and bug fixes

Cons

  • Requires wkhtmltopdf to be installed on the server
  • May have performance limitations for large-scale PDF generation
  • Some advanced features of wkhtmltopdf might not be fully exposed through the wrapper

Code Examples

  1. Basic PDF generation from a URL:
use mikehaertl\wkhtmlto\Pdf;

$pdf = new Pdf('https://example.com');
if (!$pdf->saveAs('example.pdf')) {
    echo $pdf->getError();
}
  1. Generating a PDF from HTML content:
$pdf = new Pdf;
$pdf->addPage('<html><body><h1>Hello World</h1></body></html>');
if (!$pdf->send()) {
    echo $pdf->getError();
}
  1. Configuring PDF options:
$pdf = new Pdf(array(
    'page-size' => 'A4',
    'orientation' => 'Landscape',
    'margin-top' => 0,
    'margin-right' => 0,
    'margin-bottom' => 0,
    'margin-left' => 0,
));
$pdf->addPage('https://example.com');
$pdf->saveAs('example.pdf');

Getting Started

  1. Install the library using Composer:
composer require mikehaertl/phpwkhtmltopdf
  1. Ensure wkhtmltopdf is installed on your server.

  2. Use the library in your PHP code:

use mikehaertl\wkhtmlto\Pdf;

$pdf = new Pdf('https://example.com');
if ($pdf->saveAs('example.pdf')) {
    echo "PDF saved successfully";
} else {
    echo "Error: " . $pdf->getError();
}

This basic example demonstrates how to create a PDF from a URL and save it to a file. You can explore more advanced features and options in the library's documentation.

Competitor Comparisons

4,377

PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage

Pros of snappy

  • More actively maintained with recent updates
  • Supports both PDF and image generation
  • Offers a Symfony bundle for easier integration

Cons of snappy

  • Less flexible configuration options
  • Fewer customization features for PDF output
  • Slightly steeper learning curve for non-Symfony users

Code Comparison

snappy:

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->generateFromHtml('<h1>Hello World</h1>', '/path/to/output.pdf');

phpwkhtmltopdf:

$pdf = new Pdf('/path/to/input.html');
$pdf->setBinary('/usr/local/bin/wkhtmltopdf');
$pdf->saveAs('/path/to/output.pdf');

Both libraries provide a wrapper for wkhtmltopdf, but their usage differs slightly. snappy focuses on generating PDFs from HTML strings or URLs, while phpwkhtmltopdf offers more granular control over the PDF generation process.

snappy is better suited for projects already using Symfony or requiring image generation capabilities. phpwkhtmltopdf, on the other hand, provides more flexibility and configuration options, making it a good choice for projects that need fine-tuned control over PDF output.

Ultimately, the choice between these libraries depends on your project's specific requirements, framework preferences, and desired level of customization for PDF generation.

Laravel Snappy PDF

Pros of laravel-snappy

  • Seamless integration with Laravel framework, providing a more native experience for Laravel developers
  • Offers both PDF and image generation capabilities out of the box
  • Provides a simple and intuitive API for generating PDFs within Laravel applications

Cons of laravel-snappy

  • Limited to Laravel ecosystem, not suitable for standalone PHP projects
  • Requires additional setup and configuration compared to phpwkhtmltopdf
  • May have a steeper learning curve for developers not familiar with Laravel

Code Comparison

laravel-snappy:

use Barryvdh\Snappy\Facades\SnappyPdf;

$pdf = SnappyPdf::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');

phpwkhtmltopdf:

use mikehaertl\wkhtmlto\Pdf;

$pdf = new Pdf('http://example.com');
if (!$pdf->saveAs('file.pdf')) {
    echo $pdf->getError();
}

Both libraries provide straightforward methods for generating PDFs, but laravel-snappy leverages Laravel's view system, while phpwkhtmltopdf offers a more generic approach suitable for any PHP project. The choice between them largely depends on whether you're working within a Laravel environment or need a standalone solution for PHP-based PDF generation.

10,446

HTML to PDF converter for PHP

Pros of dompdf

  • Pure PHP implementation, no external dependencies required
  • Easier to install and integrate into existing PHP projects
  • Better support for CSS styling and positioning

Cons of dompdf

  • Slower performance, especially for complex documents
  • Limited support for advanced HTML5 and CSS3 features
  • May struggle with rendering complex layouts or large documents

Code Comparison

dompdf:

require_once 'dompdf/autoload.inc.php';
$dompdf = new Dompdf\Dompdf();
$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream("document.pdf");

phpwkhtmltopdf:

use mikehaertl\wkhtmlto\Pdf;
$pdf = new Pdf($html);
if (!$pdf->saveAs('document.pdf')) {
    echo $pdf->getError();
}

Both libraries offer straightforward ways to generate PDFs from HTML, but phpwkhtmltopdf relies on the external wkhtmltopdf binary, which can provide better rendering quality and support for modern web technologies. dompdf, being a pure PHP solution, is easier to set up but may have limitations in rendering complex layouts. The choice between the two depends on specific project requirements, such as rendering accuracy, performance needs, and deployment constraints.

4,147

Official clone of PHP library to generate PDF documents and barcodes

Pros of TCPDF

  • Native PHP implementation, no external dependencies required
  • Extensive support for various image formats and barcode types
  • More fine-grained control over PDF layout and elements

Cons of TCPDF

  • Steeper learning curve due to more complex API
  • Generally slower performance, especially for large documents
  • Limited HTML support compared to phpwkhtmltopdf

Code Comparison

TCPDF:

$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'Hello, World!', 0, 1);
$pdf->Output('example.pdf', 'F');

phpwkhtmltopdf:

$pdf = new Pdf('http://example.com');
$pdf->saveAs('example.pdf');

TCPDF offers more granular control over PDF creation but requires more code for basic tasks. phpwkhtmltopdf provides a simpler API for converting HTML to PDF, making it easier to use for straightforward conversions. However, TCPDF's native PHP implementation and extensive feature set make it more suitable for complex PDF generation tasks that don't rely heavily on HTML input.

4,355

PHP library generating PDF files from UTF-8 encoded HTML

Pros of mpdf

  • Native PHP implementation, no external dependencies required
  • Supports complex layouts, including headers, footers, and page numbering
  • Extensive CSS support, including custom fonts and styles

Cons of mpdf

  • Slower performance compared to wkhtmltopdf, especially for large documents
  • Limited support for modern web technologies like JavaScript and SVG
  • May produce larger file sizes for complex documents

Code Comparison

mpdf:

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('<h1>Hello World</h1>');
$mpdf->Output('document.pdf', 'F');

phpwkhtmltopdf:

$pdf = new Pdf('http://example.com');
$pdf->saveAs('document.pdf');

mpdf is a pure PHP library that generates PDFs directly from HTML and CSS, offering extensive layout control and styling options. It's ideal for projects requiring complex document structures without external dependencies.

phpwkhtmltopdf, on the other hand, is a wrapper for the wkhtmltopdf command-line tool. It excels in rendering modern web pages, including JavaScript and CSS3, but requires the external wkhtmltopdf binary to be installed.

Choose mpdf for projects needing fine-grained control over PDF generation within a PHP environment. Opt for phpwkhtmltopdf when dealing with modern web pages or requiring faster rendering of large documents.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.