¿Cómo parser un pdf con php?

Estoy empezando con php y mi primera tarea es obtener datos de un pdf, me comentaron la siguiente librería: pdfparser.org. No tiene mala pinta pero solo tiene un par de ejemplos sencillos y no acabo de entender como funciona... Consigo obtener el texto en bruto de cada página pero luego debo tratar como ese texto para obtener un nombre, un titulo... Es muy complicado... ¿me pregunto si hay alguna forma de extraer los datos que simplifique un poco esta tarea... Alguien puede echarme una mano? ¿Ya sea conociendo esta librería o con algún ejemplo que haya visto en otra parte..?

2 Respuestas

Respuesta
-1

para empezar deberias usar DomPDF https://code.google.com/p/dompdf/ 

Es bastante Simple, Solo usas una mezcla entre PHP y HTML

Acá te Explico un listado simple en PDF

¿

¿
<?php
//Buscamos la Libreria y nos conectamos a la base de datos
require_once("dompdf/dompdf_config.inc.php");
include("conexion.php");
//en este caso usamos una Variable llamada HTML Crearemos una tabla
$html='
<html>
<body>
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
   <tr>
    <td >
      <img src="logo.png">
    </td>
    <td colspan="2"><center><h2>Listado General de Clientes</h2></center><br/><br/></td></tr>
';
//consulta de los datos del docente
$consulta1 = "select distinct * from usuarios,cli_prov where nivel='2' and usuarios.id=id_usu ";
// Ejecuta la consulta
$resultado = mysql_query( $consulta1 );
######################Imprimiendo datos ################################
$html.='
<tr>
    <td bgcolor="#5191FF" width="100"><center><b>NOMBRE DE USUARIOS</b></center></td>
    <td bgcolor="#5191FF" width="200"><b>NOMBRE DE LA EMPRESA</b></td>
    <td bgcolor="#5191FF" width="100"><b>TELEFONO</b></td>
    <td bgcolor="#5191FF" width="150"><b>CORREO</b></td>
</tr>';
while ($resultado_fila = mysql_fetch_array($resultado)){
$html.='    
<tr>
    <td>'.$resultado_fila['nombre_usu'] .'</td>
    <td>'.$resultado_fila['nombre_emp'] .'</td>
    <td>'.$resultado_fila['telefono'] . '</td>
    <td>'.$resultado_fila['correo'] . '</td>
    </tr>
';
};
$html.='</table>';
//Estas Lineas son Importantes porque son las que generan el PDF
    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $dompdf->stream("LISTADO_CLIENTES.pdf", array('Attachment'=>'0'));
?> 

Conclusion: DomPDF mescla PHP con HTML sin usar funciones complicadas... y usando html puedes generar el diseño que quieras, este ejemplo esta hecho con php4 las nuevas versiones de dompdf soportan html5 css3 y php5, tienes que tener cuidado con el uso del html y el del css te recomiendo usar funciones simples lo mas que puedas. Ya que te pueden generar errores por usar script muy elaborados. si tienes mas dudas comentanos..

Respuesta
-1

La clase fpd me parece indica para lo que necesitas, es relativamente fácil de usar

He aquí un ejemplo completo funcionado.

¿

¿

<?php
require('fpdf/fpdf.php');
require_once('Connections/tuconexion.php');
include('includes/funciones.php');
//header ('Content-type: application/pdf; charset=utf-8');
class PDF extends FPDF
{
var $widths;
var $aligns;

function SetWidths($w)
{
//Set the array of column widths
$this->widths=$w;
}

function SetAligns($a)
{
//Set the array of column alignments
$this->aligns=$a;
}

function Row($data)
{
//Calculate the height of the row
$nb=0;
for($i=0;$i<count($data);$i++)
$nb=max($nb,$this->NbLines($this->widths[$i],$data[$i]));
$h=5*$nb;
//Issue a page break first if needed
$this->CheckPageBreak($h);
//Draw the cells of the row
for($i=0;$i<count($data);$i++)
{
$w=$this->widths[$i];
$a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'C';
//Save the current position
$x=$this->GetX();
$y=$this->GetY();
//Draw the border
$this->Rect($x,$y,$w,$h);

$this->MultiCell($w,5,$data[$i],0,$a,'true');
//Put the position to the right of the cell
$this->SetXY($x+$w,$y);
}
//Go to the next line
$this->Ln($h);
}

function CheckPageBreak($h)
{
//If the height h would cause an overflow, add a new page immediately
if($this->GetY()+$h>$this->PageBreakTrigger)
$this->AddPage($this->CurOrientation);
}

function NbLines($w,$txt)
{
//Computes the number of lines a MultiCell of width w will take
$cw=&$this->CurrentFont['cw'];
if($w==0)
$w=$this->w-$this->rMargin-$this->x;
$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
$s=str_replace("\r",'',$txt);
$nb=strlen($s);
if($nb>0 and $s[$nb-1]=="\n")
$nb--;
$sep=-1;
$i=0;
$j=0;
$l=0;
$nl=1;
while($i<$nb)
{
$c=$s[$i];
if($c=="\n")
{
$i++;
$sep=-1;
$j=$i;
$l=0;
$nl++;
continue;
}
if($c==' ')
$sep=$i;
$l+=$cw[$c];
if($l>$wmax)
{
if($sep==-1)
{
if($i==$j)
$i++;
}
else
$i=$sep+1;
$sep=-1;
$j=$i;
$l=0;
$nl++;
}
else
$i++;
}
return $nl;
}

function Header()
{

$this->SetFont('Arial','B',10);
$this->Ln();
$this->Ln(15);
}

function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial','B',7,'C');
$this->Image('logo.jpg' , 25 ,230, 160 , 30,'JPG');

}

}
$paciente= $_GET["id"];
//$con = new DB;
//$pacientes = $con->coctar();
$paciente_reporte = "0";
if (isset($_GET["id"])) {
$paciente_reporte = (get_magic_quotes_gpc()) ? $_GET["id"] : addslashes($_GET["id"]);
}
mysql_select_db($database_procalid, $procalid);
$query_reporte = sprintf("SELECT  * from tutabla);
$reporte = mysql_query($query_reporte, $tuconexion) or die(mysql_error());
$row_reporte = mysql_fetch_assoc($reporte);
$totalRows_reporte = mysql_num_rows($reporte);

$pacientes = mysql_query($query_reporte);
$fila = mysql_fetch_array($pacientes);
$pdf=new PDF('P','mm','Letter');
$pdf->Open();
$pdf->AddPage();
$pdf->SetAutoPageBreak(true, 20);
$pdf->SetMargins(20,22,10);
$pdf->Ln(20);
$pdf->Line(20,46,195,46);//impresión de linea
$pdf->Ln(3);
$pdf->Ln(22);
//$pdf->SetAligns('C');
$fecha = $fila['Fecha'];
$ano = substr($fecha, -10, 4);
$mes = substr($fecha, -5, 2);
$dia = substr($fecha, -2, 2);
$pdf->SetWidths(array(60, 65, 20, 15,15));
$pdf->SetFont('Arial','B',7,'R');
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetLineWidth(.5);
$pdf->Row(array('REGISTRO No.', 'CIUDAD', 'DIA', 'MES',utf8_decode('AÑO')));
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetFont('Arial','','','C');
$pdf->SetLineWidth(.5);
$pdf->Row(array($fila ['RegistroNo'], fn_MostrarNombredepartamento ($fila['idCiudad']),$dia,$mes,$ano));
$pdf->SetFont('Arial','u',7);
//$pdf->Cell(0,6,'Ciudad: '.fn_MostrarNombredepartamento($fila['idCiudad']),0,1); //.' '.$fila['apellido_paterno'].' '.$fila['apellido_materno'],0,1);
$pdf->Cell(0,6,'LABORATORIO:LABORATORIO DE ANALISIS DE 
$pdf->Ln(0);
$pdf->SetWidths(array(100));
$pdf->SetFont('Arial','B',9);
$pdf->SetFillColor(0,0,47);
$pdf->SetTextColor(255);

$pdf->Ln(2);
$pdf->SetWidths(array(170));
$pdf->SetFont('Arial','B',9);
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetFont('Arial','',8);
$pdf->SetLineWidth(.5);
$pdf->Cell(175,6,'Descripcion de la Muestra:'.$fila['DescriMuestra'],1,1);

$pdf->Ln(5);
$pdf->SetWidths(array(50, 15, 20, 30,35,25));
$pdf->SetFont('Arial','B',7);
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
//$pdf->SetAligns('C');
$pdf->SetLineWidth(.5);
$pdf->Row(array('FECHA MUESTREO', 'HORA', 'LOTE NO.', 'FECHA DE VTO.','AREA', utf8_decode('T° C')));
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetFont('Arial','',7);
$pdf->Row(array($fila ['FechaMuestreo'], $fila['Hora'], $fila['LoteNo'], $fila['FechaVTO'], $fila['Area'], $fila['TemCenti']));
$pdf->Ln(3);
$pdf->SetWidths(array(50, 40, 40,20,25));
$pdf->SetFont('Arial','B',7);
//$pdf->SetAligns('C');
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetLineWidth(.5);
$pdf->Row(array( 'PROVEEDOR', 'MANIPULADOR', 'EMPAQUE','PESO', utf8_decode('T°LLEGADA')));
$pdf->SetFillColor(255,255,255);
$pdf->SetFont('Arial','',7);
$pdf->SetTextColor(0);
$pdf->Row(array( $fila['Proveedor'], $fila['Manipulador'], $fila['Empaque'], $fila['Peso'], $fila['TemLlegada']));
$pdf->Ln(3);
$pdf->SetWidths(array(50, 30, 30, 65));
$pdf->SetFont('Arial','B',7);
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetLineWidth(.5);
$pdf->Row(array('ASPECTO', 'OLOR', 'PH', 'FECHA ANALISIS'));
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetFont('Arial','',7);
$pdf->Row(array($fila ['Aspecto'], $fila['Olor'], $fila['Ph'], $fila['FechaAnalisis']));
$pdf->Ln(2);
$pdf->Cell(175,6,'OBSERVACIONES:'.$fila['Observaciones'],1,1);
$pdf->Ln(3);
$pdf->SetWidths(array(50,25, 25, 40,25,10));
$pdf->SetFont('Arial','B',7,'C');
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetLineWidth(.5);
//$pdf->SetAligns('C');
for($i=0;$i<1;$i++)
{
$pdf->Row(array('ANALISIS MICROBIOLOGICO', 'METODO', 'UNIDAD', 'LIMITE MAX PERMITIDO','RESULTADO','OK'));
}
//$historial = $con->conectar();
$paciente_Recordset1 = "0";
if (isset($_GET["id"])) {
$paciente_Recordset1 = (get_magic_quotes_gpc()) ? $_GET["id"] : addslashes($_GET["id"]);
}
mysql_select_db($database_procalid, $procalid);
$query_Recordset1 = sprintf("SELECT tuconsulta ", $paciente_Recordset1);
$Recordset1 = mysql_query($query_Recordset1, $tuconexion) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
$historial1 = mysql_query($query_Recordset1);
$numfilas1 = mysql_num_rows($historial1);
for ($i=0; $i<$numfilas1; $i++)
{
$fila1 = mysql_fetch_array($historial1);
$pdf->SetFont('Arial','',8);
//empieza
$directorioPadre = 'images/';
$ext='.jpg';
//termina
$pdf->SetFillColor(255,255,255);
$pdf->SetTextColor(0);
$pdf->SetFont('Arial','',6);
//$correcto =$pdf->Image($directorioPadre.$fila1['correcto'].$ext,$pdf->GetX() ,$pdf->GetX());
//$pdf->Image($directorioPadre.$fila1['correcto'].$ext ,$pdf->getX(),$pdf->getY(),'R','10')
$pdf->Row(array($fila1 ['NombreAnalisis'], $fila1['Metodo_'], $fila1['Unidad_'], $fila1['LimiteMaxPermitido_'],$fila1['resultado'],fn_correcto($fila1 ['correcto'])));
}
$pdf->Ln(2);
$pdf->SetFont('Arial','',7);
$pdf->SetLineWidth(.2);

$pdf->SetFont('Arial','',7);
$pdf->Cell(175,6,'CONCLUSIONES:'.$fila['Concluciones'],1,1);
$pdf->Cell(175,6,'CONVENSIONES:',0,1);
$pdf->SetFont('Arial','B',7);
$pdf->Cell(42,6,'NA:No Aplica',0,0,'C');
$pdf->Cell(42,6,'SN:Sin Norma',0,0,'C');
$pdf->Cell(42,6,'NI:Norma Interna',0,0,'C');
$pdf->Cell(42,6,'NR:No Registra',0,0,'C');
//$pdf->Output('reporte2.pdf','d');salida a descargar en equipo
$pdf->Output('');
?>

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas