File "pdf.php"

Full Path: C:/wamp64/www/sistemas/activosFijos/pdf.php
File size: 14.63 KB
MIME-type: text/x-php
Charset: utf-8

<?php
require_once('tcpdf/tcpdf.php'); // TCPDF versión 6.4.4 compatible con PHP 5.5+
include("../connection.php");

// Función para convertir imágenes a JPG si es necesario
function convertirAJPG($archivo_origen, $mime_type) {
    try {
        $imagen = null;
        
        switch($mime_type) {
            case 'image/png':
                $imagen = imagecreatefrompng($archivo_origen);
                break;
            case 'image/gif':
                $imagen = imagecreatefromgif($archivo_origen);
                break;
            case 'image/webp':
                if (function_exists('imagecreatefromwebp')) {
                    $imagen = imagecreatefromwebp($archivo_origen);
                }
                break;
        }
        
        if ($imagen) {
            $temp_jpg = tempnam(sys_get_temp_dir(), 'converted_') . '.jpg';
            
            // Crear fondo blanco para imágenes con transparencia
            $fondo = imagecreatetruecolor(imagesx($imagen), imagesy($imagen));
            $blanco = imagecolorallocate($fondo, 255, 255, 255);
            imagefill($fondo, 0, 0, $blanco);
            imagecopy($fondo, $imagen, 0, 0, 0, 0, imagesx($imagen), imagesy($imagen));
            
            imagejpeg($fondo, $temp_jpg, 90);
            imagedestroy($imagen);
            imagedestroy($fondo);
            
            return $temp_jpg;
        }
    } catch (Exception $e) {
        // Si falla la conversión, retornar false
    }
    
    return false;
}

$con = connection();

// Verificar si se ha enviado el formulario
if (isset($_POST['generar_pdf'])) {
    // Obtener los filtros del formulario
    $filtro_numero_acta = $_POST['numero_acta'];
    $filtro_tipo = $_POST['tipo'];
    $filtro_equipo = $_POST['equipo'];
    $filtro_fecha_inicio = $_POST['fecha_inicio'];
    $filtro_fecha_fin = $_POST['fecha_fin'];

    // Construir la misma consulta SQL que en buscarActivo.php
    $sql = "SELECT * FROM bajaActivos WHERE 1=1";

    if (!empty($filtro_numero_acta)) {
        $sql .= " AND numero_acta LIKE '%$filtro_numero_acta%'";
    }

    if (!empty($filtro_tipo)) {
        $sql .= " AND tipo LIKE '%$filtro_tipo%'";
    }

    if (!empty($filtro_equipo)) {
        $sql .= " AND equipo LIKE '%$filtro_equipo%'";
    }

    if (!empty($filtro_fecha_inicio) && !empty($filtro_fecha_fin)) {
        $sql .= " AND fecha BETWEEN '$filtro_fecha_inicio' AND '$filtro_fecha_fin'";
    }

    $query = mysqli_query($con, $sql);
	$primer_acta = 'N/A';
	if ($fila_primera = mysqli_fetch_assoc($query)) {
		$primer_acta = $fila_primera['numero_acta'];

		// Reposicionar el puntero del resultado para poder usarlo en el while luego
		mysqli_data_seek($query, 0);
	}


    if (!$query) {
        die('Error en la consulta SQL: ' . mysqli_error($con));
    }

    // Crear nueva instancia de TCPDF
    $pdf = new TCPDF('L', PDF_UNIT, 'A4', true, 'UTF-8', false); // 'L' para orientación horizontal

    // Establecer información del documento
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Avicampo');
    $pdf->SetTitle('Reporte de Baja de Activos Fijos');
    $pdf->SetSubject('Reporte de Activos');

    // Configurar márgenes
    $pdf->SetMargins(15, 30, 15);
    $pdf->SetHeaderMargin(5);
    $pdf->SetFooterMargin(10);

    // Configurar salto de página automático
    $pdf->SetAutoPageBreak(TRUE, 25);

    // Establecer fuente
    $pdf->SetFont('helvetica', '', 10);

    // Agregar página
    $pdf->AddPage();

    // ENCABEZADO CON IMAGEN
    // Función para detectar tipo de imagen y convertir si es necesario
    function procesarImagenEncabezado($ruta_imagen) {
        if (!file_exists($ruta_imagen)) {
            return false;
        }
        
        $info = getimagesize($ruta_imagen);
        $tipo = $info[2];
        
        // Si es PNG, convertir a JPG temporalmente
        if ($tipo == IMAGETYPE_PNG) {
            $imagen = imagecreatefrompng($ruta_imagen);
            $temp_jpg = tempnam(sys_get_temp_dir(), 'header_') . '.jpg';
            
            // Crear fondo blanco para PNGs transparentes
            $fondo = imagecreatetruecolor(imagesx($imagen), imagesy($imagen));
            $blanco = imagecolorallocate($fondo, 255, 255, 255);
            imagefill($fondo, 0, 0, $blanco);
            imagecopy($fondo, $imagen, 0, 0, 0, 0, imagesx($imagen), imagesy($imagen));
            
            imagejpeg($fondo, $temp_jpg, 90);
            imagedestroy($imagen);
            imagedestroy($fondo);
            return $temp_jpg;
        }
        
        // Si es JPEG, usar directamente
        if ($tipo == IMAGETYPE_JPEG) {
            return $ruta_imagen;
        }
        
        // Si es JPG, usar directamente
        return $ruta_imagen;
    }
    
    $logo_path = '../img/encabezado.jpg'; // Buscar JPG primero
    if (!file_exists($logo_path)) {
        $logo_path = '../img/encabezado.png'; // Si no existe, buscar PNG
    }
    if (!file_exists($logo_path)) {
        $logo_path = '../img/encabezado.jpeg'; // Si no existe, buscar JPEG
    }
    
    $imagen_procesada = procesarImagenEncabezado($logo_path);
    if ($imagen_procesada) {
        $pdf->Image($imagen_procesada, 15, 10, 267, 30, 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
        
        // Si creamos un archivo temporal, eliminarlo
        if ($imagen_procesada != $logo_path) {
            unlink($imagen_procesada);
        }
    }

    // Mover cursor después del encabezado
    $pdf->Ln(35);

    // TÍTULO PRINCIPAL
    $pdf->SetFont('helvetica', 'B', 16);
    $pdf->Cell(0, 10, 'ACTA DE BAJA DE ACTIVOS FIJOS', 0, 1, 'C');
    
	$pdf->Cell(0, 6, 'Número de Acta: ' . $primer_acta, 0, 1, 'R');


    // FECHA ACTUAL
    $pdf->SetFont('helvetica', '', 10);
    $fecha_actual = date('d/m/Y H:i:s');
    $pdf->Cell(0, 6, 'Fecha de generación: ' . $fecha_actual, 0, 1, 'R');
    $pdf->Ln(5);

    // OBJETIVOS
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'OBJETIVOS', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 10);
    $objetivo_text = 'Dar de baja a los artículos del área de sistemas, los cuales ya no cuentan con las condiciones para darles utilidad dentro de la organización por daño total.';
    $pdf->MultiCell(0, 6, $objetivo_text, 0, 'J');
    $pdf->Ln(5);

    // DETERMINACIONES
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'DETERMINACIONES', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 10);
    $pdf->Cell(0, 6, 'Se da de baja al siguiente material:', 0, 1, 'L');
    $pdf->Ln(3);

    // TABLA DE DATOS
    if (mysqli_num_rows($query) > 0) {
        // Encabezados de la tabla
        $pdf->SetFont('helvetica', 'B', 9);
        $pdf->SetFillColor(200, 200, 200);
        
        // Definir anchos de columnas para orientación horizontal
        $w = array(25, 20, 20, 35, 25, 30, 30, 25, 25, 25); // Ajustar según necesidad
        
        $pdf->Cell($w[0], 7, 'Nombre', 1, 0, 'C', 1);
        $pdf->Cell($w[1], 7, 'Cargo', 1, 0, 'C', 1);
        $pdf->Cell($w[2], 7, 'Tipo', 1, 0, 'C', 1);
        $pdf->Cell($w[3], 7, 'Motivo', 1, 0, 'C', 1);
        $pdf->Cell($w[4], 7, 'Equipo', 1, 0, 'C', 1);
        $pdf->Cell($w[5], 7, 'Referencia', 1, 0, 'C', 1);
		$pdf->Cell($w[6], 7, 'numero_acta', 1, 0, 'C', 1);
        $pdf->Cell($w[7], 7, 'Serial', 1, 0, 'C', 1);
        $pdf->Cell($w[8], 7, 'Fecha', 1, 1, 'C', 1);

        // Datos de la tabla
        $pdf->SetFont('helvetica', '', 9);
        $imagenes_evidencia = array();
		$hashes_imagenes = array(); // Para detectar duplicados

        
        while ($row = mysqli_fetch_array($query)) {
            $pdf->Cell($w[0], 6, substr($row['nombre'], 0, 20), 1, 0, 'L');
            $pdf->Cell($w[1], 6, substr($row['cargo'], 0, 15), 1, 0, 'L');
            $pdf->Cell($w[2], 6, substr($row['tipo'], 0, 15), 1, 0, 'L');
            $pdf->Cell($w[3], 6, substr($row['motivo'], 0, 25), 1, 0, 'L');
            $pdf->Cell($w[4], 6, substr($row['equipo'], 0, 20), 1, 0, 'L');
            $pdf->Cell($w[5], 6, substr($row['referencia'], 0, 25), 1, 0, 'L');
            $pdf->Cell($w[6], 6, substr($row['numero_acta'], 0, 25), 1, 0, 'L');
			$pdf->Cell($w[7], 6, substr($row['serial'], 0, 25), 1, 0, 'L');
            $pdf->Cell($w[8], 6, $row['fecha'], 1, 1, 'L');
            
            // Guardar imagen si existe
            if (!empty($row['evidencia'])) {
				$hash = md5($row['evidencia']); // Hash para identificar duplicados
				if (!in_array($hash, $hashes_imagenes)) {
					$imagenes_evidencia[] = $row['evidencia'];
					$hashes_imagenes[] = $hash;
				}
			}

        }
    }

    $pdf->Ln(10);

    // REGISTRO FOTOGRÁFICO
    if (!empty($imagenes_evidencia)) {
        $pdf->AddPage(); // Nueva página para las imágenes
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'REGISTRO FOTOGRÁFICO', 0, 1, 'L');
        $pdf->Ln(5);

        $x = 20; // Posición X inicial
        $y = 50; // Posición Y inicial
        $img_width = 70;  // ← AUMENTA ESTE VALOR para imágenes más anchas
        $img_height = 40; // ← AUMENTA ESTE VALOR para imágenes más altas
        $margin = 10;     // ← Puedes aumentar el margen entre imágenes
        $images_per_row = 3; // ← Reduce este número si las imágenes son muy grandes
        $current_image = 0;

        foreach ($imagenes_evidencia as $imagen_blob) {
            // Detectar tipo de imagen desde BLOB
            $finfo = new finfo(FILEINFO_MIME_TYPE);
            $mime_type = $finfo->buffer($imagen_blob);
            
            // Crear archivo temporal con extensión correcta
            $extension = '';
            $formato_tcpdf = 'JPG'; // Por defecto JPG para TCPDF
            
            switch($mime_type) {
                case 'image/jpeg':
                    $extension = '.jpg';
                    $formato_tcpdf = 'JPG';
                    break;
                case 'image/png':
                    $extension = '.png';
                    $formato_tcpdf = 'PNG';
                    break;
                case 'image/gif':
                    $extension = '.gif';
                    $formato_tcpdf = 'GIF';
                    break;
                default:
                    $extension = '.jpg';
                    $formato_tcpdf = 'JPG';
            }
            
            $temp_file = tempnam(sys_get_temp_dir(), 'img_') . $extension;
            file_put_contents($temp_file, $imagen_blob);

            // Calcular posición
            $col = $current_image % $images_per_row;
            $row = floor($current_image / $images_per_row);
            
            $pos_x = $x + ($col * ($img_width + $margin));
            $pos_y = $y + ($row * ($img_height + $margin + 10));

            // Verificar si necesitamos nueva página
			if ($pos_y + $img_height + $margin > 190) { // Ajuste dinámico
				$pdf->AddPage();
				$pdf->Ln(5);
				$pdf->SetFont('helvetica', '', 10);
				$y = 50; // Reiniciar posición Y inicial
				$pos_y = $y;
				$row = 0;
				$col = 0;
				// Ajustar current_image para que no salte de posición
				$current_image = 0;
			}


            // Insertar imagen con formato detectado
            try {
                $pdf->Image($temp_file, $pos_x, $pos_y, $img_width, $img_height, $formato_tcpdf);
            } catch (Exception $e) {
                // Si falla, intentar convertir a JPG
                if ($formato_tcpdf != 'JPG') {
                    $imagen_convertida = convertirAJPG($temp_file, $mime_type);
                    if ($imagen_convertida) {
                        $pdf->Image($imagen_convertida, $pos_x, $pos_y, $img_width, $img_height, 'JPG');
                        unlink($imagen_convertida);
                    }
                }
            }
            
            // Eliminar archivo temporal
            unlink($temp_file);
            
            $current_image++;
        }
    }

    // FIRMAS - Nueva página
    $pdf->AddPage();
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'FIRMAS', 0, 1, 'C');
    $pdf->Ln(5);

    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->Cell(0, 6, 'FIRMAS (Garantes)', 0, 1, 'C');
    $pdf->Ln(10);

    // Diseño de firmas en dos columnas
    $col_width = 130;
    $line_height = 20;

    // Primera fila de firmas
    $pdf->SetFont('helvetica', '', 9);
    
    // JEFE DE SISTEMAS
    $pdf->Cell($col_width, $line_height, '', 'B', 0, 'C');
    $pdf->Cell(10, $line_height, '', 0, 0, 'C'); // Espacio
    $pdf->Cell($col_width, $line_height, '', 'B', 1, 'C');
    
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell($col_width, 6, 'JEFE DE SISTEMAS', 0, 0, 'C');
    $pdf->Cell(10, 6, '', 0, 0, 'C');
    $pdf->Cell($col_width, 6, 'JEFE AMBIENTAL', 0, 1, 'C');
    
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell($col_width, 5, 'ARLEY RESTREPO', 0, 0, 'C');
    $pdf->Cell(10, 5, '', 0, 0, 'C');
    $pdf->Cell($col_width, 5, 'MAIRA ALEXANDRA CLAVIJO LOPEZ', 0, 1, 'C');
    $pdf->Ln(15);

    // Segunda fila de firmas
    $pdf->SetFont('helvetica', '', 9);
    $pdf->Cell($col_width, $line_height, '', 'B', 0, 'C');
    $pdf->Cell(10, $line_height, '', 0, 0, 'C');
    $pdf->Cell($col_width, $line_height, '', 'B', 1, 'C');
    
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell($col_width, 6, 'AUXILIAR DE COSTOS', 0, 0, 'C');
    $pdf->Cell(10, 6, '', 0, 0, 'C');
    $pdf->Cell($col_width, 6, 'AUDITOR', 0, 1, 'C');
    
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell($col_width, 5, 'LUIS AMAYA', 0, 0, 'C');
    $pdf->Cell(10, 5, '', 0, 0, 'C');
    $pdf->Cell($col_width, 5, 'SEBASTIAN MATURANA LLANO', 0, 1, 'C');
    $pdf->Ln(15);

    // Tercera fila - AUTORIZADO (centrado)
    $pdf->SetFont('helvetica', '', 9);
    $pdf->Cell(0, $line_height, '', 'B', 1, 'C');
    
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell(0, 6, 'AUTORIZADO', 0, 1, 'C');
    $pdf->Cell(0, 6, 'GERENCIA ADMINISTRATIVA', 0, 1, 'C');
    
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell(0, 5, 'SANDRA INES RUIZ AGUILAR', 0, 1, 'C');

    // Pie de página
    $pdf->Ln(10);
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell(0, 5, '© Avicampo ' . date('Y'), 0, 1, 'C');

    // Generar nombre de archivo
    $fecha_actual = date('Y-m-d_H-i-s');
    $nombre_archivo = "Reporte_Activos_Fijos_$fecha_actual.pdf";

    // Enviar el PDF al navegador
    $pdf->Output($nombre_archivo, 'D'); // 'D' para descarga, 'I' para mostrar en navegador

} else {
    // Redirigir si no se accede correctamente
    header("Location: buscarActivo.php");
    exit();
}
?>