with help of below code, i successfully displaying tracking_id in pdf , Now i am trying to displaying bar code image....
Its working fine if i use static value . but when i passed column value instead of static value it gave error :
Static : $text = isset($_GET['text']) ? $_GET['text'] : "1234";
:
Dynamic :
$text = isset($_GET['text']) ? $_GET['text'] : $tracking_id;
Result :
I guess I am passing tracking_id column value not in proper manner :
<?php
$con = mysqli_connect("localhost","root","iJ564645qA9v3J","do_management4");
include('database.php');
$result = mysqli_query($con,"SELECT * FROM orders");
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$tracking_id = $row['tracking_id'];
}
$database = new Database();
$result = $database->runQuery("SELECT tracking_id FROM orders where id = '".$_REQUEST['id']."'");
$header = $database->runQuery("SELECT UCASE(`COLUMN_NAME`)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='do_management4'
AND `TABLE_NAME`='orders'
and `COLUMN_NAME` in ('tracking_id')");
require __DIR__ . '/../vendor/autoload.php';
use BarcodeBakery\Barcode\BCGcode11;
// Loading Font
$font = new BCGFontFile(__DIR__ . '/../font/Arial.ttf', 18);
// Don't forget to sanitize user inputs
$text = isset($_GET['text']) ? $_GET['text'] : $tracking_id;
// The arguments are R, G, B for color.
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);
$drawException = null;
try {
$code = new BCGcode11();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse($text); // Text
} catch (Exception $exception) {
$drawException = $exception;
}
$drawing = new BCGDrawing('', $color_white);
if ($drawException) {
$drawing->drawException($drawException);
} else {
$drawing->setBarcode($code);
$drawing->draw();
}
// Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="barcode.png"');
// Draw (or save) the image into PNG format.
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
?>
Considering the documentation BCGcode11 allows only the numbers from 0 to 9 and a hyphen (-)
You either can
Remove the unwanted characters from $tracking_id which may lead to wrong datas
Use the proper class for the barecode you want.
BCGcode39 allows more characters to build your barecode : Code 39 contains all the capital letters, the numbers from 0 to 9, the following special characters "-.$/+%" and spaces.
Use BCGcode39 it allows you to use more characters lik capital letters and some special characters. or keep using BCGcode11 but then you need to remove the unallowed characters.
Related
I´ve started using HTML2PDF (https://www.html2pdf.fr/) to create invoices, now the following code works:
try {
ob_end_clean();
ob_start();
include('../faktura/fa.php');
$html = ob_get_contents();
ob_end_clean();
$content = $html;
$html2pdf = new Html2Pdf('P', 'A4', 'cs',true,"UTF-8");
$html2pdf->setDefaultFont('freeserif');
$html2pdf->pdf->SetFont('freeserif');
$html2pdf->writeHTML($content);
$pdfContent = $html2pdf->output('my_doc.pdf', 'S');
} catch (Html2PdfException $e) {
$html2pdf->clean();
$formatter = new ExceptionFormatter($e);
echo $formatter->getHtmlMessage();
}
The content of fa.php is converted to pdf, however if I change one of the lines to:
include('../faktura/fa.php?id=105');
note that I only added ?id=105, it returns only a blank page.
The php file fa.php includes:
$id = (int) $_GET['id'];
What I need to do is to pass an ID to that php script so the invoice of the exact order is generated.
Include basically means "copy the code from that file to here".
So if you change the included file code from $id = (int) $_GET['id']; to $id = $thatId;
And prior to the include() function you'd write $thatId = 105;
The included file will be able to access the variable.
File A:
$id = 105;
include('../faktura/fa.php');
File fa.php
//$id = (int) $_GET['id']; // no need this anymore as we've declared a $id variable with a value;
// .. Do something with $id
// .. for example:
echo $id; //will print 105
Or, in case you want fa.php to continue working with QUERY PARAMETER and to work with your invoice (2pdf) code:
if(!isset($id) && isset($_GET['id'])) {
$id = (int) $_GET['id'];
}
I am using Python version of FPDF, PyFPDF to generate PDFs. I want to add transparency to a rectangle I created using PyFPDF.
I found PHP code in fpdf documentation that lets us add transparency - trasnparency. I tried to follow this and write code in python but it didn't work.
Code snippet found in documentation(in PHP):
source
<?php
require('fpdf.php');
class AlphaPDF extends FPDF
{
var $extgstates = array();
// alpha: real value from 0 (transparent) to 1 (opaque)
// bm: blend mode, one of the following:
// Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn,
// HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
function SetAlpha($alpha, $bm='Normal')
{
// set alpha for stroking (CA) and non-stroking (ca) operations
$gs = $this->AddExtGState(array('ca'=>$alpha, 'CA'=>$alpha, 'BM'=>'/'.$bm));
$this->SetExtGState($gs);
}
function AddExtGState($parms)
{
$n = count($this->extgstates)+1;
$this->extgstates[$n]['parms'] = $parms;
return $n;
}
function SetExtGState($gs)
{
$this->_out(sprintf('/GS%d gs', $gs));
}
function _enddoc()
{
if(!empty($this->extgstates) && $this->PDFVersion<'1.4')
$this->PDFVersion='1.4';
parent::_enddoc();
}
function _putextgstates()
{
for ($i = 1; $i <= count($this->extgstates); $i++)
{
$this->_newobj();
$this->extgstates[$i]['n'] = $this->n;
$this->_out('<</Type /ExtGState');
$parms = $this->extgstates[$i]['parms'];
$this->_out(sprintf('/ca %.3F', $parms['ca']));
$this->_out(sprintf('/CA %.3F', $parms['CA']));
$this->_out('/BM '.$parms['BM']);
$this->_out('>>');
$this->_out('endobj');
}
}
function _putresourcedict()
{
parent::_putresourcedict();
$this->_out('/ExtGState <<');
foreach($this->extgstates as $k=>$extgstate)
$this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
$this->_out('>>');
}
function _putresources()
{
$this->_putextgstates();
parent::_putresources();
}
}
?>
usage
<?php
require('alphapdf.php');
$pdf = new AlphaPDF();
$pdf->AddPage();
$pdf->SetLineWidth(1.5);
// draw opaque red square
$pdf->SetFillColor(255,0,0);
$pdf->Rect(10,10,40,40,'DF');
// set alpha to semi-transparency
$pdf->SetAlpha(0.5);
// draw green square
$pdf->SetFillColor(0,255,0);
$pdf->Rect(20,20,40,40,'DF');
// draw jpeg image
$pdf->Image('lena.jpg',30,30,40);
// restore full opacity
$pdf->SetAlpha(1);
// print name
$pdf->SetFont('Arial', '', 12);
$pdf->Text(46,68,'Lena');
$pdf->Output();
?>
This is what I wrote in python:
source
class EXPDF(FPDF):
def __init__(self, orientation='P', unit='mm', style='A4'):
super(EXPDF, self).__init__(orientation=orientation, unit=unit, format=style)
self.page_format = style.lower()
self.extgstates = {}
def set_alpha(self, alpha, bm='Normal'):
gs = self.add_ext_gstate({'ca': alpha, 'CA': alpha, 'BM': '/'+bm})
self.set_ext_gstate(gs)
def add_ext_gstate(self, parms):
n = len(self.extgstates.keys())+1
if n not in self.extgstates.keys():
self.extgstates[n] = { 'parms': parms }
else:
self.extgstates[n]['parms'] = parms
return n
def set_ext_gstate(self, gs):
self._out(sprintf('/GS%d gs', gs))
def _enddoc(self):
if self.extgstates and self.pdf_version < '1.4':
self.pdf_version = '1.4'
super()._enddoc()
def _putextgstates(self):
for i in range(1, len(self.extgstates.keys())+1):
self._newobj()
self.extgstates[i]['n'] = self.n
self._out('<</Type /ExtGState')
parms = self.extgstates[i]['parms']
self._out(sprintf('/ca %.3F', parms['ca']))
self._out(sprintf('/CA %.3F', parms['CA']))
self._out('/BM'+parms['BM'])
self._out('>>')
self._out('endobj')
def _putresourcedict(self):
super()._putresourcedict()
self._out('/ExtGState <<')
for k in self.extgstates:
self._out('/GS'+str(k)+' '+str(self.extgstates[k]['n'])+' O R')
self._out('>>')
usage
pdf = EXPDF()
pdf.set_alpha(0.5)
pdf.rectangle(20, 20, 40, 40, 'DF')
The code didn't throw any error when I ran it. But when I tried to open the generated pdf in Adobe Acrobat, it said There was a problem reading this document (135). I tried opening the pdf in google chrome. It opened but the rectangle was still opaque.
I think your python code has a couple of errors:
it is missing the _putresources method.
in the method _putresourcesdict the following line has a capital O rather than a zero 0. So change to 0 R.
self._out('/GS'+str(k)+' '+str(self.extgstates[k]['n'])+' O R')
You need a class like this (pyFPDF used https://github.com/reingart/pyfpdf):
class PDF (fpdf.FPDF):
def __init__ (self, orientation = 'P', unit = 'mm', format = 'A4'):
self.__extgstates = []
super().__init__ (orientation, unit, format)
# alpha: real value from 0 (transparent) to 1 (opaque)
# bm: blend mode, one of the following:
# Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn,
# HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
def set_alpha(self, alpha, bm='Normal'):
# set alpha for stroking (CA) and non-stroking (ca) operations
data = {'ca':alpha,'CA':alpha,'BM':'/' + bm, 'n' : 0}
gs = self.add_ext_gstate(data)
self.set_ext_gstate(gs + 1)
def add_ext_gstate(self, data):
n = len(self.__extgstates)
self.__extgstates.append(data)
return n
def _enddoc(self):
if len(self.__extgstates) > 0 and self.pdf_version < '1.4':
self.pdf_version ='1.4'
super()._enddoc()
def set_ext_gstate(self, gs):
self._out('/GS%d gs' % (gs))
def _putextgstates(self):
i = 0
while i < len(self.__extgstates):
self._newobj()
self._out('<</Type /ExtGState')
self.__extgstates[i]["n"] = self.n
parms = self.__extgstates[i]
self._out('/ca %.3F' % (parms["ca"]))
self._out('/CA %.3F' % (parms["CA"]))
self._out('/BM ' + parms["BM"])
self._out('>>')
self._out('endobj')
i += 1
def _putresourcedict(self):
super()._putresourcedict()
self._out('/ExtGState <<')
for index, eg in enumerate(self.__extgstates):
self._out('/GS' + str(index + 1) + ' ' + str(eg["n"]) + ' 0 R')
self._out('>>')
def _putresources(self):
self._putextgstates()
super()._putresources()
I created a php page that print the barcode. Just to view it before i print it on an A4. Still in testing phase. The codes are as below.
<?php
include('include/conn.php');
include('include/Barcode39.php');
$sql="select * from barcode where b_status = 'NOT-PRINTED'";
$result=mysqli_query($conn,$sql);
echo mysqli_num_rows($result);
$i=0;
while($row=mysqli_fetch_assoc($result)){
$acc_no = $row["b_acc_no_code"];
$bc = new Barcode39($row["b_acc_no_code"]);
echo $bc->draw();
$bc->draw($acc_no.$i.".jpg");
echo '<br /><br />';
$i++;
}
?>
Without the while loop, it can be printed, but only one barcode. How to make it generate, for example in the database have 5 values, it will print 5 barcode in the same page. Thanks in advance
Try to use another bar code source. Because It is generate only one bar code per page. Can't able to create multiple bar code per page.
I know this is an older post but comes up in searches so is probably worth replying to.
I have successfully used the Barcode39 to display multiple barcodes. The trick is to get base64 data from the class and then display the barcodes in separate HTML tags.
The quickest way to do this is to add a $base64 parameter to the draw() method:
public function draw($filename = null, $base64 = false) {
Then, near the end of the draw() method, modify to buffer the imagegif() call and return the output in base64:
// check if writing image
if ($filename) {
imagegif($img, $filename);
}
// NEW: Return base 64 for the barcode image
else if ($base64) {
ob_start();
imagegif($img);
$image_data = ob_get_clean();
imagedestroy($img);
return base64_encode($image_data);
}
// display image
else {
header("Content-type: image/gif");
imagegif($img);
}
Finally, to display multiples from the calling procedure, construct the image HTML in the loop and display:
// assuming everything else has been set up, end with this...
$base64 = $barcode->draw('', true); // Note the second param is set for base64
$html = '';
for ($i = 0; $i < $numBarcodes; $i++) {
$html .= '<img src="data:image/gif;base64,'.$base64.'">';
}
die('<html><body>' . $html . '</body></html>');
I hope this helps anyone else facing this challenge.
I'm using QRCode from Google API and I put this code in the function.
Now I want to show two images, for example: Two images with different sizes or datas!
It does not matter if you use class or function, I just want to get different output on the page.
This is code:
<?php
function CreateQRCode($data, $size, $logo) {
header('Content-type: image/png');
// Get QR Code image from Google Chart API
// http://code.google.com/apis/chart/infographics/docs/qr_codes.html
$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs='.$size.'&chl='.urlencode($data));
if($logo !== FALSE){
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
// Scale logo to fit in the QR Code
$logo_qr_width = $QR_width/3;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
}
imagepng($QR);
imagedestroy($QR);
}
CreateQRCode('http://google.com', '200x200', FALSE);
?>
Like this:
example 2
example 1
Alright so first things first:
I've searched over this site for 6+ hours and I keep coming up with the same results. The main answer I keep getting is: How to Generate Barcode using PHP and Display it as an Image on the same page
But this is not working for me. Even the answer on that page that was accepted ends with "After you have added all the codes, you will get this way:" which is so vague I feel like I'm supposed to already be an expert to understand it. I'm getting frustrated with this problem because I cannot seem to find any "moron directions" that can help me understand how everything works in this library for barcode generator for php.
Here is what I have:
I'm using fpdf to print a pdf file which works great!
Page Name: PrintMyPDF.php
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
$thisorderID = $_GET['Xort'];
require ('UFunctions.php');
if (trim($thisorderID) == ""){
$value = '0';
}
if (!is_digit($thisorderID) || $thisorderID < 0)
{
header('Location:ErrorInt.php');
exit;
}
//Database connection established
require_once('DBASEConnector.php');
$sql2 = "SELECT users.name, users.storenum, users.storename, Orders.OrderID, Orders.name
FROM users, Orders
WHERE Orders.name = users.name
AND Orders.OrderID = '$thisorderID'";
$result = $db->query($sql2);
$row = $result->fetch_assoc();
$ThisStoreNum = $row['storenum'];
$ThisStoreName = $row['storename'];
require('fpdf.php');
$pdf = new FPDF();
//$fpdf->SetMargins(0, 0, 0);
//$fpdf->SetAutoPageBreak(true, 0);
$pdf->SetAuthor('Walter Ballsbig');
$pdf->SetTitle('Order Form');
$pdf->SetFont('Helvetica','B',16);
$pdf->SetTextColor(0,0,0);
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
$pdf->SetXY(50,20);
$pdf->SetDrawColor(0,0,0);
$pdf->Cell(100,10,'Order Form',1,1,'C',0);
$pdf->SetFontSize(10);
$pdf->SetX(50);
$pdf->Cell(100,10, 'Order: '.$thisorderID.' | Store: '.$ThisStoreNum.'-'.$ThisStoreName,1,1,'C',0);
$pdf->SetXY(10,50);
$pdf->SetFontSize(12);
$pdf->Cell(6,6,'X',1,0,'C',0);
$pdf->Cell(14,6,'QTY',1,0,'C',0);
$pdf->Cell(130,6, 'ITEM',1,0,'C',0);
$pdf->Cell(30,6, 'UNIT',1,1,'C',0);
$query = "SELECT Inventory.ProductI, Inventory.ProductName, Inventory.CurrentQty, Inventory.Pull, Inventory.Unit, OrderItems.ProductI, OrderItems.QtyO, OrderItems.OrderI
FROM Inventory, OrderItems
WHERE OrderItems.OrderI = '$thisorderID'
AND OrderItems.ProductI = Inventory.ProductI
ORDER BY Inventory.Pull, Inventory.ProductName";
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
$pdf->SetFontSize(12);
IF ($row['CurrentQty'] <=0)
{
$pdf->SetFontSize(10);
$pdf->Cell(6,6,'BO',1,0,'C',0);
$pdf->SetFontSize(12);
}else{
$pdf->Cell(6,6,' ',1,0,'C',0);
}
$pdf->Cell(14,6, $row['QtyO'],1,0,'C',0);
$pdf->Cell(130,6, $row['ProductName'],1,0,'L',0);
$pdf->Cell(30,6, $row['Unit'],1,1,'C',0);
}
$pdf->Output();
$db->close();
?>
This prints up my pdf beautifully! Now I wanted to add a barcode on the page that will represent the order number for scanning purposes.
Now here is what I have for my code that contains the barcode... code.
Name of barcode page: BarCodeIt.php
<?php
function BarCodeIt($MyID) {
// Including all required classes
require_once('./class/BCGFontFile.php');
require_once('./class/BCGColor.php');
require_once('./class/BCGDrawing.php');
// Including the barcode technology
require_once('./class/BCGcode39.barcode.php');
// Loading Font
$font = new BCGFontFile('./font/Arial.ttf', 18);
// Don't forget to sanitize user inputs
$text = isset($_GET['text']) ? $_GET['text'] : $MyID;
// The arguments are R, G, B for color.
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);
$drawException = null;
try {
$code = new BCGcode39();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse($text); // Text
} catch(Exception $exception) {
$drawException = $exception;
}
/* Here is the list of the arguments
1 - Filename (empty : display on screen)
2 - Background color */
$drawing = new BCGDrawing('', $color_white);
if($drawException) {
$drawing->drawException($drawException);
} else {
$drawing->setBarcode($code);
$drawing->draw();
}
//Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="barcode.png"');
// Draw (or save) the image into PNG format.
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
}
?>
Now in my PDF file just before this line:
$pdf->Output();
I have added this:
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
require('/BarCodeIt.php');
$MyBarCode = BarCodeIt($thisorderID);
echo $MyBarCode;
But what it does is all of my other pdf elements disappear and I'm left with only a big barcode (the right one! that part works) but that's all that is on the screen. It's like when the barcode section runs it negates everything else and just prints the barcode. I want to print just the barcode where I want it on the PDF but I'm not clever enough to figure out what I'm doing wrong. Any help on this would be greatly appreciated.
In $pdf->SetDisplayMode(real,'default');, real is not an identifier. I believe you've forgotten the $ prefix.
Have you warnings reporting at maximum level? If not, include:
error_reporting(E_ALL);
in your script and see that it shows additional issues.
I'm not familiar with fpdf, but what you are doing seems wrong just by looking at it: Everywhere you add elements to your pdf by using methods on your $pdf object like $pdf->... and when you want to add the barcode, you echo it out directly.
Don't echo your image out. Instead get rid of the header() calls in your barcode script, save your image and look for the right method to add an image to the $pdf object.
Here is a question with answers that deals with adding an image: Inserting an image with PHP and FPDF