1

Tengo un inconveniente con DomPDF y Bootstrap. Estoy utilizando Laravel 5.1 como framework PHP y agregué el servicio de DomPDF. Ha funcionado muy bien con estilos CSS creados por mí, pero al incluir los estilos CSS de Bootstrap me genera el siguiente error:

ErrorException in font_metrics.cls.php line 354: file_get_contents(C:\xampp\htdocs\ProjectName\public/../fonts/glyphicons-halflings-regular.ttf): failed to open stream: No such file or directory

Tiene un problema al incluir las fuentes, no sé en qué carpeta debo colocar las fuentes para que funcione correctamente.

El archivo font_metrics.cls.php, que contiene el error en la línea 354 es uno de los archivos que incluye el servicio de DomPDF. La llamada a la fuente que indica el error se realiza en el código css de bootstrap.min.css, el cual pego directamente en el archivo HTML que renderizo para generar el PDF. (No pegaré todo el código del bootstrap.min.css en esta pregunta, ya que es excesivamente largo).

Este es el código del HTML que indico a DomPDF para renderizar y convertir a PDF.

    <html lang="en">
      <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
            <title>Orden de Servicio</title>

          <style type="text/css">
            /*!
             * Bootstrap v3.3.5 (http://getbootstrap.com)
             * Copyright 2011-2015 Twitter, Inc.
             * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
             *//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
         </style> 


     </head>

      <body>
        <br><br>
            <div class="col-lg-12">
                <table class="col-lg-12">
              <thead>
                <tr>
                    <th class="col-lg-4" style="text-align: left">Proyecto:</th>
                    <th style="text-align: center">Nro de Contrato:</th>
                    <th style="text-align: center">Empresa Cliente:</th>
                    <th style="text-align: center">Empresa Proveedor:</th>
                    <th style="text-align: center">Periodo:</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                    <td style="text-align: center">{{$contratos->proyecto->nombre_Proyecto}}</td>
                    <td style="text-align: center">{{$contratos->nro_Contrato}}</td>
                    <td style="text-align: center">{{$contratos->empresaCliente->nombre_Empresa}}</td>
                    <td style="text-align: center">{{$contratos->empresaProveedor->nombre_Empresa}}</td>
                    <td style="text-align: center">{{$contratos->fecha_inicio}} - {{$contratos->fecha_fin}}</td>
                </tr>
              </tbody>
            </table>
            <div class="col-lg-12 col-md-12 col-sm-12"><br><br></div>
            <h4 class="">Valuaciones</h4>
            <div style="background-color: #688a7e; height: 16px"></div>
                  <br>
                  <div class="presupuestos">
                    <table  class="display">
                        <thead >
                          <tr>
                              <th>Nro de Valuacion</th>
                              <th>Contrato Asociado</th>
                              <th>Periodo de Valuación</th>
                              <th>Avance Físico</th>
                              <th>Avance Financiero</th>
                          </tr>
                        </thead>
                        <tbody>
                      @foreach($valuaciones as $datos)
                          <tr>
                            <td>{{$datos->nro_Valuacion}}</td>
                            <td>{{$contratos->nro_Contrato}}</td>
                            <td>{{$datos->fecha_Inicio_Periodo}} - {{$datos->fecha_Fin_Periodo}}</td>
                            <td>{{$datos->avance_fisico}}</td>
                            <td>{{$datos->avance_financiero}}</td>
                          </tr>
                      @endforeach
                        </tbody>
                    </table>
                    <br><br>
                    <a href="" class="boton" style="width:100%">boton</a>
                </div>

      </body>
    </html>

Con este archivo no hay problemas. Si yo renderizo el mismo archivo sin incluir el código de bootstrap.min.css funciona perfectamente, pero no tengo los estilos. Al agregar las líneas de los estilos bootstrap es que genera el error antes mencionado.

Este es el archivo del DomPDF que genera el error:

font_metrics.cls.php

<?php
/**
 * @package dompdf
 * @link    http://dompdf.github.com/
 * @author  Fabien Ménager <[email protected]>
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 */

require_once DOMPDF_LIB_DIR . "/class.pdf.php";

/**
 * Name of the font cache file
 *
 * This file must be writable by the webserver process only to update it
 * with save_font_families() after adding the .afm file references of a new font family
 * with Font_Metrics::save_font_families().
 * This is typically done only from command line with load_font.php on converting
 * ttf fonts to ufm with php-font-lib.
 *
 * Declared here because PHP5 prevents constants from being declared with expressions
 */
define('__DOMPDF_FONT_CACHE_FILE', DOMPDF_FONT_DIR . "dompdf_font_family_cache.php");

/**
 * The font metrics class
 *
 * This class provides information about fonts and text.  It can resolve
 * font names into actual installed font files, as well as determine the
 * size of text in a particular font and size.
 *
 * @static
 * @package dompdf
 */
class Font_Metrics {

  /**
   * @see __DOMPDF_FONT_CACHE_FILE
   */
  const CACHE_FILE = __DOMPDF_FONT_CACHE_FILE;

  /**
   * Underlying {@link Canvas} object to perform text size calculations
   *
   * @var Canvas
   */
  static protected $_pdf = null;

  /**
   * Array of font family names to font files
   *
   * Usually cached by the {@link load_font.php} script
   *
   * @var array
   */
  static protected $_font_lookup = array();


  /**
   * Class initialization
   *
   */
  static function init(Canvas $canvas = null) {
    if (!self::$_pdf) {
      if (!$canvas) {
        $canvas = Canvas_Factory::get_instance(new DOMPDF());
      }

      self::$_pdf = $canvas;
    }
  }

  /**
   * Calculates text size, in points
   *
   * @param string $text the text to be sized
   * @param string $font the desired font
   * @param float  $size the desired font size
   * @param float  $word_spacing
   * @param float  $char_spacing
   *
   * @internal param float $spacing word spacing, if any
   * @return float
   */
  static function get_text_width($text, $font, $size, $word_spacing = 0.0, $char_spacing = 0.0) {
    //return self::$_pdf->get_text_width($text, $font, $size, $word_spacing, $char_spacing);

    // @todo Make sure this cache is efficient before enabling it
    static $cache = array();

    if ( $text === "" ) {
      return 0;
    }

    // Don't cache long strings
    $use_cache = !isset($text[50]); // Faster than strlen

    $key = "$font/$size/$word_spacing/$char_spacing";

    if ( $use_cache && isset($cache[$key][$text]) ) {
      return $cache[$key]["$text"];
    }

    $width = self::$_pdf->get_text_width($text, $font, $size, $word_spacing, $char_spacing);

    if ( $use_cache ) {
      $cache[$key][$text] = $width;
    }

    return $width;
  }

  /**
   * Calculates font height
   *
   * @param string $font
   * @param float $size
   * @return float
   */
  static function get_font_height($font, $size) {
    return self::$_pdf->get_font_height($font, $size);
  }

  /**
   * Resolves a font family & subtype into an actual font file
   * Subtype can be one of 'normal', 'bold', 'italic' or 'bold_italic'.  If
   * the particular font family has no suitable font file, the default font
   * ({@link DOMPDF_DEFAULT_FONT}) is used.  The font file returned
   * is the absolute pathname to the font file on the system.
   *
   * @param string $family_raw
   * @param string $subtype_raw
   *
   * @return string
   */
  static function get_font($family_raw, $subtype_raw = "normal") {
    static $cache = array();

    if ( isset($cache[$family_raw][$subtype_raw]) ) {
      return $cache[$family_raw][$subtype_raw];
    }

    /* Allow calling for various fonts in search path. Therefore not immediately
     * return replacement on non match.
     * Only when called with NULL try replacement.
     * When this is also missing there is really trouble.
     * If only the subtype fails, nevertheless return failure.
     * Only on checking the fallback font, check various subtypes on same font.
     */

    $subtype = strtolower($subtype_raw);

    if ( $family_raw ) {
      $family = str_replace( array("'", '"'), "", strtolower($family_raw));

      if ( isset(self::$_font_lookup[$family][$subtype]) ) {
        return $cache[$family_raw][$subtype_raw] = self::$_font_lookup[$family][$subtype];
      }

      return null;
    }

    $family = "serif";

    if ( isset(self::$_font_lookup[$family][$subtype]) ) {
      return $cache[$family_raw][$subtype_raw] = self::$_font_lookup[$family][$subtype];
    }

    if ( !isset(self::$_font_lookup[$family]) ) {
      return null;
    }

    $family = self::$_font_lookup[$family];

    foreach ( $family as $sub => $font ) {
      if (strpos($subtype, $sub) !== false) {
        return $cache[$family_raw][$subtype_raw] = $font;
      }
    }

    if ($subtype !== "normal") {
      foreach ( $family as $sub => $font ) {
        if ($sub !== "normal") {
          return $cache[$family_raw][$subtype_raw] = $font;
        }
      }
    }

    $subtype = "normal";

    if ( isset($family[$subtype]) ) {
      return $cache[$family_raw][$subtype_raw] = $family[$subtype];
    }

    return null;
  }

  static function get_family($family) {
    $family = str_replace( array("'", '"'), "", mb_strtolower($family));

    if ( isset(self::$_font_lookup[$family]) ) {
      return self::$_font_lookup[$family];
    }

    return null;
  }

  /**
   * Saves the stored font family cache
   *
   * The name and location of the cache file are determined by {@link
   * Font_Metrics::CACHE_FILE}.  This file should be writable by the
   * webserver process.
   *
   * @see Font_Metrics::load_font_families()
   */
  static function save_font_families() {
    // replace the path to the DOMPDF font directories with the corresponding constants (allows for more portability)
    $cache_data = sprintf("<?php return array (%s", PHP_EOL);
    foreach (self::$_font_lookup as $family => $variants) {
      $cache_data .= sprintf("  '%s' => array(%s", addslashes($family), PHP_EOL);
      foreach ($variants as $variant => $path) {
        $path = sprintf("'%s'", $path);
        $path = str_replace('\'' . DOMPDF_FONT_DIR , 'DOMPDF_FONT_DIR . \'' , $path);
        $path = str_replace('\'' . DOMPDF_DIR , 'DOMPDF_DIR . \'' , $path);
        $cache_data .= sprintf("    '%s' => %s,%s", $variant, $path, PHP_EOL);
      }
      $cache_data .= sprintf("  ),%s", PHP_EOL);
    }
    $cache_data .= ") ?>";
    file_put_contents(self::CACHE_FILE, $cache_data);
  }

  /**
   * Loads the stored font family cache
   *
   * @see save_font_families()
   */
  static function load_font_families() {
    $dist_fonts = require_once DOMPDF_DIR . "/lib/fonts/dompdf_font_family_cache.dist.php";

    // FIXME: temporary step for font cache created before the font cache fix
    if ( is_readable( DOMPDF_FONT_DIR . "dompdf_font_family_cache" ) ) {
      $old_fonts = require_once DOMPDF_FONT_DIR . "dompdf_font_family_cache";
      // If the font family cache is still in the old format
      if ( $old_fonts === 1 ) {
        $cache_data = file_get_contents(DOMPDF_FONT_DIR . "dompdf_font_family_cache");
        file_put_contents(DOMPDF_FONT_DIR . "dompdf_font_family_cache", "<"."?php return $cache_data ?".">");
        $old_fonts = require_once DOMPDF_FONT_DIR . "dompdf_font_family_cache";
      }
      $dist_fonts += $old_fonts;
    }

    if ( !is_readable(self::CACHE_FILE) ) {
      self::$_font_lookup = $dist_fonts;
      return;
    }

    $cache_data = require_once self::CACHE_FILE;

    // If the font family cache is still in the old format
    if ( self::$_font_lookup === 1 ) {
      $cache_data = file_get_contents(self::CACHE_FILE);
      file_put_contents(self::CACHE_FILE, "<"."?php return $cache_data ?".">");
      $cache_data = require_once self::CACHE_FILE;
    }

    self::$_font_lookup = array();
    foreach ($cache_data as $key => $value) {
      self::$_font_lookup[stripslashes($key)] = $value;
    }

    // Merge provided fonts
    self::$_font_lookup += $dist_fonts;
  }

  static function get_type($type) {
    if (preg_match("/bold/i", $type)) {
      if (preg_match("/italic|oblique/i", $type)) {
        $type = "bold_italic";
      }
      else {
        $type = "bold";
      }
    }
    elseif (preg_match("/italic|oblique/i", $type)) {
      $type = "italic";
    }
    else {
      $type = "normal";
    }

    return $type;
  }

  static function install_fonts($files) {
    $names = array();

    foreach($files as $file) {
      $font = Font::load($file);
      $records = $font->getData("name", "records");
      $type = self::get_type($records[2]);
      $names[mb_strtolower($records[1])][$type] = $file;
    }

    return $names;
  }

  static function get_system_fonts() {
    $files = glob("/usr/share/fonts/truetype/*.ttf") +
             glob("/usr/share/fonts/truetype/*/*.ttf") +
             glob("/usr/share/fonts/truetype/*/*/*.ttf") +
             glob("C:\\Windows\\fonts\\*.ttf") + 
             glob("C:\\WinNT\\fonts\\*.ttf") + 
             glob("/mnt/c_drive/WINDOWS/Fonts/");

    return self::install_fonts($files);
  }

  /**
   * Returns the current font lookup table
   *
   * @return array
   */
  static function get_font_families() {
    return self::$_font_lookup;
  }

  static function set_font_family($fontname, $entry) {
    self::$_font_lookup[mb_strtolower($fontname)] = $entry;
  }

  static function register_font($style, $remote_file, $context = null) {
    $fontname = mb_strtolower($style["family"]);
    $families = Font_Metrics::get_font_families();

    $entry = array();
    if ( isset($families[$fontname]) ) {
      $entry = $families[$fontname];
    }

    $local_file = DOMPDF_FONT_DIR . md5($remote_file);
    $local_temp_file = DOMPDF_TEMP_DIR . "/" . md5($remote_file);
    $cache_entry = $local_file;
    $local_file .= ".ttf";

    $style_string = Font_Metrics::get_type("{$style['weight']} {$style['style']}");

    if ( !isset($entry[$style_string]) ) {
      $entry[$style_string] = $cache_entry;

      // Download the remote file
      file_put_contents($local_temp_file, file_get_contents($remote_file, null, $context));

      $font = Font::load($local_temp_file);

      if (!$font) {
        unlink($local_temp_file);
        return false;
      }

      $font->parse();
      $font->saveAdobeFontMetrics("$cache_entry.ufm");

      unlink($local_temp_file);

      if ( !file_exists("$cache_entry.ufm") ) {
        return false;
      }

      // Save the changes
      file_put_contents($local_file, file_get_contents($remote_file, null, $context));
      Font_Metrics::set_font_family($fontname, $entry);
      Font_Metrics::save_font_families();
    }

    return true;
  }
}

Font_Metrics::load_font_families();

 * @author  Benj Carson <[email protected]>
 * @author  Helmut Tischer <[email protected]>

ESTA ES LA LINEA 354 QUE GENERA EL ERROR

      // Download the remote file
      file_put_contents($local_temp_file, file_get_contents($remote_file, null, $context));
5
  • 2
    Parece que no es un problema con dónde colocas las fuentes, sino en cómo las incluyes (o más bien en cómo generas la ruta a la hora de incluirlas). Por favor añade el código también, en particular el de la línea 354 en la que se incluyen las fuentes y falla.
    – Alvaro Montoro
    el 5 feb. 2016 a las 14:45
  • Ya agregué el respectivo código amigo @AlvaroMontoro el 5 feb. 2016 a las 21:29
  • Yo diría que el error es que la ruta a las fuentes es incorrecta (la mitad está en "formato windows" con ` y la otra mitad está en "formato UNIX" con /). Tendrías que mirar donde creas $remote_file` antes de llamar a la función register_font(), pero esa parte del código no está en la pregunta :)
    – Alvaro Montoro
    el 5 feb. 2016 a las 21:41
  • @AlvaroMontoro el 2do bloque de código incluye todo el archivo y todas esas variables el 5 feb. 2016 a las 21:45
  • En el código que has compartido sólo está la definición de la función register_font a la que pasas el parámetro $remote_file: ¿dónde está la llamada a esa función?¿dónde generas la variable que pasas como parámetro? Si no me equivoco, ahí es donde encontrarás el problema, porque esa variable seguramente se crea concatenando los valores de dos variables/funciones con rutas en diferentes formatos
    – Alvaro Montoro
    el 5 feb. 2016 a las 21:53

2 respuestas 2

3

El problema fue solucionado, lo que hice fue sustituir el código css de bootstrap que incluía en el header de la pagina:

<style type="text/css">
        /*!
         * Bootstrap v3.3.5 (http://getbootstrap.com)
         * Copyright 2011-2015 Twitter, Inc.
         * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
         *//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
     </style> 

por la llamada al archivo css de forma normal:

<link href="css/bootstrap.min.css" rel="stylesheet">

De esta forma el problema fue solucionado. Gracias por su colaboracion.

2
  • 1
    Cualquiera diría que es una solución muy tonta, pero cuando uno adquiere cierto nivel en las herramientas, las cosas más simples siempre son las que primero se olvidan.
    – SalahAdDin
    el 5 abr. 2016 a las 5:37
  • efectivamente me soluciono el problema
    – bypabloc_
    el 21 jul. 2017 a las 16:49
0

Eso pasa por que la carpeta fuentes, fonts no se genera automáticamente, si la generas dentro de la carpeta storage ocurre ese problema.

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.