Could we help you? Please click the banners. We are young and desperately need the money
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.
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.
To use wkhtmltopdf in WordPress, follow these steps:
sudo apt-get install wkhtmltopdf
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.
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.
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.
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.
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.
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.