//DEBUG_IMG_TEMP //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print 'trouble writing file from GD'; } } if ($error) { $this->addMessage('PNG error - (' . $file . ') ' . $errormsg); return; } } //End isset($this->imagelist[$file]) (png Duplicate removal) $this->addPngFromBuf($data, $file, $x, $y, $w, $h, $is_mask, $mask); } /** * @param $file * @param $x * @param $y * @param $w * @param $h * @param $byte */ protected function addImagePngAlpha($file, $x, $y, $w, $h, $byte) { // generate images $img = @imagecreatefrompng($file); if ($img === false) { return; } // FIXME The pixel transformation doesn't work well with 8bit PNGs $eight_bit = ($byte & 4) !== 4; $wpx = imagesx($img); $hpx = imagesy($img); imagesavealpha($img, false); // create temp alpha file $tempfile_alpha = @tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_alpha); $tempfile_alpha = "$tempfile_alpha.png"; // create temp plain file $tempfile_plain = @tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_plain); $tempfile_plain = "$tempfile_plain.png"; $imgalpha = imagecreate($wpx, $hpx); imagesavealpha($imgalpha, false); // generate gray scale palette (0 -> 255) for ($c = 0; $c < 256; ++$c) { imagecolorallocate($imgalpha, $c, $c, $c); } // Use PECL gmagick + Graphics Magic to process transparent PNG images if (extension_loaded("gmagick")) { $gmagick = new \Gmagick($file); $gmagick->setimageformat('png'); // Get opacity channel (negative of alpha channel) $alpha_channel_neg = clone $gmagick; $alpha_channel_neg->separateimagechannel(\Gmagick::CHANNEL_OPACITY); // Negate opacity channel $alpha_channel = new \Gmagick(); $alpha_channel->newimage($wpx, $hpx, "#FFFFFF", "png"); $alpha_channel->compositeimage($alpha_channel_neg, \Gmagick::COMPOSITE_DIFFERENCE, 0, 0); $alpha_channel->separateimagechannel(\Gmagick::CHANNEL_RED); $alpha_channel->writeimage($tempfile_alpha); // Cast to 8bit+palette $imgalpha_ = @imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); // Make opaque image $color_channels = new \Gmagick(); $color_channels->newimage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeimage($gmagick, \Gmagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeimage($gmagick, \Gmagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeimage($gmagick, \Gmagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeimage($tempfile_plain); $imgplain = @imagecreatefrompng($tempfile_plain); } // Use PECL imagick + ImageMagic to process transparent PNG images elseif (extension_loaded("imagick")) { // Native cloning was added to pecl-imagick in svn commit 263814 // the first version containing it was 3.0.1RC1 static $imagickClonable = null; if ($imagickClonable === null) { $imagickClonable = true; if (defined('Imagick::IMAGICK_EXTVER')) { $imagickVersion = \Imagick::IMAGICK_EXTVER; } else { $imagickVersion = '0'; } if (version_compare($imagickVersion, '0.0.1', '>=')) { $imagickClonable = version_compare($imagickVersion, '3.0.1rc1', '>='); } } $imagick = new \Imagick($file); $imagick->setFormat('png'); // Get opacity channel (negative of alpha channel) if ($imagick->getImageAlphaChannel()) { $alpha_channel = $imagickClonable ? clone $imagick : $imagick->clone(); $alpha_channel->separateImageChannel(\Imagick::CHANNEL_ALPHA); // Since ImageMagick7 negate invert transparency as default if (\Imagick::getVersion()['versionNumber'] < 1800) { $alpha_channel->negateImage(true); } $alpha_channel->writeImage($tempfile_alpha); // Cast to 8bit+palette $imgalpha_ = @imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); } else { $tempfile_alpha = null; } // Make opaque image $color_channels = new \Imagick(); $color_channels->newImage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeImage($imagick, \Imagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeImage($imagick, \Imagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeImage($imagick, \Imagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeImage($tempfile_plain); $imgplain = @imagecreatefrompng($tempfile_plain); } else { // allocated colors cache $allocated_colors = []; // extract alpha channel for ($xpx = 0; $xpx < $wpx; ++$xpx) { for ($ypx = 0; $ypx < $hpx; ++$ypx) { $color = imagecolorat($img, $xpx, $ypx); $col = imagecolorsforindex($img, $color); $alpha = $col['alpha']; if ($eight_bit) { // with gamma correction $gammacorr = 2.2; $pixel = round(pow((((127 - $alpha) * 255 / 127) / 255), $gammacorr) * 255); } else { // without gamma correction $pixel = (127 - $alpha) * 2; $key = $col['red'] . $col['green'] . $col['blue']; if (!isset($allocated_colors[$key])) { $pixel_img = imagecolorallocate($img, $col['red'], $col['green'], $col['blue']); $allocated_colors[$key] = $pixel_img; } else { $pixel_img = $allocated_colors[$key]; } imagesetpixel($img, $xpx, $ypx, $pixel_img); } imagesetpixel($imgalpha, $xpx, $ypx, $pixel); } } // extract image without alpha channel $imgplain = imagecreatetruecolor($wpx, $hpx); imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($img); imagepng($imgalpha, $tempfile_alpha); imagepng($imgplain, $tempfile_plain); } $this->imageAlphaList[$file] = [$tempfile_alpha, $tempfile_plain]; // embed mask image if ($tempfile_alpha) { $this->addImagePng($imgalpha, $tempfile_alpha, $x, $y, $w, $h, true); imagedestroy($imgalpha); $this->imageCache[] = $tempfile_alpha; } // embed image, masked with previously embedded mask $this->addImagePng($imgplain, $tempfile_plain, $x, $y, $w, $h, false, ($tempfile_alpha !== null)); imagedestroy($imgplain); $this->imageCache[] = $tempfile_plain; } /** * add a PNG image into the document, from a file * this should work with remote files * * @param $file * @param $x * @param $y * @param int $w * @param int $h * @throws Exception */ function addPngFromFile($file, $x, $y, $w = 0, $h = 0) { if (!function_exists("imagecreatefrompng")) { throw new \Exception("The PHP GD extension is required, but is not installed."); } if (isset($this->imageAlphaList[$file])) { [$alphaFile, $plainFile] = $this->imageAlphaList[$file]; if ($alphaFile) { $img = null; $this->addImagePng($img, $alphaFile, $x, $y, $w, $h, true); } $img = null; $this->addImagePng($img, $plainFile, $x, $y, $w, $h, false, ($plainFile !== null)); return; } //if already cached, need not to read again if (isset($this->imagelist[$file])) { $img = null; } else { $info = file_get_contents($file, false, null, 24, 5); $meta = unpack("CbitDepth/CcolorType/CcompressionMethod/CfilterMethod/CinterlaceMethod", $info); $bit_depth = $meta["bitDepth"]; $color_type = $meta["colorType"]; // http://www.w3.org/TR/PNG/#11IHDR // 3 => indexed // 4 => greyscale with alpha // 6 => fullcolor with alpha $is_alpha = in_array($color_type, [4, 6]) || ($color_type == 3 && $bit_depth != 4); if ($is_alpha) { // exclude grayscale alpha $this->addImagePngAlpha($file, $x, $y, $w, $h, $color_type); return; } //png files typically contain an alpha channel. //pdf file format or class.pdf does not support alpha blending. //on alpha blended images, more transparent areas have a color near black. //This appears in the result on not storing the alpha channel. //Correct would be the box background image or its parent when transparent. //But this would make the image dependent on the background. //Therefore create an image with white background and copy in //A more natural background than black is white. //Therefore create an empty image with white background and merge the //image in with alpha blending. $imgtmp = @imagecreatefrompng($file); if (!$imgtmp) { return; } $sx = imagesx($imgtmp); $sy = imagesy($imgtmp); $img = imagecreatetruecolor($sx, $sy); imagealphablending($img, true); // @todo is it still needed ?? $ti = imagecolortransparent($imgtmp); if ($ti >= 0) { $tc = imagecolorsforindex($imgtmp, $ti); $ti = imagecolorallocate($img, $tc['red'], $tc['green'], $tc['blue']); imagefill($img, 0, 0, $ti); imagecolortransparent($img, $ti); } else { imagefill($img, 1, 1, imagecolorallocate($img, 255, 255, 255)); } imagecopy($img, $imgtmp, 0, 0, 0, 0, $sx, $sy); imagedestroy($imgtmp); } $this->addImagePng($img, $file, $x, $y, $w, $h); if ($img) { imagedestroy($img); } } /** * add a PNG image into the document, from a file * this should work with remote files * * @param $file * @param $x * @param $y * @param int $w * @param int $h */ function addSvgFromFile($file, $x, $y, $w = 0, $h = 0) { $doc = new \Svg\Document(); $doc->loadFile($file); $dimensions = $doc->getDimensions(); $this->save(); $this->transform([$w / $dimensions["width"], 0, 0, $h / $dimensions["height"], $x, $y]); $surface = new \Svg\Surface\SurfaceCpdf($doc, $this); $doc->render($surface); $this->restore(); } /** * add a PNG image into the document, from a memory buffer of the file * * @param $data * @param $file * @param $x * @param $y * @param float $w * @param float $h * @param bool $is_mask * @param null $mask */ function addPngFromBuf(&$data, $file, $x, $y, $w = 0.0, $h = 0.0, $is_mask = false, $mask = null) { if (isset($this->imagelist[$file])) { $data = null; $info['width'] = $this->imagelist[$file]['w']; $info['height'] = $this->imagelist[$file]['h']; $label = $this->imagelist[$file]['label']; } else { if ($data == null) { $this->addMessage('addPngFromBuf error - data not present!'); return; } $error = 0; if (!$error) { $header = chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10); if (mb_substr($data, 0, 8, '8bit') != $header) { $error = 1; if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile this file does not have a valid header ' . $file . ']'; } $errormsg = 'this file does not have a valid header'; } } if (!$error) { // set pointer $p = 8; $len = mb_strlen($data, '8bit'); // cycle through the file, identifying chunks $haveHeader = 0; $info = []; $idata = ''; $pdata = ''; while ($p < $len) { $chunkLen = $this->getBytes($data, $p, 4); $chunkType = mb_substr($data, $p + 4, 4, '8bit'); switch ($chunkType) { case 'IHDR': // this is where all the file information comes from $info['width'] = $this->getBytes($data, $p + 8, 4); $info['height'] = $this->getBytes($data, $p + 12, 4); $info['bitDepth'] = ord($data[$p + 16]); $info['colorType'] = ord($data[$p + 17]); $info['compressionMethod'] = ord($data[$p + 18]); $info['filterMethod'] = ord($data[$p + 19]); $info['interlaceMethod'] = ord($data[$p + 20]); //print_r($info); $haveHeader = 1; if ($info['compressionMethod'] != 0) { $error = 1; //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile unsupported compression method ' . $file . ']'; } $errormsg = 'unsupported compression method'; } if ($info['filterMethod'] != 0) { $error = 1; //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile unsupported filter method ' . $file . ']'; } $errormsg = 'unsupported filter method'; } break; case 'PLTE': $pdata .= mb_substr($data, $p + 8, $chunkLen, '8bit'); break; case 'IDAT': $idata .= mb_substr($data, $p + 8, $chunkLen, '8bit'); break; case 'tRNS': //this chunk can only occur once and it must occur after the PLTE chunk and before IDAT chunk //print "tRNS found, color type = ".$info['colorType']."\n"; $transparency = []; switch ($info['colorType']) { // indexed color, rbg case 3: /* corresponding to entries in the plte chunk Alpha for palette index 0: 1 byte Alpha for palette index 1: 1 byte ...etc... */ // there will be one entry for each palette entry. up until the last non-opaque entry. // set up an array, stretching over all palette entries which will be o (opaque) or 1 (transparent) $transparency['type'] = 'indexed'; $trans = 0; for ($i = $chunkLen; $i >= 0; $i--) { if (ord($data[$p + 8 + $i]) == 0) { $trans = $i; } } $transparency['data'] = $trans; break; // grayscale case 0: /* corresponding to entries in the plte chunk Gray: 2 bytes, range 0 .. (2^bitdepth)-1 */ // $transparency['grayscale'] = $this->PRVT_getBytes($data,$p+8,2); // g = grayscale $transparency['type'] = 'indexed'; $transparency['data'] = ord($data[$p + 8 + 1]); break; // truecolor case 2: /* corresponding to entries in the plte chunk Red: 2 bytes, range 0 .. (2^bitdepth)-1 Green: 2 bytes, range 0 .. (2^bitdepth)-1 Blue: 2 bytes, range 0 .. (2^bitdepth)-1 */ $transparency['r'] = $this->getBytes($data, $p + 8, 2); // r from truecolor $transparency['g'] = $this->getBytes($data, $p + 10, 2); // g from truecolor $transparency['b'] = $this->getBytes($data, $p + 12, 2); // b from truecolor $transparency['type'] = 'color-key'; break; //unsupported transparency type default: if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile unsupported transparency type ' . $file . ']'; } break; } // KS End new code break; default: break; } $p += $chunkLen + 12; } if (!$haveHeader) { $error = 1; //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile information header is missing ' . $file . ']'; } $errormsg = 'information header is missing'; } if (isset($info['interlaceMethod']) && $info['interlaceMethod']) { $error = 1; //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile no support for interlaced images in pdf ' . $file . ']'; } $errormsg = 'There appears to be no support for interlaced images in pdf.'; } } if (!$error && $info['bitDepth'] > 8) { $error = 1; //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile bit depth of 8 or less is supported ' . $file . ']'; } $errormsg = 'only bit depth of 8 or less is supported'; } if (!$error) { switch ($info['colorType']) { case 3: $color = 'DeviceRGB'; $ncolor = 1; break; case 2: $color = 'DeviceRGB'; $ncolor = 3; break; case 0: $color = 'DeviceGray'; $ncolor = 1; break; default: $error = 1; //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print '[addPngFromFile alpha channel not supported: ' . $info['colorType'] . ' ' . $file . ']'; } $errormsg = 'transparency alpha channel not supported, transparency only supported for palette images.'; } } if ($error) { $this->addMessage('PNG error - (' . $file . ') ' . $errormsg); return; } //print_r($info); // so this image is ok... add it in. $this->numImages++; $im = $this->numImages; $label = "I$im"; $this->numObj++; // $this->o_image($this->numObj,'new',array('label' => $label,'data' => $idata,'iw' => $w,'ih' => $h,'type' => 'png','ic' => $info['width'])); $options = [ 'label' => $label, 'data' => $idata, 'bitsPerComponent' => $info['bitDepth'], 'pdata' => $pdata, 'iw' => $info['width'], 'ih' => $info['height'], 'type' => 'png', 'color' => $color, 'ncolor' => $ncolor, 'masked' => $mask, 'isMask' => $is_mask ]; if (isset($transparency)) { $options['transparency'] = $transparency; } $this->o_image($this->numObj, 'new', $options); $this->imagelist[$file] = ['label' => $label, 'w' => $info['width'], 'h' => $info['height']]; } if ($is_mask) { return; } if ($w <= 0 && $h <= 0) { $w = $info['width']; $h = $info['height']; } if ($w <= 0) { $w = $h / $info['height'] * $info['width']; } if ($h <= 0) { $h = $w * $info['height'] / $info['width']; } $this->addContent(sprintf("\nq\n%.3F 0 0 %.3F %.3F %.3F cm /%s Do\nQ", $w, $h, $x, $y, $label)); } /** * add a JPEG image into the document, from a file * * @param $img * @param $x * @param $y * @param int $w * @param int $h */ function addJpegFromFile($img, $x, $y, $w = 0, $h = 0) { // attempt to add a jpeg image straight from a file, using no GD commands // note that this function is unable to operate on a remote file. if (!file_exists($img)) { return; } if ($this->image_iscached($img)) { $data = null; $imageWidth = $this->imagelist[$img]['w']; $imageHeight = $this->imagelist[$img]['h']; $channels = $this->imagelist[$img]['c']; } else { $tmp = getimagesize($img); $imageWidth = $tmp[0]; $imageHeight = $tmp[1]; if (isset($tmp['channels'])) { $channels = $tmp['channels']; } else { $channels = 3; } $data = file_get_contents($img); } if ($w <= 0 && $h <= 0) { $w = $imageWidth; } if ($w == 0) { $w = $h / $imageHeight * $imageWidth; } if ($h == 0) { $h = $w * $imageHeight / $imageWidth; } $this->addJpegImage_common($data, $img, $imageWidth, $imageHeight, $x, $y, $w, $h, $channels); } /** * common code used by the two JPEG adding functions * @param $data * @param $imgname * @param $imageWidth * @param $imageHeight * @param $x * @param $y * @param int $w * @param int $h * @param int $channels */ private function addJpegImage_common( &$data, $imgname, $imageWidth, $imageHeight, $x, $y, $w = 0, $h = 0, $channels = 3 ) { if ($this->image_iscached($imgname)) { $label = $this->imagelist[$imgname]['label']; //debugpng //if (DEBUGPNG) print '[addJpegImage_common Duplicate '.$imgname.']'; } else { if ($data == null) { $this->addMessage('addJpegImage_common error - (' . $imgname . ') data not present!'); return; } // note that this function is not to be called externally // it is just the common code between the GD and the file options $this->numImages++; $im = $this->numImages; $label = "I$im"; $this->numObj++; $this->o_image( $this->numObj, 'new', [ 'label' => $label, 'data' => &$data, 'iw' => $imageWidth, 'ih' => $imageHeight, 'channels' => $channels ] ); $this->imagelist[$imgname] = [ 'label' => $label, 'w' => $imageWidth, 'h' => $imageHeight, 'c' => $channels ]; } $this->addContent(sprintf("\nq\n%.3F 0 0 %.3F %.3F %.3F cm /%s Do\nQ ", $w, $h, $x, $y, $label)); } /** * specify where the document should open when it first starts * * @param $style * @param int $a * @param int $b * @param int $c */ function openHere($style, $a = 0, $b = 0, $c = 0) { // this function will open the document at a specified page, in a specified style // the values for style, and the required parameters are: // 'XYZ' left, top, zoom // 'Fit' // 'FitH' top // 'FitV' left // 'FitR' left,bottom,right // 'FitB' // 'FitBH' top // 'FitBV' left $this->numObj++; $this->o_destination( $this->numObj, 'new', ['page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c] ); $id = $this->catalogId; $this->o_catalog($id, 'openHere', $this->numObj); } /** * Add JavaScript code to the PDF document * * @param string $code */ function addJavascript($code) { $this->javascript .= $code; } /** * create a labelled destination within the document * * @param $label * @param $style * @param int $a * @param int $b * @param int $c */ function addDestination($label, $style, $a = 0, $b = 0, $c = 0) { // associates the given label with the destination, it is done this way so that a destination can be specified after // it has been linked to // styles are the same as the 'openHere' function $this->numObj++; $this->o_destination( $this->numObj, 'new', ['page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c] ); $id = $this->numObj; // store the label->idf relationship, note that this means that labels can be used only once $this->destinations["$label"] = $id; } /** * define font families, this is used to initialize the font families for the default fonts * and for the user to add new ones for their fonts. The default bahavious can be overridden should * that be desired. * * @param $family * @param string $options */ function setFontFamily($family, $options = '') { if (!is_array($options)) { if ($family === 'init') { // set the known family groups // these font families will be used to enable bold and italic markers to be included // within text streams. html forms will be used... $this->fontFamilies['Helvetica.afm'] = [ 'b' => 'Helvetica-Bold.afm', 'i' => 'Helvetica-Oblique.afm', 'bi' => 'Helvetica-BoldOblique.afm', 'ib' => 'Helvetica-BoldOblique.afm' ]; $this->fontFamilies['Courier.afm'] = [ 'b' => 'Courier-Bold.afm', 'i' => 'Courier-Oblique.afm', 'bi' => 'Courier-BoldOblique.afm', 'ib' => 'Courier-BoldOblique.afm' ]; $this->fontFamilies['Times-Roman.afm'] = [ 'b' => 'Times-Bold.afm', 'i' => 'Times-Italic.afm', 'bi' => 'Times-BoldItalic.afm', 'ib' => 'Times-BoldItalic.afm' ]; } } else { // the user is trying to set a font family // note that this can also be used to set the base ones to something else if (mb_strlen($family)) { $this->fontFamilies[$family] = $options; } } } /** * used to add messages for use in debugging * * @param $message */ function addMessage($message) { $this->messages .= $message . "\n"; } /** * a few functions which should allow the document to be treated transactionally. * * @param $action */ function transaction($action) { switch ($action) { case 'start': // store all the data away into the checkpoint variable $data = get_object_vars($this); $this->checkpoint = $data; unset($data); break; case 'commit': if (is_array($this->checkpoint) && isset($this->checkpoint['checkpoint'])) { $tmp = $this->checkpoint['checkpoint']; $this->checkpoint = $tmp; unset($tmp); } else { $this->checkpoint = ''; } break; case 'rewind': // do not destroy the current checkpoint, but move us back to the state then, so that we can try again if (is_array($this->checkpoint)) { // can only abort if were inside a checkpoint $tmp = $this->checkpoint; foreach ($tmp as $k => $v) { if ($k !== 'checkpoint') { $this->$k = $v; } } unset($tmp); } break; case 'abort': if (is_array($this->checkpoint)) { // can only abort if were inside a checkpoint $tmp = $this->checkpoint; foreach ($tmp as $k => $v) { $this->$k = $v; } unset($tmp); } break; } } }