2012-02-12 107 views
8

Corto

Lo que quiero hacer es preparar resultados generados por PHP para imprimir con reglas estrictas.Trabajar con PDF en PHP

Intenté todas las formas posibles con css + html: establecer las dimensiones en px, mm, cm. Nada ayudó. Cada navegador, incluso cada impresora imprimió resultados de papel absolutamente diferentes (probó ambos con & sin impresión de borde. Tampoco obtuvo el resultado). Después de una larga investigación, descubrió que CSS no es la mejor manera para este fin y mejor manera: utilizar la funcionalidad de creación de PDF con PHP. Entonces, instaló TCPDF. Pero no puedo hacer que funcione con la parte lógica que creé para HTML.

Lo que yo quiero conseguir margen de la parte superior e inferior caras del papel deben ser 11 mm
  • margen entre las filas
    • del Cuadro primera y última fila 0 mm
    • Tabla de las filas deben estar en 4 mm de izquierda y derecha lados del papel
    • 2 mm entre cada altura ancho x 21,2 mm de columna
    • 38 mm cada célula
    • 13 x filas, 5 x columnas, 13x5 = 65 células
    • Cada tabla en página nueva. En otras palabras - después de cada página de la tabla ruptura
    • En cada celda 39 Código de barras (valor debe ser $id)
    • Sólo las tablas en consecuencia PDF - sin cabecera, sin pie de página, sin título, etc ...

    Aquí es una explicación más detallada en la imagen:

    enter image description here

    Lo que estoy recibiendo

    Después del envío del formulario, el procesamiento en el lado php lleva demasiado tiempo, aproximadamente un minuto, y abre una página en blanco en lugar de un resultado en PDF.

    Código:

    (Código no es tan grande, los comentarios están haciendo que parezca tan :)

    <?php 
    require_once('tcpdf/config/lang/eng.php'); 
    require_once('tcpdf/tcpdf.php'); 
    
    // create new PDF document 
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); 
    
    $pdf->SetPrintHeader(false); 
    $pdf->SetPrintFooter(false); 
    // set document information 
    $pdf->SetCreator(PDF_CREATOR); 
    $pdf->SetAuthor('John Smith'); 
    $pdf->SetTitle(false); 
    $pdf->SetSubject(false); 
    $pdf->SetKeywords(false); 
    
    // set default header data.set all false because don't want to output header footer 
    $pdf->SetHeaderData(false, false, false, false); 
    
    // set header and footer fonts 
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); 
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); 
    
    // set default monospaced font 
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); 
    
    //set margins 
    $pdf->SetMargins(4, 11, 4); 
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); 
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); 
    
    //set auto page breaks 
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); 
    
    //set image scale factor 
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 
    
    //set some language-dependent strings 
    $pdf->setLanguageArray($l); 
    
    // --------------------------------------------------------- 
    // set font 
    $pdf->SetFont('helvetica', '', 10); 
    
    // add a page 
    $pdf->AddPage(); 
    
    // define barcode style 
    $style = array(
        'position' => '', 
        'align' => 'C', 
        'stretch' => false, 
        'fitwidth' => true, 
        'cellfitalign' => '', 
        'border' => true, 
        'hpadding' => 'auto', 
        'vpadding' => 'auto', 
        'fgcolor' => array(0, 0, 0), 
        'bgcolor' => false, //array(255,255,255), 
        'text' => true, 
        'font' => 'helvetica', 
        'fontsize' => 8, 
        'stretchtext' => 4 
    ); 
    
    ob_start(); 
    ?> 
    
    
    
    <style type="text/css"> 
    
        table { 
    
         width: 100%;   
    
         border-collapse: collapse; 
    
        } 
    
        td img { 
         height:10mm; 
        } 
    
        td { 
         padding: 0 1mm 0 1mm; 
         vertical-align:middle;    
        } 
    
        .cell { 
         width: 38mm; 
         height:21mm; 
         font-style: bold; 
         text-align: center; 
        } 
    
        tr { 
         height:21mm; 
         margin:0; 
         padding:0;    
        } 
    
    
    </style> 
    
    <?php 
    
    $i = 0; 
    $item = new item($db); 
    foreach ($_POST['checkbox'] as $id) { 
        $details = $item->getDetails($id); 
        $qt = (isset($_POST['qt'])) ? $_POST['qt'] : $details['qt']; 
        for ($cnt = 1; $cnt <= $qt; $cnt++) { 
         // check if it's the beginning of a new table 
         if ($i % 65 == 0) 
          echo '<table>'; 
    
         // check if it's the beginning of a new row 
         if ($i % 5 == 0) 
          echo '<tr>'; 
    
         echo '<td><div class="cell">www.fety.fr<br/>'; 
         $pdf->Cell(0, 0, 'CODE 39 - ANSI MH10.8M-1983 - USD-3 - 3 of 9', 0, 1); 
         $pdf->write1DBarcode($id, 'C39', '', '', '', 18, 0.4, $style, 'N'); 
         $pdf->Ln(); 
         echo '<br/>' . $details['hcode'] . '</div></td>'; 
    
         // check if it's the end of a row 
         if (($i + 1) % 5 == 0) 
          echo '</tr>'; 
    
         // check if it's the end of a table 
         if (($i + 1) % 65 == 0) 
          echo '</tr></table>'; 
    
         $i++; 
        } 
    } 
    
    // if the last table isn't full, print the remaining cells 
    if ($i % 65 != 0) { 
        for ($j = $i % 65; $j < 65; $j++) { 
         if ($j % 65 == 0) 
          echo '<table>'; 
         if ($j % 5 == 0) 
          echo '<tr>'; 
         echo '<td></td>'; 
         if (($j + 1) % 5 == 0) 
          echo '</tr>'; 
         if (($j + 1) % 65 == 0) 
          echo '</table>'; 
        } 
    } 
    
    $markup = ob_get_clean(); 
    
    // output the HTML content 
    $pdf->writeHTML($markup, true, false, true, false, ''); 
    
    
    
    // reset pointer to the last page 
    $pdf->lastPage(); 
    
    // --------------------------------------------------------- 
    //Close and output PDF document 
    $pdf->Output('bcsheet.pdf', 'I'); 
    ?> 
    

    script funciona así:

    1. El usuario selecciona las casillas de verificación artículos
    2. Después del envío del formulario, PHP obtiene los valores de las casillas marcadas a través de Ajax
    3. En f oreach loop, PHP obtiene cantidades de cada elemento de la base de datos.
    4. tabla generada
    +0

    listo para dar el 100 representante para resolver este problema – heron

    +0

    ¿Ha considerado el uso de crudos PostScript? Es una tarea desafiante, pero tendría un control total sobre su lienzo de representación. También puede encontrar bibliotecas/tutoriales para renderizar códigos de barras. – Tibo

    +0

    @Tibo Necesito dar como resultado el resultado como PDF o como HTML. HTML da diferentes resultados. Así que tengo 1 y único camino - PDF. Entonces, necesito hacer que funcione – heron

    Respuesta

    4

    aquí es un HTML/CSS a la biblioteca de PDF Converter http://www.mpdf1.com/mpdf/

    Esto tiene su propio analizador HTML/CSS y por lo tanto producirá el mismo resultado en todos los navegadores.

    <?php 
    
    $html = ' 
        <html> 
        <head> 
        <style> 
         table { 
         width: 100%; 
          border-collapse: collapse; 
         }  
         tr { 
    
         } 
         td { 
          width: 38mm; 
          height: 21.2mm; 
          margin: 0 1mm; 
          text-align: center; 
          vertical-align:middle; 
         } 
        </style> 
        </head> 
        <body> 
        <table>'; 
    
        for ($i = 0; $i < 13; $i++) 
        { 
         $html .= '<tr>'; 
         for($j = 0; $j < 5; $j++) 
         { 
          $html .= '<td><barcode code="TEC-IT" type="C39" class="barcode" /></td>'; 
         } 
         $html .= '</tr>'; 
        }  
    
    $html .= '</table> 
        </body> 
        </html>'; 
    
        include("MPDF53/mpdf.php"); 
    
        $mpdf = new mPDF('c', 'A4', '', '', 4, 4, 10.7, 10.7, 0, 0); 
    
        $mpdf->SetDisplayMode('fullpage'); 
    
        $mpdf->list_indent_first_level = 0; 
    
        $mpdf->WriteHTML($html,0); 
    
        $mpdf->Output('test.pdf','I'); 
        exit; 
    
    ?> 
    
    +0

    TCPDF también tiene soporte html. Eche un vistazo http://www.tcpdf.org/examples/example_061.phps – heron

    +0

    sí, pero este es más completo (en realidad se basa en fpdf), lo único que podría hacer con él en mi último proyecto fue cambiar la opacidad de un div. – redmoon7777

    +0

    Una cosa más en TCPDF es que admite el código de barras código 39. De todos modos, si tiene experiencia con la salida de PDF, por favor ayude a obtener este trabajo con mpdf o cualquier clase de pdf que prefiera. – heron

    2

    Creo que si usted no está consiguiendo un resultado en absoluto, es probable que están suprimiendo los errores de una manera que puede no les van a dar con su guión. Además, su enfoque con HTML simplemente no es cómo funciona; no puede intercalar las llamadas de célula nativa TCPDF con HTML; no están "generando" marcas. Así que estás mezclando dos formatos diferentes e incompatibles, que van a dos búferes diferentes.

    Sin embargo, el código aún debe generar un PDF.

    Tenga en cuenta la última página, con su contenido generado de marcado.

    Los únicos cambios que hice fue para que sea el que podía funcionar sin acceso a sus datos:

    $i = 0; 
    //$item = new item($db); 
    //foreach ($_POST['checkbox'] as $id) { 
    for ($id = 0; $id < 1; $id++) { 
        //$details = $item->getDetails($id); 
        //$qt = (isset($_POST['qt'])) ? $_POST['qt'] : $details['qt']; 
        $details = array('These are details'); 
        $qt = 50; 
        for ($cnt = 1; $cnt <= $qt; $cnt++) { 
         // check if it's the beginning of a new table 
         if ($i % 65 == 0) 
          echo '<table>'; 
    
         // check if it's the beginning of a new row 
         if ($i % 5 == 0) 
          echo '<tr>'; 
    
         echo '<td><div class="cell">www.fety.fr<br/>'; 
         $pdf->Cell(0, 0, 'CODE 39 - ANSI MH10.8M-1983 - USD-3 - 3 of 9', 0, 1); 
         $pdf->write1DBarcode($id, 'C39', '', '', '', 18, 0.4, $style, 'N'); 
         $pdf->Ln(); 
         echo '<br/>' . $details['hcode'] . '</div></td>'; 
    
         // check if it's the end of a row 
         if (($i + 1) % 5 == 0) 
          echo '</tr>'; 
    
         // check if it's the end of a table 
         if (($i + 1) % 65 == 0) 
          echo '</tr></table>'; 
    
         $i++; 
        } 
    } 
    

    consigo un PDF. No se parece en nada a lo que tienes en la imagen, pero produce un PDF. Veo que su código es de aproximadamente 90% similar a este ejemplo en el sitio TDPDF:

    http://www.tcpdf.org/examples/example_027.phps

    Cuando fui e hice mi propio ejemplo, yo era capaz de conseguir un PDF que generalmente imitaba lo que muestran en la foto. Como verá en el código que figura a continuación, tiene para trabajar con los métodos de células nativas TCPDF para que funcione la generación del código de barras. No es tan dificil; Me llevó unos 30 minutos descubrir cómo producir un pdf.

    Lo único que no pude entender es de dónde viene la línea negra en la parte superior; de alguna manera está asociado con el encabezado, pero no pude encontrar dónde desactivarlo. El código que hay detrás de la segunda PDF:

    <?php 
    
    require_once('tcpdf/config/lang/eng.php'); 
    require_once('tcpdf/tcpdf.php'); 
    
    // create new PDF document 
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); 
    
    //set auto page breaks 
    $pdf->SetAutoPageBreak(TRUE); 
    
    //set image scale factor 
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 
    
    //set some language-dependent strings 
    $pdf->setLanguageArray($l); 
    
    $pdf->SetFont('helvetica', '', 10); 
    
    // define barcode style 
    $style = array(
        'position' => '', 
        'align' => 'L', 
        'stretch' => true, 
        'fitwidth' => false, 
        'cellfitalign' => '', 
        'border' => true, 
        'hpadding' => 'auto', 
        'vpadding' => 'auto', 
        'fgcolor' => array(0,0,0), 
        'bgcolor' => false, //array(255,255,255), 
        'text' => true, 
        'font' => 'helvetica', 
        'fontsize' => 8, 
        'stretchtext' => 4 
    ); 
    
    for ($o = 0; $o < 5; $o++) { 
        $pdf->AddPage(); 
    
        $y = 10; 
    
        for ($i = 0; $i < 13; $i++) { 
         $x = 10; 
    
         for ($p = 0; $p < 5; $p++) { 
          // UPC-E 
          $pdf->write1DBarcode('04210000526', 'UPCE', $x, $y, 37, 20, 0.4, $style); 
    
          $x = $x + 38; 
         } 
    
         $y = $y + 21; 
    
         $pdf->Ln(); 
        } 
    } 
    
    //Close and output PDF document 
    $pdf->Output('example_027.pdf', 'I'); 
    
    ?> 
    
    +0

    Thx muchísimo. Resolví todos los problemas con mpdf. Actualmente estoy probando Si falla, probaré tu método. – heron

    +0

    @Jared Farrish: Tengo el mismo problema con una línea negra que aparece en la parte superior. (¿Cómo lograste arreglar esto? – Connum

    +0

    @Connum - Nunca lo descubrí, simplemente lo puse donde era difícil verlo. –

    0

    Aquí hay un enlace a un PDF que se ve exactamente como su imagen:

    Link to embrasse-moi.com barcode label file

    Y aquí es la función que lo creó. Yo uso tcpdf. Creo 3 líneas de texto, la identificación, la descripción, el precio, que busco de mi sub-id, por lo que tendrá que reemplazar el código. También paso en el desplazamiento de fila/columna para usar con avery5167 para poder usar todas las pegatinas.

    function printProductLabelsAvery5167($product_sub_ids, $quantities, $row_offset, $column_offset, $filename) 
    { 
        // Embrasse-moi.com 
        require_once('../../../3rdParty/tcpdf/config/lang/eng.php'); 
        require_once('../../../3rdParty/tcpdf/tcpdf.php'); 
    
        $pdf_file_name = $filename; 
    
        $subid = array(); 
        $poc_title = array(); 
        $color_price = array(); 
    
        for($i=0;$i<sizeof($product_sub_ids);$i++) 
        { 
         $pos_product_sub_id = $product_sub_ids[$i]; 
         $pos_product_id = getProductIdFromProductSubId($pos_product_sub_id); 
         for($qty=0;$qty<$quantities[$i];$qty++) 
         { 
          $subid[] = getProductSubIDName($pos_product_sub_id); 
          $poc_title[] = substr(getProductTitle($pos_product_id),0,48); 
          $color_price[] = substr(getProductSubIdColorDescription($pos_product_sub_id),0,38) . '  $' . number_format(getProductRetail($pos_product_id),2); 
         } 
        } 
    
        $margin_left = 0; 
        $margin_right = 0; 
        $margin_top = 0; 
        $margin_bottom = 0; 
        $cell_width = 1.75; 
        $cell_height = 0.5; 
        $cell_spacing = 0.3; 
        $columns = 4; 
        $rows = 20; 
        $line_spacing_adjust = 0.015; 
        $barcode_spacing_adjust = 0.1; 
        $barcode_height_adjust = 0.05; 
    
        $title = 'Avery 5167 template'; 
        $subject = 'PO # 123'; 
        $keywords = 'purchase order 123'; 
        $page_orientation = 'P'; 
        $page_format = 'LETTER'; 
        $unit = 'in'; 
    
        // create new PDF document 
        $pdf = new TCPDF($page_orientation, $unit, $page_format, true, 'UTF-8', false); 
        // set document information 
        $pdf->SetCreator(COMPANY_NAME); 
        $pdf->SetAuthor(getUserFullName($_SESSION['pos_user_id'])); 
        $pdf->SetTitle($title); 
        $pdf->SetSubject($subject); 
        $pdf->SetKeywords($keywords); 
        $pdf->setPrintHeader(false); 
        $pdf->setPrintFooter(false); 
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); 
        $pdf->SetMargins($margin_left, $margin_top, $margin_right); 
        $pdf->SetAutoPageBreak(TRUE, $margin_bottom); 
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 
        $pdf->setLanguageArray($l); 
        $preferences = array('PrintScaling' => 'None'); 
        $pdf->setViewerPreferences($preferences); 
        $pdf->SetFont('helvetica', 'R', 5); 
    
        //barcode: 128a? 
        // define barcode style 
        $barcode_style = array(
        'position' => '', 
        'align' => 'C', 
        'stretch' => false, 
        'fitwidth' => false, 
        'cellfitalign' => '', 
        'border' => false, 
        'hpadding' => '0', 
        'vpadding' => '0', 
        'fgcolor' => array(0,0,0), 
        'bgcolor' => false, //array(255,255,255), 
        'text' => false, 
        'font' => 'helvetica', 
        'fontsize' => 4, 
        'stretchtext' => 0 
    ); 
    
    
        // set border width 
        $pdf->SetLineWidth(0.01); 
        $pdf->SetDrawColor(0,0,0); 
        //$pdf->setCellHeightRatio(3); 
        $counter = 0; 
    
        //calculating the pages.... how many labels are to be printed on the sheet... 
        //how many labels are going on the first sheet? 
        $first_page_number_of_spots = ($rows)*($columns-($column_offset-1)) -($row_offset-1); 
        $number_of_labels = sizeof($subid); 
        if($number_of_labels <= $first_page_number_of_spots) 
        { 
         $pages = 1; 
        } 
        else 
        { 
         $lables_on_first_page = $first_page_number_of_spots; 
         $labels_remaining = $number_of_labels -$lables_on_first_page; 
         $number_of_spots_per_page = $rows*$columns; 
         $pages = ceil($labels_remaining/($number_of_spots_per_page)) + 1; 
        } 
        for($page=0;$page<$pages;$page++) 
        { 
         $pdf->AddPage(); 
         for($col=$column_offset-1;$col<$columns;$col++) 
         { 
          for($row=$row_offset-1;$row<$rows;$row++) 
          { 
           if($counter< sizeof($subid)) 
           { 
            //barcodes must be cap 
            $line1 = strtoupper($subid[$counter]); 
            $line2 = $poc_title[$counter]; 
            $line3 = $color_price[$counter]; 
           } 
           else 
           { 
            $line1 = ''; 
            $line2 = ''; 
            $line3 = ''; 
           } 
           $counter++; 
           $x_spot = $cell_spacing + $col*$cell_width + $col*$cell_spacing; 
           $y_spot = $cell_height + $row*$cell_height; 
           $coords = 'X:'.$x_spot . ' Y:' .$y_spot; 
           $border = 0; 
           $border2 = 0; 
           //this is the cell that will allow allignment to sticker checking 
           $pdf->SetXY($x_spot, $y_spot); 
           $pdf->Cell($cell_width, $cell_height, '', $border, 0, 'C', 0, '', 0, false, 'T', 'M'); 
    
           // CODE 128 A 
           $pdf->SetXY($x_spot+$barcode_spacing_adjust, $y_spot); 
           //cell to check the barcode placement 
           $pdf->Cell($cell_width-2*$barcode_spacing_adjust, $cell_height/2, '', $border, 0, 'C', 0, '', 0, false, 'T', 'M'); 
           $pdf->write1DBarcode($line1, 'C128A', $x_spot+$barcode_spacing_adjust, $y_spot+$barcode_height_adjust, $cell_width-2*$barcode_spacing_adjust, $cell_height/2 - $barcode_height_adjust, 0.4, $barcode_style, 'N'); 
    
           //the remaining 3 lines have to fit in 1/2 the sticker size 
           //$y_offset = $cell_height/2; 
           $pdf->SetXY($x_spot, $y_spot - 0*$line_spacing_adjust + 3/6*$cell_height); 
           $pdf->Cell($cell_width, $cell_height/6, $line1, $border2, 0, 'C', 0, '', 0, false, 'T', 'C'); 
           $pdf->SetXY($x_spot, $y_spot - 1*$line_spacing_adjust + 4/6*$cell_height); 
           $pdf->Cell($cell_width, $cell_height/6, $line2, $border2, 0, 'C', 0, '', 0, false, 'T', 'C'); 
           $pdf->SetXY($x_spot, $y_spot -2*$line_spacing_adjust + 5/6*$cell_height); 
           $pdf->Cell($cell_width, $cell_height/6, $line3, $border2, 0, 'C', 0, '', 0, false, 'T', 'C'); 
    
    
           //$pdf->writeHTMLCell($cell_width, $cell_height, $x_spot, $y_spot, $text_for_label, 1, 1, false, true, '', false); 
           // no work $pdf->MultiCell($cell_width, $cell_height, $text_for_label, 1, 'J', false, '','',true, 0, false, true, $cell_height, 'T', false); 
          } 
          $row_offset = 1; 
         } 
         $column_offset = 1; 
        } 
        //Close and output PDF document 
        $pdf->Output($pdf_file_name, 'D'); 
    
        //============================================================+ 
        // END OF FILE 
        //============================================================+ 
        }