/** * applies all current styles to a particular document tree * * apply_styles() applies all currently loaded styles to the provided * {@link FrameTree}. Aside from parsing CSS, this is the main purpose * of this class. * * @param \Dompdf\Frame\FrameTree $tree */ function apply_styles(FrameTree $tree) { // Use XPath to select nodes. This would be easier if we could attach // Frame objects directly to DOMNodes using the setUserData() method, but // we can't do that just yet. Instead, we set a _node attribute_ in // Frame->set_id() and use that as a handle on the Frame object via // FrameTree::$_registry. // We create a scratch array of styles indexed by frame id. Once all // styles have been assigned, we order the cached styles by specificity // and create a final style object to assign to the frame. // FIXME: this is not particularly robust... $styles = array(); $xp = new DOMXPath($tree->get_dom()); // Add generated content foreach ($this->_styles as $selector => $style) { if (strpos($selector, ":before") === false && strpos($selector, ":after") === false) { continue; } $query = $this->_css_selector_to_xpath($selector, true); // Retrieve the nodes, limit to body for generated content $nodes = @$xp->query('.' . $query["query"]); if ($nodes == null) { Helpers::record_warnings(E_USER_WARNING, "The CSS selector '{$selector}' is not valid", __FILE__, __LINE__); continue; } foreach ($nodes as $node) { foreach ($query["pseudo_elements"] as $pos) { // Do not add a new pseudo element if another one already matched if ($node->hasAttribute("dompdf_{$pos}_frame_id")) { continue; } if (($src = $this->_image($style->content)) !== "none") { $new_node = $node->ownerDocument->createElement("img_generated"); $new_node->setAttribute("src", $src); } else { $new_node = $node->ownerDocument->createElement("dompdf_generated"); } $new_node->setAttribute($pos, $pos); $new_frame_id = $tree->insert_node($node, $new_node, $pos); $node->setAttribute("dompdf_{$pos}_frame_id", $new_frame_id); } } } // Apply all styles in stylesheet foreach ($this->_styles as $selector => $style) { $query = $this->_css_selector_to_xpath($selector); // Retrieve the nodes $nodes = @$xp->query($query["query"]); if ($nodes == null) { Helpers::record_warnings(E_USER_WARNING, "The CSS selector '{$selector}' is not valid", __FILE__, __LINE__); continue; } foreach ($nodes as $node) { // Retrieve the node id // Only DOMElements get styles if ($node->nodeType != XML_ELEMENT_NODE) { continue; } $id = $node->getAttribute("frame_id"); // Assign the current style to the scratch array $spec = $this->_specificity($selector); $styles[$id][$spec][] = $style; } } // Now create the styles and assign them to the appropriate frames. (We // iterate over the tree using an implicit FrameTree iterator.) $root_flg = false; foreach ($tree->get_frames() as $frame) { // Helpers::pre_r($frame->get_node()->nodeName . ":"); if (!$root_flg && $this->_page_styles["base"]) { $style = $this->_page_styles["base"]; $root_flg = true; } else { $style = $this->create_style(); } // Find nearest DOMElement parent $p = $frame; while ($p = $p->get_parent()) { if ($p->get_node()->nodeType == XML_ELEMENT_NODE) { break; } } // Styles can only be applied directly to DOMElements; anonymous // frames inherit from their parent if ($frame->get_node()->nodeType != XML_ELEMENT_NODE) { if ($p) { $style->inherit($p->get_style()); } $frame->set_style($style); continue; } $id = $frame->get_id(); // Handle HTML 4.0 attributes AttributeTranslator::translate_attributes($frame); if (($str = $frame->get_node()->getAttribute(AttributeTranslator::$_style_attr)) !== "") { // Lowest specificity $styles[$id][1][] = $this->_parse_properties($str); } // Locate any additional style attributes if (($str = $frame->get_node()->getAttribute("style")) !== "") { // Destroy CSS comments $str = preg_replace("'/\\*.*?\\*/'si", "", $str); $spec = $this->_specificity("!attr"); $styles[$id][$spec][] = $this->_parse_properties($str); } // Grab the applicable styles if (isset($styles[$id])) { $applied_styles = $styles[$frame->get_id()]; // Sort by specificity ksort($applied_styles); if ($this->_dompdf->get_option('debugCss')) { $debug_nodename = $frame->get_node()->nodeName; print "<pre>\n[{$debug_nodename}\n"; foreach ($applied_styles as $spec => $arr) { printf("specificity: 0x%08x\n", $spec); foreach ($arr as $s) { print "[\n"; $s->debug_print(); print "]\n"; } } } // Merge the new styles with the inherited styles foreach ($applied_styles as $arr) { foreach ($arr as $s) { $style->merge($s); } } } // Inherit parent's styles if required if ($p) { if ($this->_dompdf->get_option('debugCss')) { print "inherit:\n"; print "[\n"; $p->get_style()->debug_print(); print "]\n"; } $style->inherit($p->get_style()); } if ($this->_dompdf->get_option('debugCss')) { print "DomElementStyle:\n"; print "[\n"; $style->debug_print(); print "]\n"; print "/{$debug_nodename}]\n</pre>"; } /*DEBUGCSS print: see below different print debugging method Helpers::pre_r($frame->get_node()->nodeName . ":"); echo "<pre>"; echo $style; echo "</pre>";*/ $frame->set_style($style); } // We're done! Clean out the registry of all styles since we // won't be needing this later. foreach (array_keys($this->_styles) as $key) { $this->_styles[$key] = null; unset($this->_styles[$key]); } }
/** * Renders the HTML to PDF */ public function render() { $this->saveLocale(); $logOutputFile = $this->options->getLogOutputFile(); if ($logOutputFile) { if (!file_exists($logOutputFile) && is_writable(dirname($logOutputFile))) { touch($logOutputFile); } $this->startTime = microtime(true); ob_start(); } $this->processHtml(); $this->css->apply_styles($this->tree); // @page style rules : size, margins $pageStyles = $this->css->get_page_styles(); $basePageStyle = $pageStyles["base"]; unset($pageStyles["base"]); foreach ($pageStyles as $pageStyle) { $pageStyle->inherit($basePageStyle); } if (is_array($basePageStyle->size)) { $this->setPaper(array(0, 0, $basePageStyle->size[0], $basePageStyle->size[1])); } //TODO: We really shouldn't be doing this; properties were already set in the constructor. We should add Canvas methods to set the page size and orientation after instantiaion. $this->setCanvas(CanvasFactory::get_instance($this, $this->paperSize, $this->paperOrientation)); $this->setFontMetrics(new FontMetrics($this->pdf, $this->getOptions())); if ($this->options->isFontSubsettingEnabled() && $this->pdf instanceof CPDF) { foreach ($this->tree->get_frames() as $frame) { $style = $frame->get_style(); $node = $frame->get_node(); // Handle text nodes if ($node->nodeName === "#text") { $this->getCanvas()->register_string_subset($style->font_family, $node->nodeValue); continue; } // Handle generated content (list items) if ($style->display === "list-item") { $chars = ListBullet::get_counter_chars($style->list_style_type); $this->getCanvas()->register_string_subset($style->font_family, $chars); continue; } // Handle other generated content (pseudo elements) // FIXME: This only captures the text of the stylesheet declaration, // not the actual generated content, and forces all possible counter // values. See notes in issue #750. if ($frame->get_node()->nodeName == "dompdf_generated") { // all possible counter values $chars = ListBullet::get_counter_chars('decimal'); $this->getCanvas()->register_string_subset($style->font_family, $chars); $chars = ListBullet::get_counter_chars('upper-alpha'); $this->getCanvas()->register_string_subset($style->font_family, $chars); $chars = ListBullet::get_counter_chars('lower-alpha'); $this->getCanvas()->register_string_subset($style->font_family, $chars); $chars = ListBullet::get_counter_chars('lower-greek'); $this->getCanvas()->register_string_subset($style->font_family, $chars); // the text of the stylesheet declaration $this->getCanvas()->register_string_subset($style->font_family, $style->content); continue; } } } $root = null; foreach ($this->tree->get_frames() as $frame) { // Set up the root frame if (is_null($root)) { $root = Factory::decorate_root($this->tree->get_root(), $this); continue; } // Create the appropriate decorators, reflowers & positioners. Factory::decorate_frame($frame, $this, $root); } // Add meta information $title = $this->dom->getElementsByTagName("title"); if ($title->length) { $this->getCanvas()->add_info("Title", trim($title->item(0)->nodeValue)); } $metas = $this->dom->getElementsByTagName("meta"); $labels = array("author" => "Author", "keywords" => "Keywords", "description" => "Subject"); foreach ($metas as $meta) { $name = mb_strtolower($meta->getAttribute("name")); $value = trim($meta->getAttribute("content")); if (isset($labels[$name])) { $this->pdf->add_info($labels[$name], $value); continue; } if ($name === "dompdf.view" && $this->parseDefaultView($value)) { $this->getCanvas()->set_default_view($this->defaultView, $this->defaultViewOptions); } } $root->set_containing_block(0, 0, $this->getCanvas()->get_width(), $this->getCanvas()->get_height()); $root->set_renderer(new Renderer($this)); // This is where the magic happens: $root->reflow(); // Clean up cached images Cache::clear(); global $_dompdf_warnings, $_dompdf_show_warnings; if ($_dompdf_show_warnings && isset($_dompdf_warnings)) { echo '<b>Dompdf Warnings</b><br><pre>'; foreach ($_dompdf_warnings as $msg) { echo $msg . "\n"; } echo $this->getCanvas()->get_cpdf()->messages; echo '</pre>'; flush(); } $this->restoreLocale(); }