F %.3F l ", $x1 + $rTL, $y1 + $h)); // curve: top-right corner $this->ellipse($x1 + $rTL, $y1 + $h - $rTL, $rTL, 0, 0, 8, 90, 180, false, false, false, true); // line: top edge, left end $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $rBL, $y1)); // Close & clip $this->addContent(" W n"); } /** * draw a clipping polygon, the syntax for this is similar to the GD polygon command * * @param float[] $p */ public function clippingPolygon(array $p): void { $this->save(); $this->addContent(sprintf("\n%.3F %.3F m ", $p[0], $p[1])); $n = count($p); for ($i = 2; $i < $n; $i = $i + 2) { $this->addContent(sprintf("%.3F %.3F l ", $p[$i], $p[$i + 1])); } $this->addContent("W n"); } /** * ends the last clipping shape */ function clippingEnd() { $this->restore(); } /** * scale * * @param float $s_x scaling factor for width as percent * @param float $s_y scaling factor for height as percent * @param float $x Origin abscissa * @param float $y Origin ordinate */ function scale($s_x, $s_y, $x, $y) { $y = $this->currentPageSize["height"] - $y; $tm = [ $s_x, 0, 0, $s_y, $x * (1 - $s_x), $y * (1 - $s_y) ]; $this->transform($tm); } /** * translate * * @param float $t_x movement to the right * @param float $t_y movement to the bottom */ function translate($t_x, $t_y) { $tm = [ 1, 0, 0, 1, $t_x, -$t_y ]; $this->transform($tm); } /** * rotate * * @param float $angle angle in degrees for counter-clockwise rotation * @param float $x Origin abscissa * @param float $y Origin ordinate */ function rotate($angle, $x, $y) { $y = $this->currentPageSize["height"] - $y; $a = deg2rad($angle); $cos_a = cos($a); $sin_a = sin($a); $tm = [ $cos_a, -$sin_a, $sin_a, $cos_a, $x - $sin_a * $y - $cos_a * $x, $y - $cos_a * $y + $sin_a * $x, ]; $this->transform($tm); } /** * skew * * @param float $angle_x * @param float $angle_y * @param float $x Origin abscissa * @param float $y Origin ordinate */ function skew($angle_x, $angle_y, $x, $y) { $y = $this->currentPageSize["height"] - $y; $tan_x = tan(deg2rad($angle_x)); $tan_y = tan(deg2rad($angle_y)); $tm = [ 1, -$tan_y, -$tan_x, 1, $tan_x * $y, $tan_y * $x, ]; $this->transform($tm); } /** * apply graphic transformations * * @param array $tm transformation matrix */ function transform($tm) { $this->addContent(vsprintf("\n %.3F %.3F %.3F %.3F %.3F %.3F cm", $tm)); } /** * add a new page to the document * this also makes the new page the current active object * * @param int $insert * @param int $id * @param string $pos * @return int */ function newPage($insert = 0, $id = 0, $pos = 'after') { // if there is a state saved, then go up the stack closing them // then on the new page, re-open them with the right setings if ($this->nStateStack) { for ($i = $this->nStateStack; $i >= 1; $i--) { $this->restoreState($i); } } $this->numObj++; if ($insert) { // the id from the ezPdf class is the id of the contents of the page, not the page object itself // query that object to find the parent $rid = $this->objects[$id]['onPage']; $opt = ['rid' => $rid, 'pos' => $pos]; $this->o_page($this->numObj, 'new', $opt); } else { $this->o_page($this->numObj, 'new'); } // if there is a stack saved, then put that onto the page if ($this->nStateStack) { for ($i = 1; $i <= $this->nStateStack; $i++) { $this->saveState($i); } } // and if there has been a stroke or fill color set, then transfer them if (isset($this->currentColor)) { $this->setColor($this->currentColor, true); } if (isset($this->currentStrokeColor)) { $this->setStrokeColor($this->currentStrokeColor, true); } // if there is a line style set, then put this in too if (mb_strlen($this->currentLineStyle, '8bit')) { $this->addContent("\n$this->currentLineStyle"); } // the call to the o_page object set currentContents to the present page, so this can be returned as the page id return $this->currentContents; } /** * Streams the PDF to the client. * * @param string $filename The filename to present to the client. * @param array $options Associative array: 'compress' => 1 or 0 (default 1); 'Attachment' => 1 or 0 (default 1). */ function stream($filename = "document.pdf", $options = []) { if (headers_sent()) { die("Unable to stream pdf: headers already sent"); } if (!isset($options["compress"])) $options["compress"] = true; if (!isset($options["Attachment"])) $options["Attachment"] = true; $debug = !$options['compress']; $tmp = ltrim($this->output($debug)); header("Cache-Control: private"); header("Content-Type: application/pdf"); header("Content-Length: " . mb_strlen($tmp, "8bit")); $filename = str_replace(["\n", "'"], "", basename($filename, ".pdf")) . ".pdf"; $attachment = $options["Attachment"] ? "attachment" : "inline"; $encoding = mb_detect_encoding($filename); $fallbackfilename = mb_convert_encoding($filename, "ISO-8859-1", $encoding); $fallbackfilename = str_replace("\"", "", $fallbackfilename); $encodedfilename = rawurlencode($filename); $contentDisposition = "Content-Disposition: $attachment; filename=\"$fallbackfilename\""; if ($fallbackfilename !== $filename) { $contentDisposition .= "; filename*=UTF-8''$encodedfilename"; } header($contentDisposition); echo $tmp; flush(); } /** * return the height in units of the current font in the given size * * @param float $size * * @return float */ public function getFontHeight(float $size): float { if (!$this->numFonts) { $this->selectFont($this->defaultFont); } $font = $this->fonts[$this->currentFont]; // for the current font, and the given size, what is the height of the font in user units if (isset($font['Ascender']) && isset($font['Descender'])) { $h = $font['Ascender'] - $font['Descender']; } else { $h = $font['FontBBox'][3] - $font['FontBBox'][1]; } // have to adjust by a font offset for Windows fonts. unfortunately it looks like // the bounding box calculations are wrong and I don't know why. if (isset($font['FontHeightOffset'])) { // For CourierNew from Windows this needs to be -646 to match the // Adobe native Courier font. // // For FreeMono from GNU this needs to be -337 to match the // Courier font. // // Both have been added manually to the .afm and .ufm files. $h += (int)$font['FontHeightOffset']; } return $size * $h / 1000; } /** * @param float $size * * @return float */ public function getFontXHeight(float $size): float { if (!$this->numFonts) { $this->selectFont($this->defaultFont); } $font = $this->fonts[$this->currentFont]; // for the current font, and the given size, what is the height of the font in user units if (isset($font['XHeight'])) { $xh = $font['Ascender'] - $font['Descender']; } else { $xh = $this->getFontHeight($size) / 2; } return $size * $xh / 1000; } /** * return the font descender, this will normally return a negative number * if you add this number to the baseline, you get the level of the bottom of the font * it is in the pdf user units * * @param float $size * * @return float */ public function getFontDescender(float $size): float { // note that this will most likely return a negative value if (!$this->numFonts) { $this->selectFont($this->defaultFont); } //$h = $this->fonts[$this->currentFont]['FontBBox'][1]; $h = $this->fonts[$this->currentFont]['Descender']; return $size * $h / 1000; } /** * filter the text, this is applied to all text just before being inserted into the pdf document * it escapes the various things that need to be escaped, and so on * * @param $text * @param bool $bom * @param bool $convert_encoding * @return string */ function filterText($text, $bom = true, $convert_encoding = true) { if (!$this->numFonts) { $this->selectFont($this->defaultFont); } if ($convert_encoding) { $cf = $this->currentFont; if (isset($this->fonts[$cf]) && $this->fonts[$cf]['isUnicode']) { $text = $this->utf8toUtf16BE($text, $bom); } else { //$text = html_entity_decode($text, ENT_QUOTES); $text = mb_convert_encoding($text, self::$targetEncoding, 'UTF-8'); } } elseif ($bom) { $text = $this->utf8toUtf16BE($text, $bom); } // the chr(13) substitution fixes a bug seen in TCPDF (bug #1421290) return strtr($text, [')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r']); } /** * return array containing codepoints (UTF-8 character values) for the * string passed in. * * based on the excellent TCPDF code by Nicola Asuni and the * RFC for UTF-8 at http://www.faqs.org/rfcs/rfc3629.html * * @param string $text UTF-8 string to process * @return array UTF-8 codepoints array for the string */ function utf8toCodePointsArray(&$text) { $length = mb_strlen($text, '8bit'); // http://www.php.net/manual/en/function.mb-strlen.php#77040 $unicode = []; // array containing unicode values $bytes = []; // array containing single character byte sequences $numbytes = 1; // number of octets needed to represent the UTF-8 character for ($i = 0; $i < $length; $i++) { $c = ord($text[$i]); // get one string character at time if (count($bytes) === 0) { // get starting octect if ($c <= 0x7F) { $unicode[] = $c; // use the character "as is" because is ASCII $numbytes = 1; } elseif (($c >> 0x05) === 0x06) { // 2 bytes character (0x06 = 110 BIN) $bytes[] = ($c - 0xC0) << 0x06; $numbytes = 2; } elseif (($c >> 0x04) === 0x0E) { // 3 bytes character (0x0E = 1110 BIN) $bytes[] = ($c - 0xE0) << 0x0C; $numbytes = 3; } elseif (($c >> 0x03) === 0x1E) { // 4 bytes character (0x1E = 11110 BIN) $bytes[] = ($c - 0xF0) << 0x12; $numbytes = 4; } else { // use replacement character for other invalid sequences $unicode[] = 0xFFFD; $bytes = []; $numbytes = 1; } } elseif (($c >> 0x06) === 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN $bytes[] = $c - 0x80; if (count($bytes) === $numbytes) { // compose UTF-8 bytes to a single unicode value $c = $bytes[0]; for ($j = 1; $j < $numbytes; $j++) { $c += ($bytes[$j] << (($numbytes - $j - 1) * 0x06)); } if ((($c >= 0xD800) and ($c <= 0xDFFF)) or ($c >= 0x10FFFF)) { // The definition of UTF-8 prohibits encoding character numbers between // U+D800 and U+DFFF, which are reserved for use with the UTF-16 // encoding form (as surrogate pairs) and do not directly represent // characters. $unicode[] = 0xFFFD; // use replacement character } else { $unicode[] = $c; // add char to array } // reset data for next char $bytes = []; $numbytes = 1; } } else { // use replacement character for other invalid sequences $unicode[] = 0xFFFD; $bytes = []; $numbytes = 1; } } return $unicode; } /** * convert UTF-8 to UTF-16 with an additional byte order marker * at the front if required. * * based on the excellent TCPDF code by Nicola Asuni and the * RFC for UTF-8 at http://www.faqs.org/rfcs/rfc3629.html * * @param string $text UTF-8 string to process * @param boolean $bom whether to add the byte order marker * @return string UTF-16 result string */ function utf8toUtf16BE(&$text, $bom = true) { $out = $bom ? "\xFE\xFF" : ''; $unicode = $this->utf8toCodePointsArray($text); foreach ($unicode as $c) { if ($c === 0xFFFD) { $out .= "\xFF\xFD"; // replacement character } elseif ($c < 0x10000) { $out .= chr($c >> 0x08) . chr($c & 0xFF); } else { $c -= 0x10000; $w1 = 0xD800 | ($c >> 0x10); $w2 = 0xDC00 | ($c & 0x3FF); $out .= chr($w1 >> 0x08) . chr($w1 & 0xFF) . chr($w2 >> 0x08) . chr($w2 & 0xFF); } } return $out; } /** * given a start position and information about how text is to be laid out, calculate where * on the page the text will end * * @param $x * @param $y * @param $angle * @param $size * @param $wa * @param $text * @return array */ private function getTextPosition($x, $y, $angle, $size, $wa, $text) { // given this information return an array containing x and y for the end position as elements 0 and 1 $w = $this->getTextWidth($size, $text); // need to adjust for the number of spaces in this text $words = explode(' ', $text); $nspaces = count($words) - 1; $w += $wa * $nspaces; $a = deg2rad((float)$angle); return [cos($a) * $w + $x, -sin($a) * $w + $y]; } /** * Callback method used by smallCaps * * @param array $matches * * @return string */ function toUpper($matches) { return mb_strtoupper($matches[0]); } function concatMatches($matches) { $str = ""; foreach ($matches as $match) { $str .= $match[0]; } return $str; } /** * register text for font subsetting * * @param string $font * @param string $text */ function registerText($font, $text) { if (!$this->isUnicode || in_array(mb_strtolower(basename($font)), self::$coreFonts)) { return; } if (!isset($this->stringSubsets[$font])) { $base_subset = "\u{fffd}\u{fffe}\u{ffff}"; $this->stringSubsets[$font] = $this->utf8toCodePointsArray($base_subset); } $this->stringSubsets[$font] = array_unique( array_merge($this->stringSubsets[$font], $this->utf8toCodePointsArray($text)) ); } /** * add text to the document, at a specified location, size and angle on the page * * @param float $x * @param float $y * @param float $size * @param string $text * @param float $angle * @param float $wordSpaceAdjust * @param float $charSpaceAdjust * @param bool $smallCaps */ function addText($x, $y, $size, $text, $angle = 0, $wordSpaceAdjust = 0, $charSpaceAdjust = 0, $smallCaps = false) { if (!$this->numFonts) { $this->selectFont($this->defaultFont); } $text = str_replace(["\r", "\n"], "", $text); // if ($smallCaps) { // preg_match_all("/(\P{Ll}+)/u", $text, $matches, PREG_SET_ORDER); // $lower = $this->concatMatches($matches); // d($lower); // preg_match_all("/(\p{Ll}+)/u", $text, $matches, PREG_SET_ORDER); // $other = $this->concatMatches($matches); // d($other); // $text = preg_replace_callback("/\p{Ll}/u", array($this, "toUpper"), $text); // } // if there are any open callbacks, then they should be called, to show the start of the line if ($this->nCallback > 0) { for ($i = $this->nCallback; $i > 0; $i--) { // call each function $info = [ 'x' => $x, 'y' => $y, 'angle' => $angle, 'status' => 'sol', 'p' => $this->callback[$i]['p'], 'nCallback' => $this->callback[$i]['nCallback'], 'height' => $this->callback[$i]['height'], 'descender' => $this->callback[$i]['descender'] ]; $func = $this->callback[$i]['f']; $this->$func($info); } } if ($angle == 0) { $this->addContent(sprintf("\nBT %.3F %.3F Td", $x, $y)); } else { $a = deg2rad((float)$angle); $this->addContent( sprintf("\nBT %.3F %.3F %.3F %.3F %.3F %.3F Tm", cos($a), -sin($a), sin($a), cos($a), $x, $y) ); } if ($wordSpaceAdjust != 0) { $this->addContent(sprintf(" %.3F Tw", $wordSpaceAdjust)); } if ($charSpaceAdjust != 0) { $this->addContent(sprintf(" %.3F Tc", $charSpaceAdjust)); } $len = mb_strlen($text); $start = 0; if ($start < $len) { $part = $text; // OAR - Don't need this anymore, given that $start always equals zero. substr($text, $start); $place_text = $this->filterText($part, false); // modify unicode text so that extra word spacing is manually implemented (bug #) if ($this->fonts[$this->currentFont]['isUnicode'] && $wordSpaceAdjust != 0) { $space_scale = 1000 / $size; $place_text = str_replace("\x00\x20", "\x00\x20)\x00\x20" . (-round($space_scale * $wordSpaceAdjust)) . "\x00\x20(", $place_text); } $this->addContent(" /F$this->currentFontNum " . sprintf('%.1F Tf ', $size)); $this->addContent(" [($place_text)] TJ"); } if ($wordSpaceAdjust != 0) { $this->addContent(sprintf(" %.3F Tw", 0)); } if ($charSpaceAdjust != 0) { $this->addContent(sprintf(" %.3F Tc", 0)); } $this->addContent(' ET'); // if there are any open callbacks, then they should be called, to show the end of the line if ($this->nCallback > 0) { for ($i = $this->nCallback; $i > 0; $i--) { // call each function $tmp = $this->getTextPosition($x, $y, $angle, $size, $wordSpaceAdjust, $text); $info = [ 'x' => $tmp[0], 'y' => $tmp[1], 'angle' => $angle, 'status' => 'eol', 'p' => $this->callback[$i]['p'], 'nCallback' => $this->callback[$i]['nCallback'], 'height' => $this->callback[$i]['height'], 'descender' => $this->callback[$i]['descender'] ]; $func = $this->callback[$i]['f']; $this->$func($info); } } if ($this->fonts[$this->currentFont]['isSubsetting']) { $this->registerText($this->currentFont, $text); } } /** * calculate how wide a given text string will be on a page, at a given size. * this can be called externally, but is also used by the other class functions * * @param float $size * @param string $text * @param float $wordSpacing * @param float $charSpacing * * @return float */ public function getTextWidth(float $size, string $text, float $wordSpacing = 0.0, float $charSpacing = 0.0): float { static $ord_cache = []; // this function should not change any of the settings, though it will need to // track any directives which change during calculation, so copy them at the start // and put them back at the end. $store_currentTextState = $this->currentTextState; if (!$this->numFonts) { $this->selectFont($this->defaultFont); } $text = str_replace(["\r", "\n"], "", $text); // hmm, this is where it all starts to get tricky - use the font information to // calculate the width of each character, add them up and convert to user units $w = 0; $cf = $this->currentFont; $current_font = $this->fonts[$cf]; $space_scale = 1000 / ($size > 0 ? $size : 1); if ($current_font['isUnicode']) { // for Unicode, use the code points array to calculate width rather // than just the string itself $unicode = $this->utf8toCodePointsArray($text); foreach ($unicode as $char) { // check if we have to replace character if (isset($current_font['differences'][$char])) { $char = $current_font['differences'][$char]; } if (isset($current_font['C'][$char])) { $char_width = $current_font['C'][$char]; // add the character width $w += $char_width; // add additional padding for space if (isset($current_font['codeToName'][$char]) && $current_font['codeToName'][$char] === 'space') { // Space $w += $wordSpacing * $space_scale; } } } // add additional char spacing if ($charSpacing != 0) { $w += $charSpacing * $space_scale * count($unicode); } } else { // If CPDF is in Unicode mode but the current font does not support Unicode we need to convert the character set to Windows-1252 if ($this->isUnicode) { $text = mb_convert_encoding($text, 'Windows-1252', 'UTF-8'); } $len = mb_strlen($text, 'Windows-1252'); for ($i = 0; $i < $len; $i++) { $c = $text[$i]; $char = isset($ord_cache[$c]) ? $ord_cache[$c] : ($ord_cache[$c] = ord($c)); // check if we have to replace character if (isset($current_font['differences'][$char])) { $char = $current_font['differences'][$char]; } if (isset($current_font['C'][$char])) { $char_width = $current_font['C'][$char]; // add the character width $w += $char_width; // add additional padding for space if (isset($current_font['codeToName'][$char]) && $current_font['codeToName'][$char] === 'space') { // Space $w += $wordSpacing * $space_scale; } } } // add additional char spacing if ($charSpacing != 0) { $w += $charSpacing * $space_scale * $len; } } $this->currentTextState = $store_currentTextState; $this->setCurrentFont(); return $w * $size / 1000; } /** * this will be called at a new page to return the state to what it was on the * end of the previous page, before the stack was closed down * This is to get around not being able to have open 'q' across pages * * @param int $pageEnd */ function saveState($pageEnd = 0) { if ($pageEnd) { // this will be called at a new page to return the state to what it was on the // end of the previous page, before the stack was closed down // This is to get around not being able to have open 'q' across pages $opt = $this->stateStack[$pageEnd]; // ok to use this as stack starts numbering at 1 $this->setColor($opt['col'], true); $this->setStrokeColor($opt['str'], true); $this->addContent("\n" . $opt['lin']); // $this->currentLineStyle = $opt['lin']; } else { $this->nStateStack++; $this->stateStack[$this->nStateStack] = [ 'col' => $this->currentColor, 'str' => $this->currentStrokeColor, 'lin' => $this->currentLineStyle ]; } $this->save(); } /** * restore a previously saved state * * @param int $pageEnd */ function restoreState($pageEnd = 0) { if (!$pageEnd) { $n = $this->nStateStack; $this->currentColor = $this->stateStack[$n]['col']; $this->currentStrokeColor = $this->stateStack[$n]['str']; $this->addContent("\n" . $this->stateStack[$n]['lin']); $this->currentLineStyle = $this->stateStack[$n]['lin']; $this->stateStack[$n] = null; unset($this->stateStack[$n]); $this->nStateStack--; } $this->restore(); } /** * make a loose object, the output will go into this object, until it is closed, then will revert to * the current one. * this object will not appear until it is included within a page. * the function will return the object number * * @return int */ function openObject() { $this->nStack++; $this->stack[$this->nStack] = ['c' => $this->currentContents, 'p' => $this->currentPage]; // add a new object of the content type, to hold the data flow $this->numObj++; $this->o_contents($this->numObj, 'new'); $this->currentContents = $this->numObj; $this->looseObjects[$this->numObj] = 1; return $this->numObj; } /** * open an existing object for editing * * @param $id */ function reopenObject($id) { $this->nStack++; $this->stack[$this->nStack] = ['c' => $this->currentContents, 'p' => $this->currentPage]; $this->currentContents = $id; // also if this object is the primary contents for a page, then set the current page to its parent if (isset($this->objects[$id]['onPage'])) { $this->currentPage = $this->objects[$id]['onPage']; } } /** * close an object */ function closeObject() { // close the object, as long as there was one open in the first place, which will be indicated by // an objectId on the stack. if ($this->nStack > 0) { $this->currentContents = $this->stack[$this->nStack]['c']; $this->currentPage = $this->stack[$this->nStack]['p']; $this->nStack--; // easier to probably not worry about removing the old entries, they will be overwritten // if there are new ones. } } /** * stop an object from appearing on pages from this point on * * @param $id */ function stopObject($id) { // if an object has been appearing on pages up to now, then stop it, this page will // be the last one that could contain it. if (isset($this->addLooseObjects[$id])) { $this->addLooseObjects[$id] = ''; } } /** * after an object has been created, it wil only show if it has been added, using this function. * * @param $id * @param string $options */ function addObject($id, $options = 'add') { // add the specified object to the page if (isset($this->looseObjects[$id]) && $this->currentContents != $id) { // then it is a valid object, and it is not being added to itself switch ($options) { case 'all': // then this object is to be added to this page (done in the next block) and // all future new pages. $this->addLooseObjects[$id] = 'all'; case 'add': if (isset($this->objects[$this->currentContents]['onPage'])) { // then the destination contents is the primary for the page // (though this object is actually added to that page) $this->o_page($this->objects[$this->currentContents]['onPage'], 'content', $id); } break; case 'even': $this->addLooseObjects[$id] = 'even'; $pageObjectId = $this->objects[$this->currentContents]['onPage']; if ($this->objects[$pageObjectId]['info']['pageNum'] % 2 == 0) { $this->addObject($id); // hacky huh :) } break; case 'odd': $this->addLooseObjects[$id] = 'odd'; $pageObjectId = $this->objects[$this->currentContents]['onPage']; if ($this->objects[$pageObjectId]['info']['pageNum'] % 2 == 1) { $this->addObject($id); // hacky huh :) } break; case 'next': $this->addLooseObjects[$id] = 'all'; break; case 'nexteven': $this->addLooseObjects[$id] = 'even'; break; case 'nextodd': $this->addLooseObjects[$id] = 'odd'; break; } } } /** * return a storable representation of a specific object * * @param $id * @return string|null */ function serializeObject($id) { if (array_key_exists($id, $this->objects)) { return serialize($this->objects[$id]); } return null; } /** * restore an object from its stored representation. Returns its new object id. * * @param $obj * @return int */ function restoreSerializedObject($obj) { $obj_id = $this->openObject(); $this->objects[$obj_id] = unserialize($obj); $this->closeObject(); return $obj_id; } /** * Embeds a file inside the PDF * * @param string $filepath path to the file to store inside the PDF * @param string $embeddedFilename the filename displayed in the list of embedded files * @param string $description a description in the list of embedded files */ public function addEmbeddedFile(string $filepath, string $embeddedFilename, string $description): void { $this->numObj++; $this->o_embedded_file_dictionary( $this->numObj, 'new', [ 'filepath' => $filepath, 'filename' => $embeddedFilename, 'description' => $description ] ); } /** * Add content to the documents info object * * @param string|array $label * @param string $value */ public function addInfo($label, string $value = ""): void { // this will only work if the label is one of the valid ones. // modify this so that arrays can be passed as well. // if $label is an array then assume that it is key => value pairs // else assume that they are both scalar, anything else will probably error if (is_array($label)) { foreach ($label as $l => $v) { $this->o_info($this->infoObject, $l, (string) $v); } } else { $this->o_info($this->infoObject, $label, $value); } } /** * set the viewer preferences of the document, it is up to the browser to obey these. * * @param $label * @param int $value */ function setPreferences($label, $value = 0) { // this will only work if the label is one of the valid ones. if (is_array($label)) { foreach ($label as $l => $v) { $this->o_catalog($this->catalogId, 'viewerPreferences', [$l => $v]); } } else { $this->o_catalog($this->catalogId, 'viewerPreferences', [$label => $value]); } } /** * extract an integer from a position in a byte stream * * @param $data * @param $pos * @param $num * @return int */ private function getBytes(&$data, $pos, $num) { // return the integer represented by $num bytes from $pos within $data $ret = 0; for ($i = 0; $i < $num; $i++) { $ret *= 256; $ret += ord($data[$pos + $i]); } return $ret; } /** * Check if image already added to pdf image directory. * If yes, need not to create again (pass empty data) * * @param string $imgname * @return bool */ function image_iscached($imgname) { return isset($this->imagelist[$imgname]); } /** * add a PNG image into the document, from a GD object * this should work with remote files * * @param \GdImage|resource $img A GD resource * @param string $file The PNG file * @param float $x X position * @param float $y Y position * @param float $w Width * @param float $h Height * @param bool $is_mask true if the image is a mask * @param bool $mask true if the image is masked * @throws Exception */ function addImagePng(&$img, $file, $x, $y, $w = 0.0, $h = 0.0, $is_mask = false, $mask = null) { if (!function_exists("imagepng")) { throw new \Exception("The PHP GD extension is required, but is not installed."); } //if already cached, need not to read again if (isset($this->imagelist[$file])) { $data = null; } else { // Example for transparency handling on new image. Retain for current image // $tIndex = imagecolortransparent($img); // if ($tIndex > 0) { // $tColor = imagecolorsforindex($img, $tIndex); // $new_tIndex = imagecolorallocate($new_img, $tColor['red'], $tColor['green'], $tColor['blue']); // imagefill($new_img, 0, 0, $new_tIndex); // imagecolortransparent($new_img, $new_tIndex); // } // blending mode (literal/blending) on drawing into current image. not relevant when not saved or not drawn //imagealphablending($img, true); //default, but explicitely set to ensure pdf compatibility imagesavealpha($img, false/*!$is_mask && !$mask*/); $error = 0; //DEBUG_IMG_TEMP //debugpng if (defined("DEBUGPNG") && DEBUGPNG) { print '[addImagePng ' . $file . ']'; } ob_start(); @imagepng($img); $data = ob_get_clean(); if ($data == '') { $error = 1; $errormsg = 'trouble writing file from GD'; //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; } } }