Skip to content

Instantly share code, notes, and snippets.

@Jibbarth
Created June 1, 2017 13:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Jibbarth/b2f925ebad25d1b48f2177d3b9923ac9 to your computer and use it in GitHub Desktop.
Convert pdf / PHP / Imagick

This snippet show how downgrade a PDF not mergeable with PDFMerger using Imagick and Ghostscript.

$sPathName = realpath($oFile->getPathname());
$oIm = new Imagick($sPathName);
$iNoOfPagesInPDF = $oIm->getNumberImages();
if ($iNoOfPagesInPDF) {
$aPdfPagePath = [];
for ($i = 0; $i < $iNoOfPagesInPDF; $i++) {
$sUrl = $sPathName . '[' . $i . ']';
$sPath = '/tmp/' . $oFile->getFilename() . '_' . ($i + 1) . '.pdf';
$oImage = new Imagick();
$oImage->setResolution(300, 300);
$oImage->readImage($sUrl);
$oImage->setImageFormat("pdf");
$oImage->writeImage($sPath);
$oImage->clear();
$oImage->destroy();
$aPdfPagePath[] = $sPath;
}
//Add pdf uploaded to the original pdf
$oPdf = new PDFMerger();
foreach ($aPdfPagePath as $sPath) {
$oPdf->addPDF($sPath);
}
$oPdf->merge('file', $sPathName . '.pdf', 'P');
}
$oIm->clear();
$oIm->destroy();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment