Fpdf and PDF_LABEL - php

I am trying to set up a labeling printing system in PHP and on each label I would like to add a logo on top of it and I can't manage to work it, because on fpdf images are treated as a cell it doesn't work
EDIT:
The code is as follows:
for($i=1;$i<=$nolabels;$i++) {
$text = sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s%s%s", "", "","","", "$destination", "$label", "USE BY: $date", "$i", '/', "$nolabels");
$pdf->Add_Label($text);}
for($i=1;$i<=$nolabels2;$i++) {
$text = sprintf("%s\n%s\n%s\n%s%s%s", "$destination", "$label2", "USE BY: $date", "$i", '/', "$nolabels2");
$pdf->Add_Label($text);

You can make additional "addHeader" and call it on each page. Here is one example with using X and Y coordinates
public function addHeader($pdf, $addPageNum)
{
// Header
if ($addPageNum) {
$pdf->SetFont('Arial', '', 10);
$pdf->SetTextColor(168, 168, 168);
$pdf->SetXY(20, 265);
$pdf->Cell(0, 5, __('Page') . ' ' . $pdf->PageNo() . ' von ' . '{nb}', 0, 1, 'C', 0);
}
// Footer photo
$pdf->Image(ROOT . '/webroot/img/companyLogo.png', 0, 270, 210);
}

Related

Replace String with Text

I have a website made by previous developed( Now he is not available ).
I have to access to CMS, payment backend everything, But old developer didnt left any records of database.
I am trying to rename or replace some of the text(company details) in receipt, but I dont know what am i doing wrong.
If I had an access to DB , it would be ease like butter.
Here is what I want to do :
You can see that I tried to include direct text "www.transit.com" , but it didnt show up on receipt .
Instead it showed blank.
I know its pointing to DB name like 'shop_name' and so on. But since I dont have any details on DB , I cant change it from DB.
function setShopData() {
// ショップ情報
$objDb = new SC_Helper_DB_Ex();
$arrInfo = $objDb->sfGetBasisData();
// ショップ名
$this->lfText(125, 60, $arrInfo['shop_name'], 8, 'B');
// URL
$this->lfText(125, 63, $arrInfo['www.transit.com'], 8);
// 会社名
$this->lfText(125, 68, $arrInfo['law_company'], 8);
// 郵便番号
$text = '〒 ' . $arrInfo['law_zip01'] . ' - ' . $arrInfo['law_zip02'];
$this->lfText(125, 71, $text, 8);
// 都道府県+所在地
$text = $this->arrPref[$arrInfo['law_pref']] . $arrInfo['law_addr01'];
$this->lfText(125, 74, $text, 8);
$this->lfText(125, 77, $arrInfo['law_addr02'], 8);
$text = 'TEL: '.$arrInfo['law_tel01'].'-'.$arrInfo['law_tel02'].'-'.$arrInfo['law_tel03'];
//FAX番号が存在する場合、表示する
if (strlen($arrInfo['law_fax01']) > 0) {
$text .= ' FAX: '.$arrInfo['law_fax01'].'-'.$arrInfo['law_fax02'].'-'.$arrInfo['law_fax03'];
}
$this->lfText(125, 80, $text, 8); //TEL・FAX
if (strlen($arrInfo['media-support.transit-grp.com']) > 0) {
$text = 'Email: '.'media-support.transit-grp.com';
$this->lfText(125, 83, $text, 8); //Email
}
So is there anyway I can replace these code, so that it would reflect on receipt?
Thank you
Try:
$this->lfText(125, 63, 'www.transit.com', 8);
You were referring to your array, but it didn't contain that key, you simply wanted to use a hardcoded string instead.
For the email (for instance) do:
$text = 'Email: mycompany#gmail.com';
$this->lfText(125, 83, $text, 8);
I suppose the best option is to replace the value in the array, that way any other places where this name is used will also be replaced.
function setShopData() {
// ショップ情報
// Here is the change:
$arrInfo['shop_name'] = "something else";
$objDb = new SC_Helper_DB_Ex();
$arrInfo = $objDb->sfGetBasisData();
// ショップ名
$this->lfText(125, 60, $arrInfo['shop_name'], 8, 'B');
// URL
$this->lfText(125, 63, $arrInfo['www.transit.com'], 8);
// 会社名
$this->lfText(125, 68, $arrInfo['law_company'], 8);
// 郵便番号
$text = '〒 ' . $arrInfo['law_zip01'] . ' - ' . $arrInfo['law_zip02'];
$this->lfText(125, 71, $text, 8);
// 都道府県+所在地
$text = $this->arrPref[$arrInfo['law_pref']] . $arrInfo['law_addr01'];
$this->lfText(125, 74, $text, 8);
$this->lfText(125, 77, $arrInfo['law_addr02'], 8);
$text = 'TEL: '.$arrInfo['law_tel01'].'-'.$arrInfo['law_tel02'].'-'.$arrInfo['law_tel03'];
//FAX番号が存在する場合、表示する
if (strlen($arrInfo['law_fax01']) > 0) {
$text .= ' FAX: '.$arrInfo['law_fax01'].'-'.$arrInfo['law_fax02'].'-'.$arrInfo['law_fax03'];
}
$this->lfText(125, 80, $text, 8); //TEL・FAX
if (strlen($arrInfo['law_email']) > 0) {
$text = 'Email: '.$arrInfo['law_email'];
$this->lfText(125, 83, $text, 8); //Email
}
One thing that I find odd is function setShopData() { that is usually function setShopData($arrInfo) {.
Since that is missing I assume the array is global and is set somewhere else.
At some point in the code there is a line like:
$arrInfo['shop_name'] =<database value>
If you place the line above in the code just below this any changes in the rest of the code will have the new shopname everywhere, not just on the receipt.

TCPDF: Severe formatting bug with writeHtml

Look at this code:
$pdf->Ln(4);
$pdf->SetFont('helvetica', '', 14);
$pdf->SetFillColor(200, 220, 255);
$pdf->Cell(180, 6, 'Education', 0, 1, '', 1);
$pdf->Ln(4);
$pdf->SetFont('helvetica', '', 10);
$html = '
Degree ...................... <strong>' . $education->degree_title . '</strong>
<br/>
Graduation Date ............. ' . date('m-d-Y', strtotime($education->award_date)) . '
<br/>
Attendance .................. ' . date('m-d-Y', strtotime($education->school_start_date)) . ' - ' . date('m-d-Y', strtotime($education->school_end_date)) . '
<br/>';
$pdf->writeHTML($html, true, false, true, false, '');
Because it's running when the setting is:
$pdf->setCellMargins(30, 0, 0, 0);
The end result is:
As you can see, the html <strong> causes the part of the HTML that is to be bolded, to be influenced by the "30" value in the setCellMargins. IF you don't use <strong> or any other HTML element for that matter the formatting is fine.
Is there any way around this bug? I don't want to stop using the left cell margin, and i certainly don't want to discontinue using bold in my PDF.

tcpdf center text not fully in center

I am trying to center the footer text
function Footer(){
$txt = 'Page %s of %s';
if (empty($this->pagegroups)) {
$txt = sprintf($txt, $this->getAliasNumPage(), $this->getAliasNbPages());
} else {
$txt = sprintf($txt, $this->getPageNumGroupAlias(), $this->getPageGroupAlias());
}
$this->MultiCell(0, 0, $txt, 1, 'C', false, 1, PDF_MARGIN_LEFT, $this->y);
}
As you can see in the image the cell is getting positioned correctly, the problem is with centering the text.
I get the same result if I change the MultiCell to something more straight forward:
$this->SetXY(PDF_MARGIN_LEFT, $this->y);
$this->Cell(0, 0, $txt, 1, 1, 'C');
Somehow getAliasNumPage() and getPageNumGroupAlias() add a bunch of whitespace to the right. I am unsure why. But I know that using PageNo() and getGroupPageNo() instead will fix it.
This is the code that worked for me:
public function Footer() {
$this->SetY(-15); //not present in your code but was necessary for me to have the footer be positioned correctly
$txt = 'Page %s of %s';
if (empty($this->pagegroups)) {
$txt = sprintf($txt, $this->PageNo(), $this->getAliasNbPages());
} else {
$txt = sprintf($txt, $this->getGroupPageNo(), $this->getPageGroupAlias());
}
$this->MultiCell(0, 0, $txt, 1, 'C', false, 1);
}
}

How to handle returning PDF file to be able to display in browser

I have ExtJS application that is querying database and showing the results in grid which is working properly.
Users can select any record from the grid by checkbox then send to server to print out. The server side code generate PDF file ( by TCPDF ) and return result the browser, it also works properly.
My problem is, client side doesn't show PDF file in browser window, instead of view just showing binary form of the PDF page.
So, could you please help me, how can I handle returning PDF file to show client screen?
CLIENT SIDE
{
xtype: 'button',
width: 90,
text: 'GÖNDER',
cls: 'x-btn-gonder',
handler: function(){
var ppt = Ext.getCmp('labelType').getValue();
var sb = Ext.getCmp('basic-statusbar');
var count = Ext.getCmp('labelGrids').getSelectionModel().getCount();
var rows = Ext.getCmp('labelGrids').getSelectionModel().getSelection();
if(ppt == null) {
dialog.show();
} else {
if(count > 0) {
var paper = {};
paper.PAPER = ppt;
var prints = new Array();
for (var i = 0; i < count; i++)
{
prints[i] = {'LABEL_ID': rows[i].data.LABEL_ID, 'LABEL_TYPE':rows[i].data.LABEL_TYPE}
}
paper.LABELS = prints;
Ext.Ajax.request({
url: 'lib/labels/print_label.php',
timeout: 60000,
success: function()
{
Ext.Msg.alert('İşlem Başarılı', 'Etiketler yazıcıya gönderildi.');
// set statusbar text after print
sb.setStatus({
text: 'Etiketler yazıcıya gönderildi..!',
iconCls: 'x-status-saved',
clear: true
});
// remove checked items
Ext.select('.x-grid-row-selected').each(function (element) {
Ext.getCmp('labelGrids').getSelectionModel().deselectAll();
});
},
failure: function() { Ext.Msg.alert('Yazdırma Hatası', 'Etiketler yazdırılamadı..!')},
jsonData: Ext.JSON.encode(paper)
});
// clear combobox selected value after send to printer
Ext.getCmp('labelType').reset();
// console.log(Ext.JSON.encode(prints));
} else if(count == 0) {
sb.setStatus({
iconCls: 'x-status-error',
text: 'Lütfen yazdırmak istediğiniz etiketleri seçiniz!'
});
}
winPaper.hide();
}
}
}
SERVER SIDE
<?php
require_once('../tcpdf/config/lang/eng.php');
require_once('../tcpdf/tcpdf.php');
$db = new mysqli("10.10.10.10","blabla","blablabla","label");
$db->query("SET NAMES UTF8");
$db->query("SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");
$db->query("SET lc_time_names = 'tr_TR'");
$datas = json_decode(file_get_contents("php://input"));
// get paper type from json array
$paper = $datas->PAPER;
foreach($datas->LABELS as $data)
{
$lblids[] = $data->LABEL_ID;
}
$ids = implode(",", $lblids);
// get labels from db
$sql = "SELECT LABEL_ID, SUBSYS_ART_NO, ARTICLE_DESC, END_DATE, PRODUCT_PRICE, SHELF_PRICE, LABEL_TEXT, LABEL_TYPE, LABEL_SIGN, PROMO FROM labels WHERE LABEL_ID IN (".$ids.")";
$result = $db->query($sql);
while($row = $result->fetch_assoc())
{
$labels[] = $row;
}
switch($paper)
{
case "SF":
print_shelf($labels);
break;
}
function print_shelf($labels)
{
# defining PDF variables
$width = 100;
$height = 55;
$pageSize = array($width, $height);
# create new BMPL PDF price label
$pdf = new TCPDF('L', PDF_UNIT, $pageSize, true, 'UTF-8', false);
# set PDF document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Oğuz Çelikdemir, Metro Systems Turkey');
$pdf->SetTitle('BMPL Price Label');
# disable pdf document header and footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
# set PDF default font
$pdf->setDefaultMonospacedFont('PDF_FONT_MONOSPACED');
# set auto page breaks
$pdf->SetAutoPageBreak(true, 2);
$crs = array('width' => 0.5);
$style = array('width' => 0.25, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0));
for($i = 0; $i < count($labels); $i++)
{
# add PDF page
$pdf->addPage();
# split the price values
$prdPrice = explode(".", $labels[$i]['PRODUCT_PRICE']);
$shfPrice = explode(".", $labels[$i]['SHELF_PRICE']);
$prcLeft = $prdPrice[0];
$prcRight = $prdPrice[1];
$shfLeft = $shfPrice[0];
$shfRight = $shfPrice[1];
# Label variables
$priceLeft = '<span style="color:#b4b4b4;">'.$prcLeft.'</span>';
$priceLeftCent = '<span style="color:#b4b4b4;">'.$prcRight.'</span';
$priceRight = '<span style="color:#b4b4b4;">'.$shfLeft.'</span>';
$priceRightCent = '<span style="color:#000;">'.$shfRight.'</span>';
$taxLabelLeft = '<span style="color:#b4b4b4;">KDV\'Lİ</span>';
$taxLabelRight = 'KDV\'Lİ';
$articleDesc = '\''.$labels[$i]['ARTICLE_DESC'].'\'';
$articleNumber = $labels[$i]['SUBSYS_ART_NO'];
$labelText = '\''.$labels[$i]['LABEL_TEXT'].'\'';
$promoDate = $labels[$i]['END_DATE'];
$promoLabel = $labels[$i]['PROMO'];
////////////// PREPARE THE LABELS \\\\\\\\\\\\\\
# LABEL BOTTOM
$pdf->SetFont('dinpro', '', 6);
$pdf->writeHTMLCell(20, 0, 5, 50, $articleNumber, '', 1, 0, true, 'L');
$pdf->writeHTMLCell(20, 0, 28, 50, $promoDate, '', 1, 0, true, 'L');
if(is_null($promoLabel)) {
$pdf->writeHTMLCell(20, 0, 42, 50, '', '', 1, 0, true, 'R');
} else {
$pdf->writeHTMLCell(20, 0, 42, 50, 'FIRSAT', '', 1, 0, true, 'R');
}
# LABEL LEFT
$pdf->SetFont('dinprob', 'B', 10);
$pdf->MultiCell(90, 20, $articleDesc, 0, 'L', false, 1, 5, 5.50);
$pdf->SetFont('dinprob', '', 8);
$pdf->writeHTMLCell(45, 10, 5, 17, 'SATIŞ FİYATI', '', 1, 0, true, 'F');
$pdf->SetFont('dinprob', 'B', 44);
$pdf->writeHTMLCell(30, 27, 5, 24, $priceLeft, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinprob', 'B', 20);
$pdf->writeHTMLCell(15, 10, 26.5, 28.5, $priceLeftCent, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinpro', '', 6);
$pdf->writeHTMLCell(15, 10, 29.2, 37.3, $taxLabelLeft, '', 1, 0, 'L', true);
if(!is_null($labels[$i]['LABEL_SIGN']))
{
$pdf->Line(7, 41, 38, 22, $crs);
}
# LABEL RIGHT
$pdf->SetFont('dinprob','',8);
$pdf->writeHTMLCell(45, 10, 50, 17, $labelText, '', 1, 0, true, 'C');
$pdf->SetFont('dinprob', 'B', 58);
$pdf->writeHTMLCell(45, 30, 42, 21, $priceRight, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinprob', 'B', 24);
$pdf->writeHTMLCell(15, 10, 79.5, 28, $priceRightCent, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinpro', '', 6);
$pdf->writeHTMLCell(15, 10, 81, 38.5, $taxLabelRight, '', 1, 0, 'L', true);
$js .= 'print(true);';
$pdf->IncludeJS($js);
ob_end_clean();
return $pdf->Output('bpml_label.pdf', 'I');
}
}
?>
When you return the the PDF to the client, send it with the correct content type. Add this header before sending back the response
header('Content-Type: application/pdf');
Then the client can properly decide, what to do with the document.
I tried above suggestions but no success so that I did alternate way as belows :
First of all, some browsers doesn't support response object like PDF, therefore, I did postback to PDF file url then handle with an iframe inside the Ext window object.
success: function(response)
{
var _url = response.responseText;
new Ext.Window({
title: 'Labels',
id: 'pdfWindow',
layout: 'fit',
width: 600,
height: 500,
closeAction: 'destroy', // take notice that 'hide' action doesn't work
items: [{
xtype: 'component',
autoEl: {
tag: 'iframe', // we need iframes 'src' parameter to handle PDF
style: 'height:100%; width:100%; border:none',
// here we used special style to get rid of iframe title
src: _url
}
}]
}).show();
},
SERVER SIDE
// we need an unique ID to be able set unique file name
$uniqeid = uniqid(); # if you want add true parameter to extend sensibility
$filename = '/var/www/label/print/'.$uniqeid.'.pdf';
# F parameter creating the file in specified directory, don't forget to set security 777 for folder ortherwise you might take an error
$pdf->Output($filename, 'F');
echo('/print/'.$uniqeid.'.pdf');
Add target _blank to the printing button. Your browser will open it in a new window with PDF content generated by server.
Add content header as others advise:
header('Content-Type: application/pdf');

How to display tabs using Zend_PDF

I am having an issue with generating pdf documents. My tabulator characters are not displayed properly. I already tried different fonts, or encodings (UTF-8, Windows1552).
With some fonts the character is completely hidden. With some I get a square symbol displayed instead of my tab "\t".
Here is my code.
The question is "How to display tabs using Zend_PDF?"
public function generate()
{
$pdf = new Zend_Pdf();
$page = new Zend_Pdf_Page( Zend_Pdf_Page::SIZE_A4 );
//render basic template
$template = Zend_Pdf_Image::imageWithPath( APPLICATION_PATH . '/resources/pdf/template.png' );
$page->drawImage( $template, 0 ,0, 595, 842 );
//render document title
$font = Zend_Pdf_Font::fontWithPath( APPLICATION_PATH . '/resources/pdf/arial-bold.ttf' );
$page ->setFont($font, 14)
->drawText( 'Rechnung', 390, 700, 'utf-8' );
//render reciever adress
$font = Zend_Pdf_Font::fontWithPath( APPLICATION_PATH . '/resources/pdf/arial.ttf' );
$adressText = array(
'Kundennummer' . "\t" . $this->_user->getUserIdString(),
'Belegnummer' . "\t" . $this->_payin->getPayinIdString(),
'Datum' . "\t\t\t" . $this->_payin->getDateCreated()->format( 'd.m.Y' ),
'Seite' . "\t\t\t" . '1/1'
);
$page ->setFont($font, 12);
$adressY = 680;
foreach( $adressText as $line )
{
$page->drawText( $line, 390, $adressY , 'utf-8' );
$adressY -= 12;
}
//add page to pdf document
$pdf->pages[] = $page;
//save pdf
$pdf->save( $this->getOption( 'path' ) );
}
It could be that the pdf doesn't understand \t.
Try replacing it with 'chr(9)' which is the ascii value of the tab character. For example:-
$tab = chr(9);
$adressText = array(
'Kundennummer' . $tab . $this->_user->getUserIdString(),
'Belegnummer' . $tab . $this->_payin->getPayinIdString(),
// etc..
);
Correction:
As you have to supply the x,y coordinates to Zend_Pdf_Page::drawText() things like tabs, line feeds, etc will not work.
You will have to set fixed coordinates for your tab stops.
For example:-
$tabs = array(5, 20, 30, 50);
$page->drawText("At 1st tab", $tabs[0], 10);
$page->drawText("At 2nd Tab", $tabs[1], 10);
$page->drawText("At 3rd Tab", $tabs[2], 10);
Hopefully you get the idea.

Categories