Menü schliessen
Created: June 25th 2025
Last updated: June 25th 2025
Categories: IT Development
Author: Aleksandar Pantic

How to Use wkhtmltopdf in WordPress for Dynamic PDF Generation

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Generating dynamic PDFs in WordPress can enhance user experience by providing downloadable content like reports, lists, or invoices. wkhtmltopdf is a powerful open-source tool that converts HTML to PDF using the WebKit rendering engine, making it ideal for WordPress applications. This blog post explores how to implement wkhtmltopdf in WordPress, using AJAX for seamless PDF generation.

What is wkhtmltopdf?

wkhtmltopdf is a command-line utility that transforms HTML content into high-quality PDF documents. It’s perfect for WordPress sites that need to generate PDFs from dynamic data, such as post lists or custom post types. By integrating it with WordPress’s AJAX functionality, you can allow users to download custom PDFs based on their selections.

Setting Up wkhtmltopdf

To use wkhtmltopdf in WordPress, follow these steps:

  • Install wkhtmltopdf on your server. For example, on Ubuntu, run:
    sudo apt-get install wkhtmltopdf
  • Install the PHP library. Use the mikehaertl/phpwkhtmltopdf library to simplify integration with PHP. You can install it via Composer:
    composer require mikehaertl/phpwkhtmltopdf

    Alternatively, download it from the official GitHub repository: Download and include it manually in your project.

  • Set up AJAX to handle user requests and trigger PDF generation.

Example: Generating PDFs with AJAX

Below is a basic example of generating a PDF of selected items (e.g., blog posts) using AJAX and wkhtmltopdf. This setup allows users to select items and download a PDF with a custom layout.

Step 1: Front-End AJAX Script

The JavaScript code handles user selections and sends an AJAX request to generate the PDF.

const downloadPDF = async (button, mode) => {
    const contentWrapper = document.querySelector('#items-container');
    button.classList.add('loading');

    let selectedItems = [];
    if (mode === 'selected') {
        const checkedBoxes = document.querySelectorAll('input[name="content-select"]:checked');
        selectedItems = Array.from(checkedBoxes).map(box => box.value);
    }

    const payload = {
        action: 'render_pdf',
        export_mode: mode,
        item_ids: JSON.stringify(selectedItems),
        section: contentWrapper ? contentWrapper.dataset.section : ''
    };

    const response = await ajaxFetch(payload);

    if (response instanceof Blob) {
        const date = new Date();
        const dateString = `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`;
        const fileName = `content_${dateString}.pdf`;

        const link = document.createElement('a');
        const pdfFile = new File([response], fileName, { type: 'application/pdf' });
        link.href = window.URL.createObjectURL(pdfFile);
        link.download = fileName;
        link.click();
        link.remove();

        button.classList.remove('loading');
    }
};

This script collects selected item IDs, sends an AJAX request, and creates a downloadable PDF from the response.

Step 2: Back-End PHP Handler

The PHP function processes the AJAX request, fetches the content, and uses wkhtmltopdf to generate the PDF.

<?php
function render_pdf_document() {
    require_once __DIR__ . '/vendor/autoload.php'; // Load wkhtmltopdf library
    use mikehaertl\wkhtmlto\Pdf;

    $export_mode = $_POST['export_mode'] ?? '';
    $section = $_POST['section'] ?? '';
    $item_ids = [];

    if ($export_mode === 'selected' && !empty($_POST['item_ids'])) {
        $item_ids = json_decode(stripslashes($_POST['item_ids']), true);
        if (empty($item_ids)) {
            wp_send_json_error(['message' => 'No items selected.']);
            return;
        }
    } else {
        $item_ids = get_content_ids($section); // Custom function to fetch IDs
        if (empty($item_ids)) {
            wp_send_json_error(['message' => 'No content found.']);
            return;
        }
    }

    // Generate HTML for PDF
    $html = create_pdf_template($item_ids); // Custom function for HTML

    // Initialize wkhtmltopdf
    $pdf = new Pdf([
        'binary' => '/usr/local/bin/wkhtmltopdf',
        'options' => [
            'page-size' => 'A4',
            'header-html' => create_pdf_header(),
            'footer-html' => create_pdf_footer()
        ]
    ]);

    $pdf->addPage($html);

    if (!$pdf->send()) {
        wp_send_json_error(['message' => 'PDF generation failed.']);
    }
}
add_action('wp_ajax_render_pdf', 'render_pdf_document');
add_action('wp_ajax_nopriv_render_pdf', 'render_pdf_document');
?>

This function validates the request, retrieves item IDs, generates HTML, and converts it to a PDF using wkhtmltopdf.

Step 3: HTML Template

The create_pdf_template function (not shown) generates an HTML structure, such as a list of posts with titles and excerpts, styled with CSS for the PDF.

Why Use wkhtmltopdf?

  • Professional Output: Supports complex HTML and CSS for polished PDFs.
  • Customization: Add headers, footers, and custom page settings.
  • Dynamic Integration: Works seamlessly with AJAX for user-driven PDFs.

Challenges to Consider

  • Server Setup: Requires wkhtmltopdf installation, which may need server access.
  • Performance: Large PDFs can be resource-heavy; optimize HTML and test thoroughly.
  • Security: Sanitize user inputs to prevent injection risks.

Conclusion

Using wkhtmltopdf with WordPress and AJAX enables dynamic PDF generation for a better user experience. This example provides a foundation for creating custom PDFs based on user selections. Experiment with HTML templates and styling to match your site’s branding, and test for performance and compatibility. With wkhtmltopdf, you can take your WordPress site’s functionality to new heights.