Dompdf.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  1. <?php
  2. /**
  3. * @package dompdf
  4. * @link http://dompdf.github.com/
  5. * @author Benj Carson <benjcarson@digitaljunkies.ca>
  6. * @author Fabien Ménager <fabien.menager@gmail.com>
  7. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  8. */
  9. namespace Dompdf;
  10. use DOMDocument;
  11. use DOMNode;
  12. use Dompdf\Adapter\CPDF;
  13. use DOMXPath;
  14. use Dompdf\Frame\Factory;
  15. use Dompdf\Frame\FrameTree;
  16. use HTML5_Tokenizer;
  17. use HTML5_TreeBuilder;
  18. use Dompdf\Image\Cache;
  19. use Dompdf\Renderer\ListBullet;
  20. use Dompdf\Css\Stylesheet;
  21. use Dompdf\Helpers;
  22. /**
  23. * Dompdf - PHP5 HTML to PDF renderer
  24. *
  25. * Dompdf loads HTML and does its best to render it as a PDF. It gets its
  26. * name from the new DomDocument PHP5 extension. Source HTML is first
  27. * parsed by a DomDocument object. Dompdf takes the resulting DOM tree and
  28. * attaches a {@link Frame} object to each node. {@link Frame} objects store
  29. * positioning and layout information and each has a reference to a {@link
  30. * Style} object.
  31. *
  32. * Style information is loaded and parsed (see {@link Stylesheet}) and is
  33. * applied to the frames in the tree by using XPath. CSS selectors are
  34. * converted into XPath queries, and the computed {@link Style} objects are
  35. * applied to the {@link Frame}s.
  36. *
  37. * {@link Frame}s are then decorated (in the design pattern sense of the
  38. * word) based on their CSS display property ({@link
  39. * http://www.w3.org/TR/CSS21/visuren.html#propdef-display}).
  40. * Frame_Decorators augment the basic {@link Frame} class by adding
  41. * additional properties and methods specific to the particular type of
  42. * {@link Frame}. For example, in the CSS layout model, block frames
  43. * (display: block;) contain line boxes that are usually filled with text or
  44. * other inline frames. The Block therefore adds a $lines
  45. * property as well as methods to add {@link Frame}s to lines and to add
  46. * additional lines. {@link Frame}s also are attached to specific
  47. * AbstractPositioner and {@link AbstractFrameReflower} objects that contain the
  48. * positioining and layout algorithm for a specific type of frame,
  49. * respectively. This is an application of the Strategy pattern.
  50. *
  51. * Layout, or reflow, proceeds recursively (post-order) starting at the root
  52. * of the document. Space constraints (containing block width & height) are
  53. * pushed down, and resolved positions and sizes bubble up. Thus, every
  54. * {@link Frame} in the document tree is traversed once (except for tables
  55. * which use a two-pass layout algorithm). If you are interested in the
  56. * details, see the reflow() method of the Reflower classes.
  57. *
  58. * Rendering is relatively straightforward once layout is complete. {@link
  59. * Frame}s are rendered using an adapted {@link Cpdf} class, originally
  60. * written by Wayne Munro, http://www.ros.co.nz/pdf/. (Some performance
  61. * related changes have been made to the original {@link Cpdf} class, and
  62. * the {@link Dompdf\Adapter\CPDF} class provides a simple, stateless interface to
  63. * PDF generation.) PDFLib support has now also been added, via the {@link
  64. * Dompdf\Adapter\PDFLib}.
  65. *
  66. *
  67. * @package dompdf
  68. */
  69. class Dompdf
  70. {
  71. /**
  72. * Version string for dompdf
  73. *
  74. * @var string
  75. */
  76. private $version = 'dompdf';
  77. /**
  78. * DomDocument representing the HTML document
  79. *
  80. * @var DOMDocument
  81. */
  82. private $dom;
  83. /**
  84. * FrameTree derived from the DOM tree
  85. *
  86. * @var FrameTree
  87. */
  88. private $tree;
  89. /**
  90. * Stylesheet for the document
  91. *
  92. * @var Stylesheet
  93. */
  94. private $css;
  95. /**
  96. * Actual PDF renderer
  97. *
  98. * @var Canvas
  99. */
  100. private $canvas;
  101. /**
  102. * Desired paper size ('letter', 'legal', 'A4', etc.)
  103. *
  104. * @var string|array
  105. */
  106. private $paperSize;
  107. /**
  108. * Paper orientation ('portrait' or 'landscape')
  109. *
  110. * @var string
  111. */
  112. private $paperOrientation = "portrait";
  113. /**
  114. * Callbacks on new page and new element
  115. *
  116. * @var array
  117. */
  118. private $callbacks = [];
  119. /**
  120. * Experimental caching capability
  121. *
  122. * @var string
  123. */
  124. private $cacheId;
  125. /**
  126. * Base hostname
  127. *
  128. * Used for relative paths/urls
  129. * @var string
  130. */
  131. private $baseHost = "";
  132. /**
  133. * Absolute base path
  134. *
  135. * Used for relative paths/urls
  136. * @var string
  137. */
  138. private $basePath = "";
  139. /**
  140. * Protocol used to request file (file://, http://, etc)
  141. *
  142. * @var string
  143. */
  144. private $protocol;
  145. /**
  146. * HTTP context created with stream_context_create()
  147. * Will be used for file_get_contents
  148. *
  149. * @var resource
  150. */
  151. private $httpContext;
  152. /**
  153. * Timestamp of the script start time
  154. *
  155. * @var int
  156. */
  157. private $startTime = null;
  158. /**
  159. * The system's locale
  160. *
  161. * @var string
  162. */
  163. private $systemLocale = null;
  164. /**
  165. * Tells if the system's locale is the C standard one
  166. *
  167. * @var bool
  168. */
  169. private $localeStandard = false;
  170. /**
  171. * The default view of the PDF in the viewer
  172. *
  173. * @var string
  174. */
  175. private $defaultView = "Fit";
  176. /**
  177. * The default view options of the PDF in the viewer
  178. *
  179. * @var array
  180. */
  181. private $defaultViewOptions = [];
  182. /**
  183. * Tells whether the DOM document is in quirksmode (experimental)
  184. *
  185. * @var bool
  186. */
  187. private $quirksmode = false;
  188. /**
  189. * Protocol whitelist
  190. *
  191. * Protocols and PHP wrappers allowed in URLs. Full support is not
  192. * guaranteed for the protocols/wrappers contained in this array.
  193. *
  194. * @var array
  195. */
  196. private $allowedProtocols = [null, "", "file://", "http://", "https://"];
  197. /**
  198. * Local file extension whitelist
  199. *
  200. * File extensions supported by dompdf for local files.
  201. *
  202. * @var array
  203. */
  204. private $allowedLocalFileExtensions = ["htm", "html"];
  205. /**
  206. * @var array
  207. */
  208. private $messages = [];
  209. /**
  210. * @var Options
  211. */
  212. private $options;
  213. /**
  214. * @var FontMetrics
  215. */
  216. private $fontMetrics;
  217. /**
  218. * The list of built-in fonts
  219. *
  220. * @var array
  221. * @deprecated
  222. */
  223. public static $native_fonts = [
  224. "courier", "courier-bold", "courier-oblique", "courier-boldoblique",
  225. "helvetica", "helvetica-bold", "helvetica-oblique", "helvetica-boldoblique",
  226. "times-roman", "times-bold", "times-italic", "times-bolditalic",
  227. "symbol", "zapfdinbats"
  228. ];
  229. /**
  230. * The list of built-in fonts
  231. *
  232. * @var array
  233. */
  234. public static $nativeFonts = [
  235. "courier", "courier-bold", "courier-oblique", "courier-boldoblique",
  236. "helvetica", "helvetica-bold", "helvetica-oblique", "helvetica-boldoblique",
  237. "times-roman", "times-bold", "times-italic", "times-bolditalic",
  238. "symbol", "zapfdinbats"
  239. ];
  240. /**
  241. * Class constructor
  242. *
  243. * @param array|Options $options
  244. */
  245. public function __construct($options = null)
  246. {
  247. mb_internal_encoding('UTF-8');
  248. if (version_compare(PHP_VERSION, '7.0.0') >= 0)
  249. {
  250. @ini_set('pcre.jit', 0);
  251. }
  252. if (isset($options) && $options instanceof Options) {
  253. $this->setOptions($options);
  254. } elseif (is_array($options)) {
  255. $this->setOptions(new Options($options));
  256. } else {
  257. $this->setOptions(new Options());
  258. }
  259. $versionFile = realpath(__DIR__ . '/../VERSION');
  260. if (file_exists($versionFile) && ($version = file_get_contents($versionFile)) !== false && $version !== '$Format:<%h>$') {
  261. $this->version = sprintf('dompdf %s', $version);
  262. }
  263. $this->localeStandard = sprintf('%.1f', 1.0) == '1.0';
  264. $this->saveLocale();
  265. $this->paperSize = $this->options->getDefaultPaperSize();
  266. $this->paperOrientation = $this->options->getDefaultPaperOrientation();
  267. $this->setCanvas(CanvasFactory::get_instance($this, $this->paperSize, $this->paperOrientation));
  268. $this->setFontMetrics(new FontMetrics($this->getCanvas(), $this->getOptions()));
  269. $this->css = new Stylesheet($this);
  270. $this->restoreLocale();
  271. }
  272. /**
  273. * Save the system's locale configuration and
  274. * set the right value for numeric formatting
  275. */
  276. private function saveLocale()
  277. {
  278. if ($this->localeStandard) {
  279. return;
  280. }
  281. $this->systemLocale = setlocale(LC_NUMERIC, "0");
  282. setlocale(LC_NUMERIC, "C");
  283. }
  284. /**
  285. * Restore the system's locale configuration
  286. */
  287. private function restoreLocale()
  288. {
  289. if ($this->localeStandard) {
  290. return;
  291. }
  292. setlocale(LC_NUMERIC, $this->systemLocale);
  293. }
  294. /**
  295. * @param $file
  296. * @deprecated
  297. */
  298. public function load_html_file($file)
  299. {
  300. $this->loadHtmlFile($file);
  301. }
  302. /**
  303. * Loads an HTML file
  304. * Parse errors are stored in the global array _dompdf_warnings.
  305. *
  306. * @param string $file a filename or url to load
  307. * @param string $encoding Encoding of $file
  308. *
  309. * @throws Exception
  310. */
  311. public function loadHtmlFile($file, $encoding = null)
  312. {
  313. $this->saveLocale();
  314. if (!$this->protocol && !$this->baseHost && !$this->basePath) {
  315. [$this->protocol, $this->baseHost, $this->basePath] = Helpers::explode_url($file);
  316. }
  317. $protocol = strtolower($this->protocol);
  318. $uri = Helpers::build_url($this->protocol, $this->baseHost, $this->basePath, $file);
  319. if ( !in_array($protocol, $this->allowedProtocols) ) {
  320. throw new Exception("Permission denied on $file. The communication protocol is not supported.");
  321. }
  322. if (!$this->options->isRemoteEnabled() && ($protocol != "" && $protocol !== "file://")) {
  323. throw new Exception("Remote file requested, but remote file download is disabled.");
  324. }
  325. if ($protocol == "" || $protocol === "file://") {
  326. $realfile = realpath($uri);
  327. $chroot = realpath($this->options->getChroot());
  328. if ($chroot && strpos($realfile, $chroot) !== 0) {
  329. throw new Exception("Permission denied on $file. The file could not be found under the directory specified by Options::chroot.");
  330. }
  331. $ext = strtolower(pathinfo($realfile, PATHINFO_EXTENSION));
  332. if (!in_array($ext, $this->allowedLocalFileExtensions)) {
  333. throw new Exception("Permission denied on $file. This file extension is forbidden");
  334. }
  335. if (!$realfile) {
  336. throw new Exception("File '$file' not found.");
  337. }
  338. $uri = $realfile;
  339. }
  340. [$contents, $http_response_header] = Helpers::getFileContent($uri, $this->httpContext);
  341. if (empty($contents)) {
  342. throw new Exception("File '$file' not found.");
  343. }
  344. // See http://the-stickman.com/web-development/php/getting-http-response-headers-when-using-file_get_contents/
  345. if (isset($http_response_header)) {
  346. foreach ($http_response_header as $_header) {
  347. if (preg_match("@Content-Type:\s*[\w/]+;\s*?charset=([^\s]+)@i", $_header, $matches)) {
  348. $encoding = strtoupper($matches[1]);
  349. break;
  350. }
  351. }
  352. }
  353. $this->restoreLocale();
  354. $this->loadHtml($contents, $encoding);
  355. }
  356. /**
  357. * @param string $str
  358. * @param string $encoding
  359. * @deprecated
  360. */
  361. public function load_html($str, $encoding = null)
  362. {
  363. $this->loadHtml($str, $encoding);
  364. }
  365. public function loadDOM($doc, $quirksmode = false) {
  366. // Remove #text children nodes in nodes that shouldn't have
  367. $tag_names = ["html", "head", "table", "tbody", "thead", "tfoot", "tr"];
  368. foreach ($tag_names as $tag_name) {
  369. $nodes = $doc->getElementsByTagName($tag_name);
  370. foreach ($nodes as $node) {
  371. self::removeTextNodes($node);
  372. }
  373. }
  374. $this->dom = $doc;
  375. $this->quirksmode = $quirksmode;
  376. $this->tree = new FrameTree($this->dom);
  377. }
  378. /**
  379. * Loads an HTML string
  380. * Parse errors are stored in the global array _dompdf_warnings.
  381. *
  382. * @param string $str HTML text to load
  383. * @param string $encoding Encoding of $str
  384. */
  385. public function loadHtml($str, $encoding = null)
  386. {
  387. $this->saveLocale();
  388. // Determine character encoding when $encoding parameter not used
  389. if ($encoding === null) {
  390. mb_detect_order('auto');
  391. if (($encoding = mb_detect_encoding($str, null, true)) === false) {
  392. //"auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
  393. $encoding = "auto";
  394. }
  395. }
  396. if (in_array(strtoupper($encoding), array('UTF-8','UTF8')) === false) {
  397. $str = mb_convert_encoding($str, 'UTF-8', $encoding);
  398. //Update encoding after converting
  399. $encoding = 'UTF-8';
  400. }
  401. $metatags = [
  402. '@<meta\s+http-equiv="Content-Type"\s+content="(?:[\w/]+)(?:;\s*?charset=([^\s"]+))?@i',
  403. '@<meta\s+content="(?:[\w/]+)(?:;\s*?charset=([^\s"]+))"?\s+http-equiv="Content-Type"@i',
  404. '@<meta [^>]*charset\s*=\s*["\']?\s*([^"\' ]+)@i',
  405. ];
  406. foreach ($metatags as $metatag) {
  407. if (preg_match($metatag, $str, $matches)) {
  408. if (isset($matches[1]) && in_array($matches[1], mb_list_encodings())) {
  409. $document_encoding = $matches[1];
  410. break;
  411. }
  412. }
  413. }
  414. if (isset($document_encoding) && in_array(strtoupper($document_encoding), ['UTF-8','UTF8']) === false) {
  415. $str = preg_replace('/charset=([^\s"]+)/i', 'charset=UTF-8', $str);
  416. } elseif (isset($document_encoding) === false && strpos($str, '<head>') !== false) {
  417. $str = str_replace('<head>', '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">', $str);
  418. } elseif (isset($document_encoding) === false) {
  419. $str = '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">' . $str;
  420. }
  421. // remove BOM mark from UTF-8, it's treated as document text by DOMDocument
  422. // FIXME: roll this into the encoding detection using UTF-8/16/32 BOM (http://us2.php.net/manual/en/function.mb-detect-encoding.php#91051)?
  423. if (substr($str, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF)) {
  424. $str = substr($str, 3);
  425. }
  426. // Store parsing warnings as messages
  427. set_error_handler([Helpers::class, 'record_warnings']);
  428. try {
  429. // @todo Take the quirksmode into account
  430. // http://hsivonen.iki.fi/doctype/
  431. // https://developer.mozilla.org/en/mozilla's_quirks_mode
  432. $quirksmode = false;
  433. if ($this->options->isHtml5ParserEnabled() && class_exists(HTML5_Tokenizer::class)) {
  434. $tokenizer = new HTML5_Tokenizer($str);
  435. $tokenizer->parse();
  436. $doc = $tokenizer->save();
  437. $quirksmode = ($tokenizer->getTree()->getQuirksMode() > HTML5_TreeBuilder::NO_QUIRKS);
  438. } else {
  439. // loadHTML assumes ISO-8859-1 unless otherwise specified on the HTML document header.
  440. // http://devzone.zend.com/1538/php-dom-xml-extension-encoding-processing/ (see #4)
  441. // http://stackoverflow.com/a/11310258/264628
  442. $doc = new DOMDocument("1.0", $encoding);
  443. $doc->preserveWhiteSpace = true;
  444. $doc->loadHTML($str);
  445. $doc->encoding = $encoding;
  446. // If some text is before the doctype, we are in quirksmode
  447. if (preg_match("/^(.+)<!doctype/i", ltrim($str), $matches)) {
  448. $quirksmode = true;
  449. } // If no doctype is provided, we are in quirksmode
  450. elseif (!preg_match("/^<!doctype/i", ltrim($str), $matches)) {
  451. $quirksmode = true;
  452. } else {
  453. // HTML5 <!DOCTYPE html>
  454. if (!$doc->doctype->publicId && !$doc->doctype->systemId) {
  455. $quirksmode = false;
  456. }
  457. // not XHTML
  458. if (!preg_match("/xhtml/i", $doc->doctype->publicId)) {
  459. $quirksmode = true;
  460. }
  461. }
  462. }
  463. $this->loadDOM($doc, $quirksmode);
  464. } finally {
  465. restore_error_handler();
  466. $this->restoreLocale();
  467. }
  468. }
  469. /**
  470. * @param DOMNode $node
  471. * @deprecated
  472. */
  473. public static function remove_text_nodes(DOMNode $node)
  474. {
  475. self::removeTextNodes($node);
  476. }
  477. /**
  478. * @param DOMNode $node
  479. */
  480. public static function removeTextNodes(DOMNode $node)
  481. {
  482. $children = [];
  483. for ($i = 0; $i < $node->childNodes->length; $i++) {
  484. $child = $node->childNodes->item($i);
  485. if ($child->nodeName === "#text") {
  486. $children[] = $child;
  487. }
  488. }
  489. foreach ($children as $child) {
  490. $node->removeChild($child);
  491. }
  492. }
  493. /**
  494. * Builds the {@link FrameTree}, loads any CSS and applies the styles to
  495. * the {@link FrameTree}
  496. */
  497. private function processHtml()
  498. {
  499. $this->tree->build_tree();
  500. $this->css->load_css_file($this->css->getDefaultStylesheet(), Stylesheet::ORIG_UA);
  501. $acceptedmedia = Stylesheet::$ACCEPTED_GENERIC_MEDIA_TYPES;
  502. $acceptedmedia[] = $this->options->getDefaultMediaType();
  503. // <base href="" />
  504. $base_nodes = $this->dom->getElementsByTagName("base");
  505. if ($base_nodes->length && ($href = $base_nodes->item(0)->getAttribute("href"))) {
  506. [$this->protocol, $this->baseHost, $this->basePath] = Helpers::explode_url($href);
  507. }
  508. // Set the base path of the Stylesheet to that of the file being processed
  509. $this->css->set_protocol($this->protocol);
  510. $this->css->set_host($this->baseHost);
  511. $this->css->set_base_path($this->basePath);
  512. // Get all the stylesheets so that they are processed in document order
  513. $xpath = new DOMXPath($this->dom);
  514. $stylesheets = $xpath->query("//*[name() = 'link' or name() = 'style']");
  515. /** @var \DOMElement $tag */
  516. foreach ($stylesheets as $tag) {
  517. switch (strtolower($tag->nodeName)) {
  518. // load <link rel="STYLESHEET" ... /> tags
  519. case "link":
  520. if (mb_strtolower(stripos($tag->getAttribute("rel"), "stylesheet") !== false) || // may be "appendix stylesheet"
  521. mb_strtolower($tag->getAttribute("type")) === "text/css"
  522. ) {
  523. //Check if the css file is for an accepted media type
  524. //media not given then always valid
  525. $formedialist = preg_split("/[\s\n,]/", $tag->getAttribute("media"), -1, PREG_SPLIT_NO_EMPTY);
  526. if (count($formedialist) > 0) {
  527. $accept = false;
  528. foreach ($formedialist as $type) {
  529. if (in_array(mb_strtolower(trim($type)), $acceptedmedia)) {
  530. $accept = true;
  531. break;
  532. }
  533. }
  534. if (!$accept) {
  535. //found at least one mediatype, but none of the accepted ones
  536. //Skip this css file.
  537. break;
  538. }
  539. }
  540. $url = $tag->getAttribute("href");
  541. $url = Helpers::build_url($this->protocol, $this->baseHost, $this->basePath, $url);
  542. $this->css->load_css_file($url, Stylesheet::ORIG_AUTHOR);
  543. }
  544. break;
  545. // load <style> tags
  546. case "style":
  547. // Accept all <style> tags by default (note this is contrary to W3C
  548. // HTML 4.0 spec:
  549. // http://www.w3.org/TR/REC-html40/present/styles.html#adef-media
  550. // which states that the default media type is 'screen'
  551. if ($tag->hasAttributes() &&
  552. ($media = $tag->getAttribute("media")) &&
  553. !in_array($media, $acceptedmedia)
  554. ) {
  555. break;
  556. }
  557. $css = "";
  558. if ($tag->hasChildNodes()) {
  559. $child = $tag->firstChild;
  560. while ($child) {
  561. $css .= $child->nodeValue; // Handle <style><!-- blah --></style>
  562. $child = $child->nextSibling;
  563. }
  564. } else {
  565. $css = $tag->nodeValue;
  566. }
  567. // Set the base path of the Stylesheet to that of the file being processed
  568. $this->css->set_protocol($this->protocol);
  569. $this->css->set_host($this->baseHost);
  570. $this->css->set_base_path($this->basePath);
  571. $this->css->load_css($css, Stylesheet::ORIG_AUTHOR);
  572. break;
  573. }
  574. // Set the base path of the Stylesheet to that of the file being processed
  575. $this->css->set_protocol($this->protocol);
  576. $this->css->set_host($this->baseHost);
  577. $this->css->set_base_path($this->basePath);
  578. }
  579. }
  580. /**
  581. * @param string $cacheId
  582. * @deprecated
  583. */
  584. public function enable_caching($cacheId)
  585. {
  586. $this->enableCaching($cacheId);
  587. }
  588. /**
  589. * Enable experimental caching capability
  590. *
  591. * @param string $cacheId
  592. */
  593. public function enableCaching($cacheId)
  594. {
  595. $this->cacheId = $cacheId;
  596. }
  597. /**
  598. * @param string $value
  599. * @return bool
  600. * @deprecated
  601. */
  602. public function parse_default_view($value)
  603. {
  604. return $this->parseDefaultView($value);
  605. }
  606. /**
  607. * @param string $value
  608. * @return bool
  609. */
  610. public function parseDefaultView($value)
  611. {
  612. $valid = ["XYZ", "Fit", "FitH", "FitV", "FitR", "FitB", "FitBH", "FitBV"];
  613. $options = preg_split("/\s*,\s*/", trim($value));
  614. $defaultView = array_shift($options);
  615. if (!in_array($defaultView, $valid)) {
  616. return false;
  617. }
  618. $this->setDefaultView($defaultView, $options);
  619. return true;
  620. }
  621. /**
  622. * Renders the HTML to PDF
  623. */
  624. public function render()
  625. {
  626. $this->saveLocale();
  627. $options = $this->options;
  628. $logOutputFile = $options->getLogOutputFile();
  629. if ($logOutputFile) {
  630. if (!file_exists($logOutputFile) && is_writable(dirname($logOutputFile))) {
  631. touch($logOutputFile);
  632. }
  633. $this->startTime = microtime(true);
  634. if (is_writable($logOutputFile)) {
  635. ob_start();
  636. }
  637. }
  638. $this->processHtml();
  639. $this->css->apply_styles($this->tree);
  640. // @page style rules : size, margins
  641. $pageStyles = $this->css->get_page_styles();
  642. $basePageStyle = $pageStyles["base"];
  643. unset($pageStyles["base"]);
  644. foreach ($pageStyles as $pageStyle) {
  645. $pageStyle->inherit($basePageStyle);
  646. }
  647. $defaultOptionPaperSize = $this->getPaperSize($options->getDefaultPaperSize());
  648. // If there is a CSS defined paper size compare to the paper size used to create the canvas to determine a
  649. // recreation need
  650. if (is_array($basePageStyle->size)) {
  651. $basePageStyleSize = $basePageStyle->size;
  652. $this->setPaper([0, 0, $basePageStyleSize[0], $basePageStyleSize[1]]);
  653. }
  654. $paperSize = $this->getPaperSize();
  655. if (
  656. $defaultOptionPaperSize[2] !== $paperSize[2] ||
  657. $defaultOptionPaperSize[3] !== $paperSize[3] ||
  658. $options->getDefaultPaperOrientation() !== $this->paperOrientation
  659. ) {
  660. $this->setCanvas(CanvasFactory::get_instance($this, $this->paperSize, $this->paperOrientation));
  661. $this->fontMetrics->setCanvas($this->getCanvas());
  662. }
  663. $canvas = $this->getCanvas();
  664. $root = null;
  665. foreach ($this->tree->get_frames() as $frame) {
  666. // Set up the root frame
  667. if (is_null($root)) {
  668. $root = Factory::decorate_root($this->tree->get_root(), $this);
  669. continue;
  670. }
  671. // Create the appropriate decorators, reflowers & positioners.
  672. Factory::decorate_frame($frame, $this, $root);
  673. }
  674. // Add meta information
  675. $title = $this->dom->getElementsByTagName("title");
  676. if ($title->length) {
  677. $canvas->add_info("Title", trim($title->item(0)->nodeValue));
  678. }
  679. $metas = $this->dom->getElementsByTagName("meta");
  680. $labels = [
  681. "author" => "Author",
  682. "keywords" => "Keywords",
  683. "description" => "Subject",
  684. ];
  685. /** @var \DOMElement $meta */
  686. foreach ($metas as $meta) {
  687. $name = mb_strtolower($meta->getAttribute("name"));
  688. $value = trim($meta->getAttribute("content"));
  689. if (isset($labels[$name])) {
  690. $canvas->add_info($labels[$name], $value);
  691. continue;
  692. }
  693. if ($name === "dompdf.view" && $this->parseDefaultView($value)) {
  694. $canvas->set_default_view($this->defaultView, $this->defaultViewOptions);
  695. }
  696. }
  697. $root->set_containing_block(0, 0, $canvas->get_width(), $canvas->get_height());
  698. $root->set_renderer(new Renderer($this));
  699. // This is where the magic happens:
  700. $root->reflow();
  701. // Clean up cached images
  702. Cache::clear();
  703. global $_dompdf_warnings, $_dompdf_show_warnings;
  704. if ($_dompdf_show_warnings && isset($_dompdf_warnings)) {
  705. echo '<b>Dompdf Warnings</b><br><pre>';
  706. foreach ($_dompdf_warnings as $msg) {
  707. echo $msg . "\n";
  708. }
  709. if ($canvas instanceof CPDF) {
  710. echo $canvas->get_cpdf()->messages;
  711. }
  712. echo '</pre>';
  713. flush();
  714. }
  715. if ($logOutputFile && is_writable($logOutputFile)) {
  716. $this->write_log();
  717. ob_end_clean();
  718. }
  719. $this->restoreLocale();
  720. }
  721. /**
  722. * Add meta information to the PDF after rendering
  723. */
  724. public function add_info($label, $value)
  725. {
  726. $canvas = $this->getCanvas();
  727. if (!is_null($canvas)) {
  728. $canvas->add_info($label, $value);
  729. }
  730. }
  731. /**
  732. * Writes the output buffer in the log file
  733. *
  734. * @return void
  735. */
  736. private function write_log()
  737. {
  738. $log_output_file = $this->getOptions()->getLogOutputFile();
  739. if (!$log_output_file || !is_writable($log_output_file)) {
  740. return;
  741. }
  742. $frames = Frame::$ID_COUNTER;
  743. $memory = memory_get_peak_usage(true) / 1024;
  744. $time = (microtime(true) - $this->startTime) * 1000;
  745. $out = sprintf(
  746. "<span style='color: #000' title='Frames'>%6d</span>" .
  747. "<span style='color: #009' title='Memory'>%10.2f KB</span>" .
  748. "<span style='color: #900' title='Time'>%10.2f ms</span>" .
  749. "<span title='Quirksmode'> " .
  750. ($this->quirksmode ? "<span style='color: #d00'> ON</span>" : "<span style='color: #0d0'>OFF</span>") .
  751. "</span><br />", $frames, $memory, $time);
  752. $out .= ob_get_contents();
  753. ob_clean();
  754. file_put_contents($log_output_file, $out);
  755. }
  756. /**
  757. * Streams the PDF to the client.
  758. *
  759. * The file will open a download dialog by default. The options
  760. * parameter controls the output. Accepted options (array keys) are:
  761. *
  762. * 'compress' = > 1 (=default) or 0:
  763. * Apply content stream compression
  764. *
  765. * 'Attachment' => 1 (=default) or 0:
  766. * Set the 'Content-Disposition:' HTTP header to 'attachment'
  767. * (thereby causing the browser to open a download dialog)
  768. *
  769. * @param string $filename the name of the streamed file
  770. * @param array $options header options (see above)
  771. */
  772. public function stream($filename = "document.pdf", $options = [])
  773. {
  774. $this->saveLocale();
  775. $canvas = $this->getCanvas();
  776. if (!is_null($canvas)) {
  777. $canvas->stream($filename, $options);
  778. }
  779. $this->restoreLocale();
  780. }
  781. /**
  782. * Returns the PDF as a string.
  783. *
  784. * The options parameter controls the output. Accepted options are:
  785. *
  786. * 'compress' = > 1 or 0 - apply content stream compression, this is
  787. * on (1) by default
  788. *
  789. * @param array $options options (see above)
  790. *
  791. * @return string|null
  792. */
  793. public function output($options = [])
  794. {
  795. $this->saveLocale();
  796. $canvas = $this->getCanvas();
  797. if (is_null($canvas)) {
  798. return null;
  799. }
  800. $output = $canvas->output($options);
  801. $this->restoreLocale();
  802. return $output;
  803. }
  804. /**
  805. * @return string
  806. * @deprecated
  807. */
  808. public function output_html()
  809. {
  810. return $this->outputHtml();
  811. }
  812. /**
  813. * Returns the underlying HTML document as a string
  814. *
  815. * @return string
  816. */
  817. public function outputHtml()
  818. {
  819. return $this->dom->saveHTML();
  820. }
  821. /**
  822. * Get the dompdf option value
  823. *
  824. * @param string $key
  825. * @return mixed
  826. * @deprecated
  827. */
  828. public function get_option($key)
  829. {
  830. return $this->options->get($key);
  831. }
  832. /**
  833. * @param string $key
  834. * @param mixed $value
  835. * @return $this
  836. * @deprecated
  837. */
  838. public function set_option($key, $value)
  839. {
  840. $this->options->set($key, $value);
  841. return $this;
  842. }
  843. /**
  844. * @param array $options
  845. * @return $this
  846. * @deprecated
  847. */
  848. public function set_options(array $options)
  849. {
  850. $this->options->set($options);
  851. return $this;
  852. }
  853. /**
  854. * @param string $size
  855. * @param string $orientation
  856. * @deprecated
  857. */
  858. public function set_paper($size, $orientation = "portrait")
  859. {
  860. $this->setPaper($size, $orientation);
  861. }
  862. /**
  863. * Sets the paper size & orientation
  864. *
  865. * @param string|array $size 'letter', 'legal', 'A4', etc. {@link Dompdf\Adapter\CPDF::$PAPER_SIZES}
  866. * @param string $orientation 'portrait' or 'landscape'
  867. * @return $this
  868. */
  869. public function setPaper($size, $orientation = "portrait")
  870. {
  871. $this->paperSize = $size;
  872. $this->paperOrientation = $orientation;
  873. return $this;
  874. }
  875. /**
  876. * Gets the paper size
  877. *
  878. * @param null|string|array $paperSize
  879. * @return int[] A four-element integer array
  880. */
  881. public function getPaperSize($paperSize = null)
  882. {
  883. $size = $paperSize !== null ? $paperSize : $this->paperSize;
  884. if (is_array($size)) {
  885. return $size;
  886. } else if (isset(Adapter\CPDF::$PAPER_SIZES[mb_strtolower($size)])) {
  887. return Adapter\CPDF::$PAPER_SIZES[mb_strtolower($size)];
  888. } else {
  889. return Adapter\CPDF::$PAPER_SIZES["letter"];
  890. }
  891. }
  892. /**
  893. * Gets the paper orientation
  894. *
  895. * @return string Either "portrait" or "landscape"
  896. */
  897. public function getPaperOrientation()
  898. {
  899. return $this->paperOrientation;
  900. }
  901. /**
  902. * @param FrameTree $tree
  903. * @return $this
  904. */
  905. public function setTree(FrameTree $tree)
  906. {
  907. $this->tree = $tree;
  908. return $this;
  909. }
  910. /**
  911. * @return FrameTree
  912. * @deprecated
  913. */
  914. public function get_tree()
  915. {
  916. return $this->getTree();
  917. }
  918. /**
  919. * Returns the underlying {@link FrameTree} object
  920. *
  921. * @return FrameTree
  922. */
  923. public function getTree()
  924. {
  925. return $this->tree;
  926. }
  927. /**
  928. * @param string $protocol
  929. * @return $this
  930. * @deprecated
  931. */
  932. public function set_protocol($protocol)
  933. {
  934. return $this->setProtocol($protocol);
  935. }
  936. /**
  937. * Sets the protocol to use
  938. * FIXME validate these
  939. *
  940. * @param string $protocol
  941. * @return $this
  942. */
  943. public function setProtocol($protocol)
  944. {
  945. $this->protocol = $protocol;
  946. return $this;
  947. }
  948. /**
  949. * @return string
  950. * @deprecated
  951. */
  952. public function get_protocol()
  953. {
  954. return $this->getProtocol();
  955. }
  956. /**
  957. * Returns the protocol in use
  958. *
  959. * @return string
  960. */
  961. public function getProtocol()
  962. {
  963. return $this->protocol;
  964. }
  965. /**
  966. * @param string $host
  967. * @deprecated
  968. */
  969. public function set_host($host)
  970. {
  971. $this->setBaseHost($host);
  972. }
  973. /**
  974. * Sets the base hostname
  975. *
  976. * @param string $baseHost
  977. * @return $this
  978. */
  979. public function setBaseHost($baseHost)
  980. {
  981. $this->baseHost = $baseHost;
  982. return $this;
  983. }
  984. /**
  985. * @return string
  986. * @deprecated
  987. */
  988. public function get_host()
  989. {
  990. return $this->getBaseHost();
  991. }
  992. /**
  993. * Returns the base hostname
  994. *
  995. * @return string
  996. */
  997. public function getBaseHost()
  998. {
  999. return $this->baseHost;
  1000. }
  1001. /**
  1002. * Sets the base path
  1003. *
  1004. * @param string $path
  1005. * @deprecated
  1006. */
  1007. public function set_base_path($path)
  1008. {
  1009. $this->setBasePath($path);
  1010. }
  1011. /**
  1012. * Sets the base path
  1013. *
  1014. * @param string $basePath
  1015. * @return $this
  1016. */
  1017. public function setBasePath($basePath)
  1018. {
  1019. $this->basePath = $basePath;
  1020. return $this;
  1021. }
  1022. /**
  1023. * @return string
  1024. * @deprecated
  1025. */
  1026. public function get_base_path()
  1027. {
  1028. return $this->getBasePath();
  1029. }
  1030. /**
  1031. * Returns the base path
  1032. *
  1033. * @return string
  1034. */
  1035. public function getBasePath()
  1036. {
  1037. return $this->basePath;
  1038. }
  1039. /**
  1040. * @param string $default_view The default document view
  1041. * @param array $options The view's options
  1042. * @return $this
  1043. * @deprecated
  1044. */
  1045. public function set_default_view($default_view, $options)
  1046. {
  1047. return $this->setDefaultView($default_view, $options);
  1048. }
  1049. /**
  1050. * Sets the default view
  1051. *
  1052. * @param string $defaultView The default document view
  1053. * @param array $options The view's options
  1054. * @return $this
  1055. */
  1056. public function setDefaultView($defaultView, $options)
  1057. {
  1058. $this->defaultView = $defaultView;
  1059. $this->defaultViewOptions = $options;
  1060. return $this;
  1061. }
  1062. /**
  1063. * @param resource $http_context
  1064. * @return $this
  1065. * @deprecated
  1066. */
  1067. public function set_http_context($http_context)
  1068. {
  1069. return $this->setHttpContext($http_context);
  1070. }
  1071. /**
  1072. * Sets the HTTP context
  1073. *
  1074. * @param resource $httpContext
  1075. * @return $this
  1076. */
  1077. public function setHttpContext($httpContext)
  1078. {
  1079. $this->httpContext = $httpContext;
  1080. return $this;
  1081. }
  1082. /**
  1083. * @return resource
  1084. * @deprecated
  1085. */
  1086. public function get_http_context()
  1087. {
  1088. return $this->getHttpContext();
  1089. }
  1090. /**
  1091. * Returns the HTTP context
  1092. *
  1093. * @return resource
  1094. */
  1095. public function getHttpContext()
  1096. {
  1097. return $this->httpContext;
  1098. }
  1099. /**
  1100. * @param Canvas $canvas
  1101. * @return $this
  1102. */
  1103. public function setCanvas(Canvas $canvas)
  1104. {
  1105. $this->canvas = $canvas;
  1106. return $this;
  1107. }
  1108. /**
  1109. * @return Canvas
  1110. * @deprecated
  1111. */
  1112. public function get_canvas()
  1113. {
  1114. return $this->getCanvas();
  1115. }
  1116. /**
  1117. * Return the underlying Canvas instance (e.g. Dompdf\Adapter\CPDF, Dompdf\Adapter\GD)
  1118. *
  1119. * @return Canvas
  1120. */
  1121. public function getCanvas()
  1122. {
  1123. return $this->canvas;
  1124. }
  1125. /**
  1126. * @param Stylesheet $css
  1127. * @return $this
  1128. */
  1129. public function setCss(Stylesheet $css)
  1130. {
  1131. $this->css = $css;
  1132. return $this;
  1133. }
  1134. /**
  1135. * @return Stylesheet
  1136. * @deprecated
  1137. */
  1138. public function get_css()
  1139. {
  1140. return $this->getCss();
  1141. }
  1142. /**
  1143. * Returns the stylesheet
  1144. *
  1145. * @return Stylesheet
  1146. */
  1147. public function getCss()
  1148. {
  1149. return $this->css;
  1150. }
  1151. /**
  1152. * @param DOMDocument $dom
  1153. * @return $this
  1154. */
  1155. public function setDom(DOMDocument $dom)
  1156. {
  1157. $this->dom = $dom;
  1158. return $this;
  1159. }
  1160. /**
  1161. * @return DOMDocument
  1162. * @deprecated
  1163. */
  1164. public function get_dom()
  1165. {
  1166. return $this->getDom();
  1167. }
  1168. /**
  1169. * @return DOMDocument
  1170. */
  1171. public function getDom()
  1172. {
  1173. return $this->dom;
  1174. }
  1175. /**
  1176. * @param Options $options
  1177. * @return $this
  1178. */
  1179. public function setOptions(Options $options)
  1180. {
  1181. $this->options = $options;
  1182. $fontMetrics = $this->getFontMetrics();
  1183. if (isset($fontMetrics)) {
  1184. $fontMetrics->setOptions($options);
  1185. }
  1186. return $this;
  1187. }
  1188. /**
  1189. * @return Options
  1190. */
  1191. public function getOptions()
  1192. {
  1193. return $this->options;
  1194. }
  1195. /**
  1196. * @return array
  1197. * @deprecated
  1198. */
  1199. public function get_callbacks()
  1200. {
  1201. return $this->getCallbacks();
  1202. }
  1203. /**
  1204. * Returns the callbacks array
  1205. *
  1206. * @return array
  1207. */
  1208. public function getCallbacks()
  1209. {
  1210. return $this->callbacks;
  1211. }
  1212. /**
  1213. * @param array $callbacks the set of callbacks to set
  1214. * @deprecated
  1215. */
  1216. public function set_callbacks($callbacks)
  1217. {
  1218. $this->setCallbacks($callbacks);
  1219. }
  1220. /**
  1221. * Sets callbacks for events like rendering of pages and elements.
  1222. * The callbacks array contains arrays with 'event' set to 'begin_page',
  1223. * 'end_page', 'begin_frame', or 'end_frame' and 'f' set to a function or
  1224. * object plus method to be called.
  1225. *
  1226. * The function 'f' must take an array as argument, which contains info
  1227. * about the event.
  1228. *
  1229. * @param array $callbacks the set of callbacks to set
  1230. */
  1231. public function setCallbacks($callbacks)
  1232. {
  1233. if (is_array($callbacks)) {
  1234. $this->callbacks = [];
  1235. foreach ($callbacks as $c) {
  1236. if (is_array($c) && isset($c['event']) && isset($c['f'])) {
  1237. $event = $c['event'];
  1238. $f = $c['f'];
  1239. if (is_callable($f) && is_string($event)) {
  1240. $this->callbacks[$event][] = $f;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. /**
  1247. * @return boolean
  1248. * @deprecated
  1249. */
  1250. public function get_quirksmode()
  1251. {
  1252. return $this->getQuirksmode();
  1253. }
  1254. /**
  1255. * Get the quirks mode
  1256. *
  1257. * @return boolean true if quirks mode is active
  1258. */
  1259. public function getQuirksmode()
  1260. {
  1261. return $this->quirksmode;
  1262. }
  1263. /**
  1264. * @param FontMetrics $fontMetrics
  1265. * @return $this
  1266. */
  1267. public function setFontMetrics(FontMetrics $fontMetrics)
  1268. {
  1269. $this->fontMetrics = $fontMetrics;
  1270. return $this;
  1271. }
  1272. /**
  1273. * @return FontMetrics
  1274. */
  1275. public function getFontMetrics()
  1276. {
  1277. return $this->fontMetrics;
  1278. }
  1279. /**
  1280. * PHP5 overloaded getter
  1281. * Along with {@link Dompdf::__set()} __get() provides access to all
  1282. * properties directly. Typically __get() is not called directly outside
  1283. * of this class.
  1284. *
  1285. * @param string $prop
  1286. *
  1287. * @throws Exception
  1288. * @return mixed
  1289. */
  1290. function __get($prop)
  1291. {
  1292. switch ($prop)
  1293. {
  1294. case 'version' :
  1295. return $this->version;
  1296. default:
  1297. throw new Exception( 'Invalid property: ' . $prop );
  1298. }
  1299. }
  1300. }