Generate PDF using TCPDF on ajax call - php

I'm using TCPDF class to generate PDF. First I send some data in json format (jquery) then I would like to generate PDF with these data.
Could you tell me if I am right. I should generate pdf, save it on the server and then if ajax call returns success, redirect the user to this pdf. Is a good way?
I have:
$.ajax({
url: '/pdf/fiele_to_generate_pdf.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: $.toJSON(jsonObj),
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.location.href = '/pdf/example.pdf';
}
});
Thanks for any advice.
Edit: So I have sent a request to make the pdf via Ajax to the server, then the pdf file was generated and saved on the server. Then I have used window.location.href to redirect the user to this pdf. Everything works but I would like to avoid saving file on the server. Any ideas?

Ok this script will save the file and also display in the browser
the trick is in using the output method with the 'F' or 'I':
$pdf->Output("your path", 'F'); //save pdf
$pdf->Output('file.pdf', 'I'); // show pdf
CODE
<?php
class PDF extends TCPDF {
public function Header (){
$this->SetFont('dejavusans', '', 14);
$title = utf8_encode('title');
$subtitle = utf8_encode('sub title');
$this->SetHeaderMargin(40);
$this->Line(15,23,405,23);
}
public function Footer() {
$this->SetFont('dejavusans', '', 8);
$this-> Cell (0, 5, 'Pag '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
}
public static function makeHTML ($json){
$html = '<table border="0.5" cellspacing="0" cellpadding="4">
<tr>
<th bgcolor="#DAB926" style="width:3%; text-align:left"><strong>you th</strong></th>
</tr>';
for ($i=0; $i<count($json); $i++)
{
$a= $i+1;
$html .= '<tr>
<td style="width:15%; text-align:left">'.$json[$i]->Name.'</td>
</tr>';
}
$html .= '</table>';
return $html;
}
}
function printReport ($json )
{
set_time_limit(0);
$pdf = new PDF("L", PDF_UNIT, "A3",true, 'UTF-8', false);
$pdf->SetMargins (15, 27, 15, true);
$pdf->SetFont('dejavusans', '', 8);
$pdf->SetAutoPageBreak(TRUE,50);
$pdf->AddPage();
//create html
$html = $pdf->makeHTML($json);
$pdf->writeHTML($html, false, false, false, false, '');
if (!file_exists("your path"))
mkdir("your path");
$pdf->Output("your path", 'F'); //save pdf
$pdf->Output('file.pdf', 'I'); // show pdf
return true;
}
$json = json_decode("your json");
printReport($json);
?>

Related

TCPDF returning weird characters

maybe you can help me. When I try to show a pdf I created I got some weird symbols like this
u\>�'���O���r>c!%�#�R�`YPd+��vv����1��E�'^k-�WD�*+��W^��wy��V Z��dUdJ�B���C�ڳtK����j:c���5����50���D3lgH#�}%���D+������ix����,��-�'\�� �_st^&0�Y���������v�*Ӗ,W����u!H��sNN��0cӝ��`xEk��d��^� �8K9�BL����9�̋"6/�E�|�̛�-�7�P��B�#�T�F���4`����
What I do is transform a html file with this code
$html = $this->load->view('ReporteIngresoView', $data, TRUE);
$pdf = new Pdf('P', 'mm', 'A4', TRUE, 'UTF-8', FALSE);
$pdf->SetTitle('Reporte ingreso');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(40);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(TRUE);
$pdf->SetAuthor('Pontificia Universidad Católica del Ecuador');
$pdf->SetDisplayMode('real', 'default');
$pdf->AddPage();
$pdf->writeHTML($html, TRUE, 0, TRUE, 0);
$pdf->Output('My-File-Name.pdf', 'I');
On the other side I recieve it like this
Ext.Ajax.request
(
{
method: 'post',
url: '../servidor/archivo/ingreso/getreporte',
success: function(response){
Ext.getCmp('winReporteRegistro').update( response.responseText );
}
}
);
I am using php (server), html (create the page), extjs (interface), ajax (request) and TCPDF to create the pdf.
Any ideas?
Thanks in advance,
You need to convert the response to a Blob (link)
After creating the blob, you can create an URL object (link)
This is how I create a server side generated pdf and display it on the front end.
Adding code snippet:
var blob = new Blob(response.responseText, {type: 'application/pdf'});
var objectURL = URL.createObjectURL(blob);
Returning the location of the file and open that in another web page was the answer, the code is:
Server:
$html = $this->load->view('ReporteCajaView', $data, TRUE);
$pdf = new Pdf('P', 'mm', 'A4', TRUE, 'UTF-8', FALSE);
$pdf->SetTitle('Reporte item');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetMargins(25, 20, 20, true);
$pdf->SetAutoPageBreak(TRUE);
$pdf->SetAuthor('Universidad Católica');
$pdf->SetDisplayMode('real', 'default');
$pdf->setPrintHeader(FALSE);
$pdf->setPrintFooter(FALSE);
$pdf->AddPage();
$id = uniqid();
$pdf->writeHTML($html, TRUE, 0, TRUE, 0);
$pathservidor = 'c:/wamp64/www/Archivo/pdf/';
$pdf->Output($pathservidor . 'Reporte de caja' . '.pdf', 'F');
echo 'c:/wamp64/www/Archivo/pdf/'.'Reporte de caja'.'.pdf';
Client:
Ext.Ajax.request
(
{
method: 'post',
url: '../servidor/archivo/item/getreporte',
success: function(response){
window.open(response.responseText);
}
}
);
Thanks!
Sorry for the late answer but I broke my teeth on this yesterday and this morning I had an illumination :-)
You need to support the mime-type so simply add this in your .htaccess:
AddType application/pdf .pdf

How to send the file inline to the browser using php with TCPDF

I am new in PHP. i am using TCPDF to generate pdf file with php coding. I have a problem. I am not able to send file inline to the browser. when i click on file link it begin to start. I want to send it to the browser inline.
Here is my Code
<?php
require_once('tcpdf/tcpdf.php');
class MYPDF extends TCPDF {
//Page header
public function Header() {
// Logo
$image_file ='image/pacra.jpg';
$this->Image($image_file, 100, 05, 15);
// Set font
$this->SetFont('helvetica', 'I', 15);
// Title
$this->SetTextColor(0,63,127);
$this->Cell(0,50, 'The Pakistan Credit Rating Agency Limited', 0, false, 'C', 0, '', 0, false);
// $this->setColor(0,63,127);
$this->Line(10,30,200,30);
/*$style = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '10,20,5,10', 'phase' => 10, 'color' => array(255, 0, 0));
$this->Line(5, 10, 80, 30, $style);*/
}
// Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-25);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 05, 'Awami Complex FB-1, Usman Block, New Garden Town, Lahore - 54600, Pakistan'
, 0, false, 'C', 0, '', 0, false, 'T', 'M');
$this->Ln();
$this->Cell(0, 05, 'PABX: 92(42)3586 9504 Fax: 92(42)3583 0425 E-mail: pacra#pacra.com'
, 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->AddPage();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test123"; // Database name
$tbl_name="form"; // Table name
$con = mysqli_connect('localhost','root','');
mysqli_select_db($con,"test123");
$sql="SELECT * FROM form WHERE Id=34";
$result = mysqli_query($con,$sql);
while($rows= (mysqli_fetch_array($result,MYSQLI_ASSOC)))
{
$name = $rows['Name'];
$address = $rows['Address'];
$class = $rows['Designation'];
$phone = $rows['Text'];
$pdf->SetXY(10,32);
$pdf->SetFontSize(12);
$pdf->SetTextColor(0,63,127);
$pdf->writeHTML($name, true, false, true, false, '');
$pdf->SetTextColor(0,0,0);
$pdf->SetXY(180,32);
$pdf->writeHTML($address, true, false, true, false, '');
$pdf->SetXY(10,36);
$pdf->SetTextColor(0,0,0);
$pdf->writeHTML($class, true, false, true, false, '');
$pdf->SetXY(10,45);
$pdf->writeHTML($phone, true, false, true, false, '');
}
$html= '<h6>This is test paragraph</h6>
<br>
<h6>This is another test paragraph</h6>
';
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('test.pdf','I');
?>
Although it works with I, it works for O as well.
Try
$pdf->Output('name.pdf', 'O');
If the above does not work, it is just better to use the php header() function.
header("Content-type: application/pdf");
After using the header() function, just echo the content of the PDF file you created.
This is what I found out in the documentation.
I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects
the "Save as" option on the link generating the PDF.
D: send to the browser and force a file download with the name given by name.
F: save to a local server file with the name given by name.
S: return the document as a string (name is ignored).
FI: equivalent to F + I option
FD: equivalent to F + D option
E: return the document as base64 mime multi-part email attachment (RFC 2045)

PDF is not generated in codeigniter and display blank

I am working in codeigniter.I have downloaded TCPDF for creating pdf. I have followed all step for generating pdf in codeigniter.
My controller is:
function list_branch_report()
{
if($this->input->post('submit'))
{
$this->load->library('Pdf');
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Pdf Example');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'CodeIgniter TCPDF Integration');
$pdf->AddPage();
$pdf->Output('pdfexample.pdf', 'I');
$branch_id = $this->input->post('br_name');
$branch_code = $this->input->post('branch_code');
$query1 = $this->db->query("select * from branch_bal where branch_id = '$branch_id'");
$result1 = $query1->result();
$query2 = $this->db->query("select * from cash_depo where bid = '$branch_id'");
$result2 = $query2->result();
$this->load->view("admin/list_branch_report",array('br_result'=>$result1,'cash_result'=>$result2,'b_code'=>$branch_code));
}
And my view page is:
<div style="float:left;width:100%">
<center><h1> Branch Report </h1></center>
</div>
When I try to generate pdf then it will display blank.
where are you writing HTML to PDF I haven't work on tcpdf but as my experience with mpdf as far as i know
there should a function like
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
please refer tcpdf documentation for writeHTML() or writeHTMLCell() functions
http://www.tcpdf.org/doc/code/classTCPDF.html
or refer examples
http://www.tcpdf.org/examples.php
you have to assign codeigniter view to variable for that give last attribute as true
$html= $this->load->view("admin/list_branch_report",array('br_result'=>$result1,'cash_result'=>$result2,'b_code'=>$branch_code),true);
and then assign this to
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
I have written ob_start(); before the load view page.Then i have written
$html = $this->load->view("admin/list_branch_report",array('br_result'=>$result1,'cash_result'=>$result2,'b_code'=>$branch_code),true);
$pdf->writeHTML($html, true, false, true, false, '');
ob_clean();
$pdf->Output();
this code.
So it works perfect.
Thanks to all.
use mpdf instead of tpdf and send html that you want to convert in pdf.

Trying to save canvas data to server [duplicate]

I'm working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:
Create an image on an HTML5 Canvas using a generative algorithm
When the image is completed, allow users to save the canvas as an image file to the server
Allow the user to either download the image or add it to a gallery of pieces of produced using the algorithm.
However, I’m stuck on the second step. After some help from Google, I found this blog post, which seemed to be exactly what I wanted:
Which led to the JavaScript code:
function saveImage() {
var canvasData = canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", "testSave.php", false);
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.setRequestHeader("Content-Type", "application/upload");
ajax.send("imgData=" + canvasData);
}
and corresponding PHP (testSave.php):
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData = substr($imageData, strpos($imageData, ",") + 1);
$unencodedData = base64_decode($filteredData);
$fp = fopen('/path/to/file.png', 'wb');
fwrite($fp, $unencodedData);
fclose($fp);
}
?>
But this doesn’t seem to do anything at all.
More Googling turns up this blog post which is based off of the previous tutorial. Not very different, but perhaps worth a try:
$data = $_POST['imgData'];
$file = "/path/to/file.png";
$uri = substr($data,strpos($data, ",") + 1);
file_put_contents($file, base64_decode($uri));
echo $file;
This one creates a file (yay) but it’s corrupted and doesn’t seem to contain anything. It also appears to be empty (file size of 0).
Is there anything really obvious that I’m doing wrong? The path where I’m storing my file is writable, so that isn’t an issue, but nothing seems to be happening and I’m not really sure how to debug this.
Edit
Following Salvidor Dali’s link I changed the AJAX request to be:
function saveImage() {
var canvasData = canvas.toDataURL("image/png");
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open("POST", "testSave.php", false);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData=" + canvasData);
}
And now the image file is created and isn’t empty! It seems as if the content type matters and that changing it to x-www-form-urlencoded allowed the image data to be sent.
The console returns the (rather large) string of base64 code and the datafile is ~140 kB. However, I still can’t open it and it seems to not be formatted as an image.
Here is an example of how to achieve what you need:
Draw something (taken from canvas tutorial)
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// begin custom shape
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);
// complete custom shape
context.closePath();
context.lineWidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = 'blue';
context.stroke();
</script>
Convert canvas image to URL format (base64)
// script
var dataURL = canvas.toDataURL();
Send it to your server via Ajax
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file, you just saved
// and than put the image in your browser.
});
Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):
I played with this two weeks ago, it's very simple. The only problem is that all the tutorials just talk about saving the image locally. This is how I did it:
1) I set up a form so I can use a POST method.
2) When the user is done drawing, he can click the "Save" button.
3) When the button is clicked I take the image data and put it into a hidden field. After that I submit the form.
document.getElementById('my_hidden').value = canvas.toDataURL('image/png');
document.forms["form1"].submit();
4) When the form is submited I have this small php script:
<?php
$upload_dir = somehow_get_upload_dir(); //implement this function yourself
$img = $_POST['my_hidden'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);
?>
I think you should convert the image to base64 and then to Blob and send it to the server. When you use base64 images, a lot of lines will be sent to server. With blob, it's only the file.
You can use this code bellow:
function dataURLtoBlob(dataURL) {
let array, binary, i, len;
binary = atob(dataURL.split(',')[1]);
array = [];
i = 0;
len = binary.length;
while (i < len) {
array.push(binary.charCodeAt(i));
i++;
}
return new Blob([new Uint8Array(array)], {
type: 'image/png'
});
};
And canvas code here:
const canvas = document.getElementById('canvas');
const file = dataURLtoBlob( canvas.toDataURL() );
After that you can use ajax with Form:
const fd = new FormData;
fd.append('image', file);
$.ajax({
type: 'POST',
url: '/url-to-save',
data: fd,
processData: false,
contentType: false
});
The code in CoffeeScript syntax:
dataURLtoBlob = (dataURL) ->
# Decode the dataURL
binary = atob(dataURL.split(',')[1])
# Create 8-bit unsigned array
array = []
i = 0
while i < binary.length
array.push binary.charCodeAt(i)
i++
# Return our Blob object
new Blob([ new Uint8Array(array) ], type: 'image/png')
And canvas code here:
canvas = document.getElementById('canvas')
file = dataURLtoBlob(canvas.toDataURL())
After that you can use ajax with Form:
fd = new FormData
# Append our Canvas image file to the form data
fd.append 'image', file
$.ajax
type: 'POST'
url: '/url-to-save'
data: fd
processData: false
contentType: false
Send canvas image to PHP:
var photo = canvas.toDataURL('image/jpeg');
$.ajax({
method: 'POST',
url: 'photo_upload.php',
data: {
photo: photo
}
});
Here's PHP script:
photo_upload.php
<?php
$data = $_POST['photo'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
die;
?>
I've worked on something similar.
Had to convert canvas Base64-encoded image to Uint8Array Blob.
function b64ToUint8Array(b64Image) {
var img = atob(b64Image.split(',')[1]);
var img_buffer = [];
var i = 0;
while (i < img.length) {
img_buffer.push(img.charCodeAt(i));
i++;
}
return new Uint8Array(img_buffer);
}
var b64Image = canvas.toDataURL('image/jpeg');
var u8Image = b64ToUint8Array(b64Image);
var formData = new FormData();
formData.append("image", new Blob([ u8Image ], {type: "image/jpg"}));
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload", true);
xhr.send(formData);
If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:
<?php
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
?>
http://php.net/manual/ro/function.base64-decode.php
In addition to Salvador Dali's answer:
on the server side don't forget that the data comes in base64 string format. It's important because in some programming languages you need to explisitely say that this string should be regarded as bytes not simple Unicode string.
Otherwise decoding won't work: the image will be saved but it will be an unreadable file.
I just made an imageCrop and Upload feature with
https://www.npmjs.com/package/react-image-crop
to get the ImagePreview ( the cropped image rendering in a canvas)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);
I prefer sending data in blob with content type image/jpeg rather than toDataURL ( a huge base64 string`
My implementation for uploading to Azure Blob using SAS URL
axios.post(azure_sas_url, image_in_blob, {
headers: {
'x-ms-blob-type': 'BlockBlob',
'Content-Type': 'image/jpeg'
}
})

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