knplabs/knp-snappy
PHP wrapper for wkhtmltopdf/wkhtmltoimage to generate PDFs and images (thumbnails, snapshots) from URLs or HTML. Simple API, configurable binaries and options, with integrations available for Symfony and Laravel.
Install the Package
composer require knplabs/knp-snappy
For Laravel, consider using the dedicated bundle:
composer require barryvdh/laravel-snappy
Install wkhtmltopdf
Download the correct version (0.12.x) from wkhtmltopdf.org and ensure it's executable.
For automated installation via Composer (Linux):
composer require h4cc/wkhtmltopdf-amd64 # 64-bit
# or
composer require h4cc/wkhtmltopdf-i386 # 32-bit
Basic Usage
Initialize the Pdf class with the binary path:
use Knp\Snappy\Pdf;
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
echo $snappy->getOutput('https://example.com');
Generating PDFs
$snappy->getOutput('https://example.com');
$snappy->generateFromHtml('<h1>Hello</h1>', 'output.pdf');
$snappy->getOutput(['https://url1.com', 'https://url2.com']);
Generating Images
Use the Image class for thumbnails/snapshots:
use Knp\Snappy\Image;
$image = new Image('/usr/local/bin/wkhtmltoimage');
$image->getOutput('https://example.com');
Streaming Responses For browser display or downloads:
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
echo $snappy->getOutput('https://example.com');
Laravel Integration
Use barryvdh/laravel-snappy for seamless Laravel integration:
use Barryvdh\Snappy\SnappyPdf;
$pdf = SnappyPdf::loadView('pdf.template', ['data' => $data]);
return $pdf->stream('filename.pdf');
Queueing Long-Running Tasks Offload PDF generation to a queue (e.g., Laravel Queues):
dispatch(new GeneratePdfJob($url, $filename));
Dynamic Options Set options dynamically based on context:
$snappy->setOption('margin-top', '20mm');
$snappy->setOption('margin-bottom', '20mm');
$snappy->setOption('orientation', 'Landscape');
Caching Cache generated PDFs to avoid reprocessing:
$cacheKey = 'pdf_' . md5($url);
if (cache()->has($cacheKey)) {
return cache()->get($cacheKey);
}
$pdf = $snappy->getOutput($url);
cache()->put($cacheKey, $pdf, now()->addHours(1));
return $pdf;
Error Handling
Validate wkhtmltopdf output and handle failures:
try {
$pdf = $snappy->getOutput($url);
} catch (\Knp\Snappy\Exception\GenerationException $e) {
Log::error('PDF generation failed: ' . $e->getMessage());
return response()->view('errors.pdf_failed');
}
Binary Path Issues
// ❌ Avoid (deprecated)
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf --quiet');
// ✅ Correct
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->setOption('quiet', true);
Security Risks
--enable-local-file-access for untrusted HTML/JS.Memory Limits
memory_limit or optimize the input:
ini_set('memory_limit', '512M');
Cross-Platform Paths
/) or DIRECTORY_SEPARATOR for paths:
$snappy->setOption('cache-dir', storage_path('app') . DIRECTORY_SEPARATOR . 'cache');
Temporary Files
$snappy->setOption('temp-dir', sys_get_temp_dir());
Check wkhtmltopdf Logs
Enable verbose logging to diagnose issues:
$snappy->setOption('debug-javascript', true);
$snappy->setOption('log-level', '9');
Validate HTML/JS Test HTML/JS in a browser first. Use tools like Puppeteer for debugging.
Process Output
Capture wkhtmltopdf stderr for errors:
$output = $snappy->getOutput($url, ['output' => 'output.pdf']);
$error = $snappy->getErrorOutput();
Log::error($error);
Common Errors
chmod +x).robots.txt).Custom Options
Extend Snappy to support custom wkhtmltopdf options:
$snappy->setOption('custom-header', ['User-Agent' => 'MyAgent/1.0']);
Pre/Post-Processing Hook into the generation process:
$snappy->generateFromHtml($html, 'output.pdf');
// Post-process the file (e.g., compress, sign)
Event Listeners Use Laravel events to trigger actions before/after PDF generation:
event(new PdfGenerated($pdfPath, $url));
Fallback Mechanisms
Implement fallback to alternative libraries (e.g., Dompdf) if wkhtmltopdf fails:
try {
$pdf = $snappy->getOutput($url);
} catch (\Exception $e) {
$pdf = app(\Dompdf\Dompdf::class)->loadHtml($html)->output();
}
Default Options Reset options to defaults:
$snappy->resetOptions();
Option Order
Options are passed in the order they are set. Critical options (e.g., quiet) should be set first.
Windows-Specific On Windows, ensure paths use backslashes or forward slashes:
$snappy->setOption('cache-dir', 'C:/temp/cache');
Docker Environments
Mount the wkhtmltopdf binary into the container:
COPY --from=wkhtmltopdf /usr/local/bin/wkhtmltopdf /usr/local/bin/
How can I help you explore Laravel packages today?