How can I use TCPDF to create 2x6 label sheets that include 2D barcodes WITHOUT using columns or third party classes?

For three weeks (I think I'm slowing down so much!) I tried to use my own TCPDF examples as well as some suggestions found on this site to figure out how to do it using database records. Mr. Asuni has responded to some of the requests for help when others ask how to use third party patches (classes) to keep things fine, only so that it can be done in TCPDF without such classes. For some reason (perhaps my own misunderstanding), I was unable to use TCPDF to print labels using its columns approach.

I also didn't want to ditch TCPDF in favor of other possible solutions (reasons why I won't go into it). PHP TCPDF Export for Standard Address Labels is an example of a asked or asked question where the required functionality was obtained by switching to fpdf17.

So, I stayed until today, even trying some great code written in French, but I couldn't convince him to create the structure I need.

Since questions like the one I quoted above were so hard "bumps" (on this site and elsewhere) with no seeming resolution, I decided to read everything I could work on the code until I was discouraged and tested, retest and check some more.

I finally found a way to make a PDF from a database that would make PDFs containing pages of 6 labels (two, three at the bottom) in AVERY 5164 format. And I was able to do this without using the TCPDF columns approach OR any third party patches or classes.

Almost everyone should be able to change their mind to suit their needs if they pay close attention to the values โ€‹โ€‹of the variables in my code.

I POSITIVE there should be a more elegant (and correct!) Way to get the results that I did, so I am VERY open to suggestions on how my code could be improved.

And, before I get burned, yes, I KNOW that the database call must be PDO. I am stuck with my client giving me access.

Finally, just to give an idea of โ€‹โ€‹how long it took to create different PDFs of varying number of records: 12 records (2 pages) โ†’ 4 seconds to activate the download of 200 records โ†’ 44 seconds the file sizes were reasonable (I was unable to record any, although .... sorry!)

Here's my solution [NOTE: My db connection file is not included below for obvious reasons]:

// value from url calling this page - this client wants results by year every time
$colname_year = "-1";
if (isset($_GET['year'])) {
  $colname_year = $_GET['year'];
}
//I DO include Mr. Asuni credits in my file, but it left out here for brevity sake.
//----------------
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 document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('whoever you are');
$pdf->SetTitle('what you want to call it');
$pdf->SetSubject('your subject');
$pdf->SetKeywords('TCPDF, PDF, HHMWC, QR, CODE');
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
// 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
require_once('../../tcpdf/results/lang/eng.php');
$pdf->setLanguageArray($l);
// --------------
// add a page
$pdf->AddPage();
// set the font
$pdf->SetFont('helvetica', '', 10);
// set style for barcode
$style = array(
    'border' => 2,
    'vpadding' => 'auto',
    'hpadding' => 'auto',
    'fgcolor' => array(0,0,0),
    'bgcolor' => false, //array(255,255,255)
    'module_width' => 1, // width of a single module in points
    'module_height' => 1 // height of a single module in points
);
// connect to database
require_once('../../../Connections/con1.php');
mysql_select_db($database_con1, $con1); // Get needed records from database
$query_info = sprintf("select regkey, name1, name2, company, city, state, volunteer, meal, choice, golf from convregis where (name1<>'Anonymous Donation' and print='0' and completed='Yes' and hold='0' and year=%s) order by name2, name1 ASC", GetSQLValueString($colname_year, "text"));
$info = mysql_query($query_info, $con1) or die(mysql_error());
$num_fields = mysql_num_fields($info);
$j=0; // the field number
$x=1; // the record number
while($row = mysql_fetch_array($info)) { 
  for($j=0; $j<$num_fields; $j++) {
     $name = mysql_field_name($info, $j);
     $object[$x][$name] = $row[$name];
  }
  $x++; // get next record set
}
//set variables for placement of QR CODE and text lines
$size=40; // mm size of QRCODE / H = QR-CODE Best error correction
$qrlm=40; // left margin of code on left
$qrlm2=140; // left margin of code on right
$qrvm=40; // vertical placement (how far down the page) of BOTH codes on first row
$l=20; // left margin of text, left side
$l2=120; // left margin of text, right side
$y=15; // vertical placement (how far down the page) of BOTH texts on first row
// There will be two records per row - there will be three rows
$ii = count($object); // total number of record rows to do
for($i=1; $i<=$ii; $i++) {    //$object[$i]['field_name'] / this sets $i = $x above
    if ($i<=$ii) {
        $codeurl = "https:clientwebsiteaddress/attend.php?regkey=".$object[$i]['regkey'];
        ///write the QR CODE
        $pdf->write2DBarcode($codeurl, 'QRCODE,H', $qrlm, $qrvm, $size, $size, $style, 'N');
        // the QR CODE, when scanned by a smartphone at the convention's
        //registration packet pickup table, triggers an update to the
        //database in the attend.php page, setting a registrant to "in attendance" 
        $regkey=$object[$i]['regkey']; //assign row data to a variable and manipulate as needed
        $fullname=strtoupper($object[$i]['name2']).", ".strtoupper($object[$i]['name1']);
        $vol=$object[$i]['volunteer'];
        $company=strtoupper($object[$i]['company']);
        $city=$object[$i]['city'];
        $state=$object[$i]['state'];
         $meal=$object[$i]['meal'];
         $golf=$object[$i]['golf'];
         if ($golf<>"1") {
             $golf=" ";
             } else {
             $golf="GOLF";
         }
         if ($meal<>"1") {
             $meal=" ";
            } else {
            $meal="MEAL: ".strtoupper($object[$i]['choice']);
        }
        if ($meal<>" ") {
            $mealgolf=$meal."        /       ".$golf;
            } else {
            $mealgolf=$golf;
        }
        //write the lines of text
        $pdf->Text($l, $y, $fullname.'               '.$vol);
        $pdf->Text($l, $y+5, $regkey.'               '.$city.', '.$state);
        $pdf->Text($l, $y+10, $company);
        $pdf->Text($l, $y+15, $mealgolf);
        $i++; // get next record
        if ($i<=$ii) {
            $codeurl2 = "https:clientwebsiteaddress/attend.php?regkey=".$object[$i]['regkey'];
            $pdf->write2DBarcode($codeurl2, 'QRCODE,H', $qrlm2, $qrvm, $size, $size, $style, 'N');
            $regkey2=$object[$i]['regkey'];
            $fullname2=strtoupper($object[$i]['name2']).", ".strtoupper($object[$i]['name1']);
            $vol2=$object[$i]['volunteer'];
            $company2=strtoupper($object[$i]['company']);
            $city2=$object[$i]['city'];
             $state2=$object[$i]['state'];
            $meal2=$object[$i]['meal'];
            $golf2=$object[$i]['golf'];
            if ($golf2<>"1") {
                    $golf2=" ";
                    } else {
                    $golf2="GOLF";
            }
            if ($meal2<>"1") {
                $meal2=" ";
                } else {
                $meal2="MEAL: ".strtoupper($object[$i]['choice']);
            }
            if ($meal2<>" ") {
                $mealgolf2=$meal2."        /       ".$golf2;
                } else {
                $mealgolf2=$golf2;
            }
            $pdf->Text($l2, $y, $fullname2.'               '.$vol2);
            $pdf->Text($l2, $y+5, $regkey2.'               '.$city2.', '.$state2);
            $pdf->Text($l2, $y+10, $company2);
            $pdf->Text($l2, $y+15, $mealgolf2);
            $qrvm=$qrvm+85; $y=$y+85; // add 85 mm drop to vertical alignment of qrcodes
            if($i<=$ii and $qrvm>210) {  //no more room on this page but more records to do
                $qrvm=40; // reset qrcode vertical alignment
                $y=15; // reset where texts write
                $pdf->AddPage();
            }
        }
    }
} // end of PDF (no more records to do)
$pdf->Output($year.'EnvelopeLabels.pdf', 'I'); //Close and output PDF document
?>

      

I hope I didn't break anything by modifying the code a bit to remove sensitive information. Thanks for the great site - I've learned a lot and hope I helped someone in return!

+3


source to share


1 answer


Take a look at my solution - it can print 24 labels - 3 * 8 in A4 size. just do a simple change in width, height and $ qty and u can get 2 * 6.



<?php

include("dbconfig.php");

require_once('../tcpdf/tcpdf.php');
// include 1D barcode class (search for installation path)
require_once('../tcpdf/tcpdf_barcodes_1d.php');

date_default_timezone_set('Asia/Kolkata');


// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, 'mm', 'A4', true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Casual Creators');
$pdf->SetTitle('Bar Code Labels');
$pdf->SetSubject('');
$pdf->SetKeywords('');

//remove header and footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->setTopMargin(13.0);
$pdf->SetRightMargin(6.0);

$pdf->setHeaderMargin(13);
$pdf->SetFooterMargin(13.0); //13mm

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, 13.0);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);



// set a barcode on the page footer
//$pdf->setBarcode(date('Y-m-d H:i:s'));

// set font
$pdf->SetFont('helvetica', '', 11);

// add a page
$pdf->AddPage();

// print a message
//$txt = "";
//$pdf->MultiCell(70, 50, $txt, 0, 'J', false, 1, 125, 30, true, 0, false, true, 0, 'T', false);
//$pdf->SetY(30);

// -----------------------------------------------------------------------------

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

// define barcode style
$style = array(
        'position' => '',
        'align' => 'L',
        'stretch' => false,
        'fitwidth' => false,
        'cellfitalign' => '',
        'border' => false,
        'hpadding' => 'auto',
        'vpadding' => 'auto',
        'fgcolor' => array(0,0,0),
        'bgcolor' => false, //array(255,255,255),
        'text' => true,
        'font' => 'helvetica',
        'fontsize' => 8,
        'stretchtext' => 0
);


//63.5 mm label width
//33.9mm label height
//2.5 mm gap between

// PRINT VARIOUS 1D BARCODES

// CODE 39 - ANSI MH10.8M-1983 - USD-3 - 3 of 9.


$query1 = "SELECT * FROM PRODUCTS WHERE ID = '123456' ";

$result1 = $conn->query($query1);
$qty = 24;
$item ;

if ($result1-> num_rows > 0)  {

    $row = $result1 -> fetch_assoc();

    $item = $row["id"];
}
else {
    echo 'DbFailed';
}

$counter = 1;

$i = '0' ;

for( ; $i < $qty ; $i++)
{

    $x = $pdf->GetX();
    $y = $pdf->GetY();
    $pdf->setCellMargins(0,0,2.5,0);
    // The width is set to the the same as the cell containing the name.
    // The Y position is also adjusted slightly.
    $pdf->write1DBarcode($item , 'C39', $x-2.5, $y-6.5, 63.5, 18, 0.4, $style, 'L');
    //Reset X,Y so wrapping cell wraps around the barcode cell.
    $pdf->SetXY($x,$y);
    $pdf->Cell(63.5, 25, 'MyProduct', 0, 0, 'L', FALSE, '', 0, FALSE, 'C', 'B');
    $pdf->SetXY($x,$y);
    $pdf->Cell(63.5, 33, 'Price', 0, 0, 'L', FALSE, '', 0, FALSE, 'C', 'B');

    if($counter == 3)
    {
        $pdf->Ln(33.9);
        $counter = 1;
    }else{
        $counter++;
    }

}




// ---------------------------------------------------------
ob_end_clean();
//Close and output PDF document
$pdf->Output('barcodes.pdf', 'I');

?>

      

+1


source







All Articles