public static function loadPdf($pdfFile, $pageWidth = 550)
{
if (!EscposImage::isImagickLoaded()) {
throw new Exception(__FUNCTION__ . " requires imagick extension.");
}
/*
* Load first page at very low density (resolution), to figure out what
* density to use to achieve $pageWidth
*/
try {
$image = new \Imagick();
$testRes = 2;
// Test resolution
$image->setresolution($testRes, $testRes);
/* Load document just to measure geometry */
$image->readimage($pdfFile);
$geo = $image->getimagegeometry();
$image->destroy();
$width = $geo['width'];
$newRes = $pageWidth / $width * $testRes;
/* Load entire document in */
$image->setresolution($newRes, $newRes);
$image->readImage($pdfFile);
$pages = $image->getNumberImages();
/* Convert images to Escpos objects */
$ret = array();
for ($i = 0; $i < $pages; $i++) {
$image->setIteratorIndex($i);
$ep = new ImagickEscposImage();
$ep->readImageFromImagick($image);
$ret[] = $ep;
}
return $ret;
} catch (\ImagickException $e) {
/* Wrap in normal exception, so that classes which call this do not
* themselves require imagick as a dependency. */
throw new Exception($e);
}
}
foreach ($pages as $page) { $printer->graphics($page, Printer::IMG_DOUBLE_HEIGHT | Printer::IMG_DOUBLE_WIDTH); } $printer->cut(); $printer->close(); /* * 3: PDF printing still too slow? If you regularly print the same files, serialize & compress your * EscposImage objects (after printing[1]), instead of throwing them away. * * (You can also do this to print logos on computers which don't have an * image processing library, by preparing a serialized version of your logo on your PC) * * [1]After printing, the pixels are loaded and formatted for the print command you used, so even a raspberry pi can print complex PDF's quickly. */ $connector = new FilePrintConnector("php://stdout"); $printer = new Printer($connector); $pdf = 'resources/document.pdf'; $ser = 'resources/document.z'; if (!file_exists($ser)) { $pages = ImagickEscposImage::loadPdf($pdf); } else { $pages = unserialize(gzuncompress(file_get_contents($ser))); } foreach ($pages as $page) { $printer->graphics($page); } $printer->cut(); $printer->close(); if (!file_exists($ser)) { file_put_contents($ser, gzcompress(serialize($pages))); }