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);
}
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);
}
}
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');
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.
I am attempting to replicate the encryption method that is already in existence for part of an application that was written in VB.Net, in PHP. The resulting encrypted values must be the same. I don't have much experience doing encryption and despite my best effort in scouring the web for information my encrypted values do not match. Could someone let me know where I am going wrong in my PHP code?
Here is the .Net process. Unfortunately this method cannot be changed at this time.
Public Class Encrypt
'8 bytes randomly selected for both the Key and the Initialization Vector
'the IV is used to encrypt the first block of text so that any repetitive
'patterns are not apparent
Private Shared KEY_64() As Byte = {42, 16, 93, 156, 78, 4, 218, 32}
Private Shared IV_64() As Byte = {55, 103, 246, 79, 36, 99, 167, 3}
Public Function EncryptPwd(ByVal value As String) As String
Try
Dim cryptoProvider As DESCryptoServiceProvider = _
New DESCryptoServiceProvider()
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = _
New CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), _
CryptoStreamMode.Write)
Dim sw As StreamWriter = New StreamWriter(cs)
sw.Write(value)
sw.Flush()
cs.FlushFinalBlock()
ms.Flush()
'convert back to a string
Return Convert.ToBase64String(ms.GetBuffer(), 0, CInt(ms.Length))
Finally
End Try
End Function
End Class
Here is my PHP.
<?php
function addpadding($string, $blocksize = 8)
{
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
?>
<form id="form1" name="form1" method="post" action="">
enter text
<input name="data" type="text" />
<input type="hidden" value="op" name="op" />
<input type="submit" name="Submit" value="Submit" />
</form>
<?php
if(!isset($_POST['op'])) {
}else {
$buffer = $_POST['data'];
$keyArray=array( 42, 16, 93, 18, 156, 78, 4, 32 );
$key=null;
foreach ($keyArray as $element)
$key.=CHR($element);
$ivArray=array( 55, 103, 246, 79, 36, 99, 167, 3 );
$iv=null;
foreach ($ivArray as $element)
$iv.=CHR($element);
echo "Key: " .$key. "<br>";
echo "IV: " .$iv. "<br>";
echo "Result: " .base64_encode(mcrypt_cbc(MCRYPT_DES, $key, addpadding($buffer), MCRYPT_ENCRYPT, $iv));
}
?>
Looks like a typo
Private Shared KEY_64() As Byte = {42, 16, 93, 156, 78, 4, 218, 32}
$keyArray=array( 42, 16, 93, 18, 156, 78, 4, 32 );
try
$keyArray=array(42, 16, 93, 156, 78, 4, 218, 32);
I've had similar issues taking RSA-encrypted data from .Net to be decrypted in PHP. Typically it came down to a character set issue. If possible, make sure both systems are handling string values as UTF-8 strings.