Foros del Web » Programando para Internet » PHP » Zend »

No se carga imagen con libreria tcpdf con zend framework

Estas en el tema de No se carga imagen con libreria tcpdf con zend framework en el foro de Zend en Foros del Web. Hola, estoy tratando de crear pdf con la librería tcpdf con zend framework y ya agregue la librería en la seccion de "library" y estaba ...
  #1 (permalink)  
Antiguo 23/12/2010, 11:04
 
Fecha de Ingreso: febrero-2010
Ubicación: Machala
Mensajes: 9
Antigüedad: 14 años, 2 meses
Puntos: 0
Pregunta No se carga imagen con libreria tcpdf con zend framework

Hola, estoy tratando de crear pdf con la librería tcpdf con zend framework y ya agregue la librería en la seccion de "library" y estaba probando los ejemplos en el proyecto y si salen (en lo que se refiere a texto) pero cuando cargo una imagen me sale un error "el archivo está dañado y no puede repararse", eso me sale en el navegador mozilla... :(

La verdad en algunos foros mencionan que hay que configurar algunos parametros en el archivo tcpdf_config.php, pero la verdad he revisado y no sé como será de configurarle la ruta o porque no me sale el pdf, creo que es por la ruta de la imagen que no me genera el pdf...

Cualquier sugerencia sera bienvenida
  #2 (permalink)  
Antiguo 23/12/2010, 11:32
 
Fecha de Ingreso: diciembre-2010
Ubicación: Rosario, Santa Fe
Mensajes: 326
Antigüedad: 13 años, 4 meses
Puntos: 13
Respuesta: No se carga imagen con libreria tcpdf con zend framework

Si nos pones el código que usas para generar el pdf tal vez te podamos ayudar. Ya que sin ver es muy dificil encontrar el problema.
  #3 (permalink)  
Antiguo 23/12/2010, 12:52
 
Fecha de Ingreso: febrero-2010
Ubicación: Machala
Mensajes: 9
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: No se carga imagen con libreria tcpdf con zend framework

Ok, tengo el siguiente codigo:

Una clase que hereda de tcpdf y es donde cargo la imagen:

Código PHP:
require_once 'tcpdf/tcpdf.php';

class 
adm_createCurriculum extends TCPDF
{
        public function 
Header() {
        
// Logo
        
$image_file K_PATH_IMAGES.'foto.png';
        
$this->Image($image_file101015'''PNG''''T'false300''falsefalse0falsefalsefalse);
        
// Set font
        
$this->SetFont('helvetica''B'20);
        
// Title
        
$this->Cell(015'Curriculum Vitae'0false'C'0''0false'T''M');
    }

    
// Page footer
    
public function Footer() {
        
// Position at 15 mm from bottom
        
$this->SetY(-15);
        
// Set font
        
$this->SetFont('helvetica''I'8);
        
// Page number
        
$this->Cell(010'Pagina '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0false'R'0''0false'T''M');
    }


la constante K_PATH_IMAGES está en el archivo de configuración de la librería:
Código PHP:
if (!defined('K_TCPDF_EXTERNAL_CONFIG')) {

    
// DOCUMENT_ROOT fix for IIS Webserver
    
if ((!isset($_SERVER['DOCUMENT_ROOT'])) OR (empty($_SERVER['DOCUMENT_ROOT']))) {
        if(isset(
$_SERVER['SCRIPT_FILENAME'])) {
            
$_SERVER['DOCUMENT_ROOT'] = str_replace'\\''/'substr($_SERVER['SCRIPT_FILENAME'], 00-strlen($_SERVER['PHP_SELF'])));
        } elseif(isset(
$_SERVER['PATH_TRANSLATED'])) {
            
$_SERVER['DOCUMENT_ROOT'] = str_replace'\\''/'substr(str_replace('\\\\''\\'$_SERVER['PATH_TRANSLATED']), 00-strlen($_SERVER['PHP_SELF'])));
        }    else {
            
// define here your DOCUMENT_ROOT path if the previous fails
            
$_SERVER['DOCUMENT_ROOT'] = 'C:/xampp/htdocs/reporte/library/tcpdf';//aqui defino una ruta pero no estoy segura de como debe estar declarada la ruta, si es donde están todos los proyectos o solo el que utilizo, 
        
}
    }

    
// Automatic calculation for the following K_PATH_MAIN constant
    
$k_path_main str_replace'\\''/'realpath(substr(dirname(__FILE__), 00-strlen('config'))));
    if (
substr($k_path_main, -1) != '/') {
        
$k_path_main .= '/';
    }

    
/**
     * Installation path (/var/www/tcpdf/).
     * By default it is automatically calculated but you can also set it as a fixed string to improve performances.
     */
    
define ('K_PATH_MAIN'$k_path_main);

    
// Automatic calculation for the following K_PATH_URL constant
    
$k_path_url $k_path_main// default value for console mode
    
if (isset($_SERVER['HTTP_HOST']) AND (!empty($_SERVER['HTTP_HOST']))) {
        if(isset(
$_SERVER['HTTPS']) AND (!empty($_SERVER['HTTPS'])) AND strtolower($_SERVER['HTTPS'])!='off') {
            
$k_path_url 'https://';
        } else {
            
$k_path_url 'http://';
        }
        
$k_path_url .= $_SERVER['HTTP_HOST'];
        
$k_path_url .= str_replace'\\''/'substr(K_PATH_MAIN, (strlen($_SERVER['DOCUMENT_ROOT']) - 1)));
    }

    
/**
     * URL path to tcpdf installation folder (http://localhost/tcpdf/).
     * By default it is automatically calculated but you can also set it as a fixed string to improve performances.
     */
    
define ('K_PATH_URL'$k_path_url);

    
/**
     * path for PDF fonts
     * use K_PATH_MAIN.'fonts/old/' for old non-UTF8 fonts
     */
    
define ('K_PATH_FONTS'K_PATH_MAIN.'fonts/');

    
/**
     * cache directory for temporary files (full path)
     */
    
define ('K_PATH_CACHE'K_PATH_MAIN.'cache/');

    
/**
     * cache directory for temporary files (url path)
     */
    
define ('K_PATH_URL_CACHE'K_PATH_URL.'cache/');

    
/**
     *images directory
     */
    
define ('K_PATH_IMAGES'K_PATH_MAIN.'images/');

    
/**
     * blank image
     */
    
define ('K_BLANK_IMAGE'K_PATH_IMAGES.'_blank.png');

    
/**
     * page format
     */
    
define ('PDF_PAGE_FORMAT''A4');

    
/**
     * page orientation (P=portrait, L=landscape)
     */
    
define ('PDF_PAGE_ORIENTATION''P');

    
/**
     * document creator
     */
    
define ('PDF_CREATOR''TCPDF');

    
/**
     * document author
     */
    
define ('PDF_AUTHOR''TCPDF');

    
/**
     * header title
     */
    
define ('PDF_HEADER_TITLE''TCPDF Example');

    
/**
     * header description string
     */
    
define ('PDF_HEADER_STRING'"by Nicola Asuni - Tecnick.com\nwww.tcpdf.org");

    
/**
     * image logo
     */
    
define ('PDF_HEADER_LOGO''tcpdf_logo.jpg');

    
/**
     * header logo image width [mm]
     */
    
define ('PDF_HEADER_LOGO_WIDTH'30);

    
/**
     *  document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch]
     */
    
define ('PDF_UNIT''mm');

    
/**
     * header margin
     */
    
define ('PDF_MARGIN_HEADER'5);

    
/**
     * footer margin
     */
    
define ('PDF_MARGIN_FOOTER'10);

    
/**
     * top margin
     */
    
define ('PDF_MARGIN_TOP'27);

    
/**
     * bottom margin
     */
    
define ('PDF_MARGIN_BOTTOM'25);

    
/**
     * left margin
     */
    
define ('PDF_MARGIN_LEFT'15);

    
/**
     * right margin
     */
    
define ('PDF_MARGIN_RIGHT'15);

    
/**
     * default main font name
     */
    
define ('PDF_FONT_NAME_MAIN''helvetica');

    
/**
     * default main font size
     */
    
define ('PDF_FONT_SIZE_MAIN'10);

    
/**
     * default data font name
     */
    
define ('PDF_FONT_NAME_DATA''helvetica');

    
/**
     * default data font size
     */
    
define ('PDF_FONT_SIZE_DATA'8);

    
/**
     * default monospaced font name
     */
    
define ('PDF_FONT_MONOSPACED''courier');

    
/**
     * ratio used to adjust the conversion of pixels to user units
     */
    
define ('PDF_IMAGE_SCALE_RATIO'1.25);

    
/**
     * magnification factor for titles
     */
    
define('HEAD_MAGNIFICATION'1.1);

    
/**
     * height of cell repect font height
     */
    
define('K_CELL_HEIGHT_RATIO'1.25);

    
/**
     * title magnification respect main font size
     */
    
define('K_TITLE_MAGNIFICATION'1.3);

    
/**
     * reduction factor for small font
     */
    
define('K_SMALL_RATIO'2/3);

    
/**
     * set to true to enable the special procedure used to avoid the overlappind of symbols on Thai language
     */
    
define('K_THAI_TOPCHARS'true);

    
/**
     * if true allows to call TCPDF methods using HTML syntax
     * IMPORTANT: For security reason, disable this feature if you are printing user HTML content.
     */
    
define('K_TCPDF_CALLS_IN_HTML'true); 
Un controlador donde hago uso de esa clase:

Código PHP:
require_once APPLICATION_PATH .'/functions/adm_createCurriculum.php';
require_once 
'tcpdf/config/lang/spa.php';
require_once 
'tcpdf/tcpdf.php';

class 
IndexController extends Zend_Controller_Action
{
      public function 
indexAction()
     {
      try{
        
// create new PDF document
        
$pdf = new adm_createCurriculum(PDF_PAGE_ORIENTATIONPDF_UNITPDF_PAGE_FORMATtrue'UTF-8'false);//adm_createCurriculum();//
        
        // set document information
        
$pdf->SetCreator(PDF_CREATOR);
        
$pdf->SetAuthor('UTMACH');
        
$pdf->SetTitle('Curriculum Vitae');
        
$pdf->SetSubject('RR.HH.');
        
        
// set font
        
$pdf->SetFont('times'''16);

        
//add a page
        
$pdf->AddPage();
        
$pdf->Cell(20,20,"Patricia Perez",0,0,'L');        
        
$pdf->Ln(15);
        
$pdf->MultiCell(0,40,"Algo por ahi que ya no me acuerdo y tiene mucho que decir, haber que mas le agrego para que salte a la siguiente linea.");
        
        
//Close and output PDF document
        
echo $pdf->Output("file.pdf","I");
       }catch(
Exception$ex)
       {
         echo 
$ex->getMessage();    
       }
    }

Ese es el código principal que utilizo...
  #4 (permalink)  
Antiguo 23/12/2010, 13:09
 
Fecha de Ingreso: diciembre-2010
Ubicación: Rosario, Santa Fe
Mensajes: 326
Antigüedad: 13 años, 4 meses
Puntos: 13
Respuesta: No se carga imagen con libreria tcpdf con zend framework

en el primero de los codigos, imprimiste $image_file para ver si el path era correcto?
Aunque lo mejor sería probar si file_exists($image_file) da verdadero, en ese caso queda descartado que tenga problema con la imagen.
  #5 (permalink)  
Antiguo 23/12/2010, 13:25
 
Fecha de Ingreso: febrero-2010
Ubicación: Machala
Mensajes: 9
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: No se carga imagen con libreria tcpdf con zend framework

ya le probé para ver si existe y tambien imprimi la ruta e igual me sigue sin salir... :(
  #6 (permalink)  
Antiguo 23/12/2010, 16:19
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: No se carga imagen con libreria tcpdf con zend framework

Que tal mar_y_sol, esta es la ruta de la carpeta image ? library/tcpdf/image , si no es debería serlo, igual te comento que no estas integrando de una forma muy "limpia" la librería, deberías tener library/Application/TcPdf.php

Código PHP:
Ver original
  1. <?php
  2. require_once 'tcpdf/tcpdf.php';
  3.  
  4. Application_TcPdf extends TCPDF
  5. {
  6.    public function Header()
  7.    {
  8.         // Logo
  9.         $image_file = K_PATH_IMAGES . 'foto.png';
  10.         $this->Image($image_file, 10, 10, 15, '', 'PNG', '', 'T', false,
  11.                     300, '', false, false, 0, false, false, false);
  12.         // Set font
  13.         $this->SetFont('helvetica', 'B', 20);
  14.         // Title
  15.         $this->Cell(0, 15, 'Curriculum Vitae', 0, false, 'C', 0,
  16.                        '', 0, false, 'T', 'M');
  17.     }
  18.  
  19.     // Page footer
  20.     public function Footer()
  21.     {
  22.         // Position at 15 mm from bottom
  23.         $this->SetY(-15);
  24.         // Set font
  25.         $this->SetFont('helvetica', 'I', 8);
  26.         // Page number
  27.         $this->Cell(0, 10, 'Pagina '. $this->getAliasNumPage() . '/' .
  28.                $this->getAliasNbPages(),  0, false, 'R', 0, '', 0, false, 'T', 'M');
  29.     }
}

y luego para utilizarla

Código PHP:
Ver original
  1. //IndexController.php
  2. ...
  3. public function indexAction()
  4. {
  5.      try {
  6.          $pdf = new Application_TcPdf(PDF_PAGE_ORIENTATION, PDF_UNIT,
  7.                                       PDF_PAGE_FORMAT, true, 'UTF-8', false);
  8.          ...
  9.       } catch(Exception $e){...}
  10. }
  11. ...

Saludos.
  #7 (permalink)  
Antiguo 27/12/2010, 15:07
 
Fecha de Ingreso: febrero-2010
Ubicación: Machala
Mensajes: 9
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: No se carga imagen con libreria tcpdf con zend framework

gracias por su recomendación masterpuppet pero sabes, ya intenté de esa forma también pero tampoco me sale... :( la verdad no entiendo por qué no me carga la imagen porque sigo creyendo que es la imagen la que no quiere mostrar...

Una pregunta la carpeta images y cache deben tener permisos de escritura cierto, bueno eso encontré en la pagina de la librería que decía que debían tener pero aún así no me sale...

Etiquetas: carga, framework, libreria, php, tcpdf
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:22.