【问题标题】:How can I use TCPDF to make 2x6 sheets of labels that include 2D barcodes WITHOUT using columns OR 3rd-party classes?如何在不使用列或 3rd-party 类的情况下使用 TCPDF 制作包含 2D 条形码的 2x6 标签?
【发布时间】:2015-06-25 01:58:35
【问题描述】:

三周以来(我想我的速度太慢了!)我尝试使用 TCPDF 自己的示例以及在此站点上找到的一些建议来弄清楚如何使用数据库记录来做到这一点。当其他人询问如何使用 3rd 方补丁(类)来使事情顺利进行时,Asuni 先生已经回应了一些帮助请求,只是它可以在没有这些类的情况下在 TCPDF 中完成。无论出于何种原因(也许是我自己的误解),我都无法使用他的列方法使用 TCPDF 打印标签。

我也不愿意放弃 TCPDF 转而采用其他可能的解决方案(原因我不会详述)。 PHP TCPDF Export for Standard Address Labels 是通过切换到 fpdf17 获得所需功能时此处提出/解决的问题的示例。

所以我一直坚持到今天,甚至尝试了一些用法语编写的精彩代码,但我无法说服它创建我需要的结构。

因为像我上面提到的问题已经被“命中”了很多次(在这个网站和其他地方),但似乎没有解决方案,我决定尽我所能阅读,工作代码直到我睡眼惺忪,然后测试,重新测试并测试更多。

我终于找到了一种从数据库制作 PDF 的方法,该方法可以制作包含 AVERY 5164 格式的 6 个标签页(跨 2 个,向下 3 个)的 PDF。而且我能够在不使用 TCPDF 的列方法或任何 3rd-party 补丁或类的情况下做到这一点。

如果密切关注我代码中变量的含义,几乎任何人都应该能够根据自己的需要更改我的解决方案。

我很肯定,必须有一种更优雅(更正确!)的方法来获得我所做的结果,所以我非常愿意接受有关如何改进我的代码的建议。

而且,在我被烧死之前,是的,我知道数据库调用需要是 PDO。我对客户允许我访问的内容感到困惑。

最后,只是为了说明生成不同数量记录的各种 PDF 需要多长时间: 12条记录(2页)--> 4秒下载激活 200 条记录 --> 44 秒 文件大小是合理的(不过我没有写下来……抱歉!)

这是我的解决方案 [注意:我的 db 连接文件是一个包含在下面没有给出的明显原因]:

// 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's credits in my file, but it's left out here for brevity's 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
?>

我希望我没有通过稍微更改代码以删除敏感信息来破坏任何内容。 感谢您提供了一个很棒的网站 - 我学到了很多东西,希望现在能帮助别人!

【问题讨论】:

    标签: php mysql tcpdf labels


    【解决方案1】:

    看看我的解决方案 - 它可以打印 24 个标签 - 3*8 到 A4 中。 只需对 width 、 height 和 $qty 进行简单的更改,就可以得到 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's 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');
    
    ?>
    

    【讨论】:

    • 您的建议可以作为评论,但不能作为答案。请更具体并描述一些细节。谢谢!
    • armam,希望对您有所帮助
    • 对我来说代码不起作用,我不得不在样式代码中注释掉这一行,否则每行只打印一个条形码: // 'position' => '',
    【解决方案2】:

    只要看到这个问题和上面的答案,我认为它只是一个宽度和高度的计算问题。

    以下解决方案可能对几乎一维的 TCPDF 标签打印有用。 该示例适合 4 列并支持分页符,然后根据需要调整参数。

    $pdf->SetMargins(10, 30);
    
    $pdf->AddPage('P', 'A4');
    
    $style_barcode = array(
        'position' => '',
        'align' => 'C',
        'stretch' => false,
        'fitwidth' => true,
        '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' => 4
    );
    
    // Set some content to print
    $counter = 1;
    $label_cols = 4; // No. of Columns
    $label_w = 40; // Label width
    $label_w_base_margin = 10; // Label width base margin
    $label_h = 15; // Label height
    $label_h_base_margin = 10; // Label height base margin - Do not change except you know what you are doing
    $label_h_margin = $label_h - 6.5; // Label height margin - Do not change except you know what you are doing
    
    // print a block of text using Write()
    $txt = "Test";
    $pdf->SetFont('helvetica', '', 10); // cid0jp or msungstdlight can display chinese
    //$style_barcode['position'] = 'L';
    $x = $pdf->GetX();
    $y = $pdf->GetY();
    for ($i=1; $i <= 80; $i++) {
    
        if ($y >= 250) { // Set Page break if GetY >= 250 (may be use Constructor but no time to review class code at all, sorry)
            $pdf->AddPage('P', 'A4'); 
            $y = $pdf->GetY();
        }
        $pdf->write1DBarcode('AABBCCDD'.$i, 'C39', $x, $y, $label_w, $label_h, 0.4, $style_barcode, 'L');
    
        $x = $x + $label_w + $label_w_base_margin;
        if($counter == $label_cols){
            $pdf->Ln($label_h);
            $counter = 1;
            $x = $pdf->GetX();
            $y = $y + $label_h_base_margin + $label_h_margin;
        }else{
            $counter++;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2018-02-09
      相关资源
      最近更新 更多