tcpdf center text not fully in center - php

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);
}
}

Related

TCPDF margins on different page by auto page break

https://ibb.co/qYH0x20
I'm using TCPDF for label PDF on my project.
I set custom footer function. In footer function, there are different margins for second page.
I'm writing text by MultiCell method. But on the project image,
$pdf->MultiCell(0, 0, $txt, 1, 'L', 0, 1, '', '', true, 0, true);
// This code is in the Extended footer method.
// $t2 = is page front or back
if ($t2 == 2) { $this->SetMargins(2, 1, 7, true); } else { $this->SetMargins(7, 1, 2, true); }
Where is the problem??

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.

Fpdf and PDF_LABEL

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);
}

How to put HTML data into header of tcpdf?

I'm using the tcpdf library to generate the pdf document. I'm using smarty template engine to hold the data. Below is the script to put in the header data:
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 'PQR',
'XYZ');
I want to put HTML table content of smarty template in place of XYZ, the table content is going to be dynamic(meaning the data in table may vary for each PDF document).
As #vinzcoco says, you must extend TCPDF to achieve what you want. Here is a simple improvement that I think it could be useful for you:
class MyTCPDF extends TCPDF {
var $htmlHeader;
public function setHtmlHeader($htmlHeader) {
$this->htmlHeader = $htmlHeader;
}
public function Header() {
$this->writeHTMLCell(
$w = 0, $h = 0, $x = '', $y = '',
$this->htmlHeader, $border = 0, $ln = 1, $fill = 0,
$reseth = true, $align = 'top', $autopadding = true);
}
}
Now, once you've got your MyTCPDF object available, you just need to do this to set the HTML header content:
$mytcpdfObject->setHtmlHeader('<table>...</table>');
and the HTML content won't be hardcoded into the Header() method (more flexible for you).
I used the following method to set header
$PDF_HEADER_LOGO = "logo.png";//any image file. check correct path.
$PDF_HEADER_LOGO_WIDTH = "20";
$PDF_HEADER_TITLE = "This is my Title";
$PDF_HEADER_STRING = "Tel 1234567896 Fax 987654321\n"
. "E abc#gmail.com\n"
. "www.abc.com";
$pdf->SetHeaderData($PDF_HEADER_LOGO, $PDF_HEADER_LOGO_WIDTH, $PDF_HEADER_TITLE, $PDF_HEADER_STRING);
This is work for me.
You must instance your PDF class and extend the TCPDF class.
After your PDF class should look like this:
class MyTCPDF extends TCPDF{
public function Header(){
$html = '<table>...</table>';
$this->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = 'top', $autopadding = true);
}
}
You must adapt this to your own project.

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');

Categories