Created
March 18, 2019 21:40
-
-
Save Unifex/e96a2fd48fc0d1a745f40d7f57ed2fed to your computer and use it in GitHub Desktop.
This file provides a practical test of using Chrome PHP and PHPUnite to create a PDF of multiple pages from the web.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* A test of using Headless Chrome and the Linux CLI tool phpunite. | |
* | |
* Save this file to a directory. | |
* Run `composer require chrome-php/chrome` in the same directory | |
* If you are using Chromium run `export CHROME_PATH=chromium-browser` | |
* Run `php -S localhost:8080` to start a local server. | |
* Open http://localhost:8080 in a browser. | |
*/ | |
?><html> | |
<head> | |
<title>PHP Chrome + PDFUnite</title> | |
</head> | |
<body> | |
<?php | |
require __DIR__ . '/vendor/autoload.php'; | |
use HeadlessChromium\BrowserFactory; | |
$urls = [ | |
'https://mahara.org/view/view.php?id=2', | |
'https://mahara.org/interaction/forum/topic.php?id=8408', | |
'https://mahara.org/view/view.php?id=72397', | |
'https://wiki.mahara.org/wiki/Contributors', | |
'https://wiki.mahara.org/wiki/Developer_Area', | |
]; | |
$pdfs = []; | |
$target = __DIR__ . '/pdfs'; | |
if (!is_dir($target)) { | |
mkdir($target); | |
} | |
$browserFactory = new BrowserFactory(); | |
// Starts headless chrome. | |
$browser = $browserFactory->createBrowser(); | |
// Creates a new page object. | |
$page = $browser->createPage(); | |
for ($i = 0; $i < count($urls); $i++) { | |
// Browse to a URL. | |
$page->navigate($urls[$i])->waitForNavigation(); | |
$pdf = $target . '/page_' . $i . '.pdf'; | |
$pdfs[] = $pdf; | |
echo "Fetching ${urls[$i]} to $pdf<br />\n"; | |
// Save to a PDF. | |
$page->pdf(['printBackground' => FALSE])->saveToFile($pdf); | |
} | |
$browser->close(); | |
$output = []; | |
exec( | |
'pdfunite ' . implode(' ', $pdfs) . ' ' . $target . '/document.pdf', | |
$output | |
); | |
?> | |
<ul> | |
<li><?php print implode("</li>\n <li>", $output); ?></li> | |
</ul> | |
<a href="/pdfs/document.pdf">Download PDF</a> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment