Skip to content

Instantly share code, notes, and snippets.

@dccampbell
Created October 1, 2018 07:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dccampbell/8ea06424d91c1f1f984796c8893421b4 to your computer and use it in GitHub Desktop.
Save dccampbell/8ea06424d91c1f1f984796c8893421b4 to your computer and use it in GitHub Desktop.
Minimal PHP example of printing HTML to PDF using Headless Chrome
<?php
$chromeExec = 'google-chrome';
$inputFile = __DIR__.'/input.html';
$outputFile = __DIR__.'/output.pdf';
$version = shell_exec($chromeExec . ' --version 2>&1');
if(!strpos($version, 'Google Chrome') === 0) {
throw new Exception('Google Chrome not found at: '.$chromeExec);
}
$html = file_get_contents($inputFile);
$url = 'data:text/html,' . rawurlencode($html);
$command = sprintf(
'%s --headless --disable-gpu --print-to-pdf=%s %s 2>&1', $chromeExec, escapeshellarg($outputFile), escapeshellarg($url)
);
exec($command);
@dccampbell
Copy link
Author

Install Chrome on CentOS:

wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
sudo yum install -y ./google-chrome-stable_current_x86_64.rpm 
sudo yum install -y liberation-fonts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment