php barcode - display multiple barcode in single page - php

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.

Related

Fetch rss with php - Conditional for Enclosured image and not Enclosured

I'm working on a project and it's something new for me. I'll need to fetch rss content from websites, and display Descripion, Title and Images (Thumbnails). Right now i've noticed that some feeds show thumbnails as Enclosure tag and some others dont. right now i have the code for both, but i need to understand how i can create a conditional like:
If the rss returns enclosure image { Do something }
Else { get the common thumb }
Here follow the code that grab the images:
ENCLOSURE TAG IMAGE:
if ($enclosure = $block->get_enclosure())
{
echo "<img src=\"" . $enclosure->get_link() . "\">";
}
NOT ENCLOSURE:
if ($enclosure = $block->get_enclosure())
{
echo '<img src="'.$enclosure->get_thumbnail().'" title="'.$block->get_title().'" width="200" height="200">';
}
=================================================================================================
PS: If we look at both codes they're almost the same, the difference are get_thumbnail and get_link.
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Thanks everyone in advance!
EDITED
Here is the full code i have right now:
include_once(ABSPATH . WPINC . '/feed.php');
if(function_exists('fetch_feed')) {
$feed = fetch_feed('http://feeds.bbci.co.uk/news/world/africa/rss.xml'); // this is the external website's RSS feed URL
if (!is_wp_error($feed)) : $feed->init();
$feed->set_output_encoding('UTF-8'); // this is the encoding parameter, and can be left unchanged in almost every case
$feed->handle_content_type(); // this double-checks the encoding type
$feed->set_cache_duration(21600); // 21,600 seconds is six hours
$feed->handle_content_type();
$limit = $feed->get_item_quantity(18); // fetches the 18 most recent RSS feed stories
$items = $feed->get_items(0, $limit); // this sets the limit and array for parsing the feed
endif;
}
$blocks = array_slice($items, 0, 3); // Items zero through six will be displayed here
foreach ($blocks as $block) {
//echo $block->get_date("m d Y");
echo '<div class="single">';
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
echo '<div class="description">';
echo '<h3>'. $block->get_title() .'</h3>';
echo '<p>'.$block->get_description().'</p>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
}
And here are the XML pieces with 2 different tags for images:
Using Thumbnails: view-source:http://feeds.bbci.co.uk/news/world/africa/rss.xml
Using Enclosure: http://feeds.news24.com/articles/news24/SouthAfrica/rss
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Sure there is. You've not said in your question what blocks you so I have to assume the reason, but I can imagine multiple.
Is the reason a decisions with more than two alternations?
You handle the scenario of a feed item having no image or an image already:
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
With your current scenario there is only one additional alternation which makes it three: if the enclosure is a thumbnail and not a link:
No image (no enclosure)
Image from link (enclosure with link)
Image from thumbnail (enclosure with thumbnail)
And you then don't know how to create a decision of that. This is what basically else-if is for:
if (!$enclosure = $block->get_enclosure())
{
echo "no enclosure: ", "-/-", "\n";
} elseif ($enclosure->get_link()) {
echo "enclosure link: ", $enclosure->get_link(), "\n";
} elseif ($enclosure->get_thumbnail()) {
echo "enclosure thumbnail: ", $enclosure->get_thumbnail(), "\n";
}
This is basically then doing the output based on that. However if you assign the image URL to a variable, you can decide on the output later on:
$image = NULL;
if (!$enclosure = $block->get_enclosure())
{
// nothing to do
} elseif ($enclosure->get_link()) {
$image = $enclosure->get_link();
} elseif ($enclosure->get_thumbnail()) {
$image = $enclosure->get_thumbnail();
}
if (isset($image)) {
// display image
}
And if you then move this more or less complex decision into a function of it's own, it will become even better to read:
$image = feed_item_get_image($block);
if (isset($image)) {
// display image
}
This works quite well until the decision becomes even more complex, but this would go out of scope for an answer on Stackoverflow.

How do I print a barcode using barcode generator for PHP onto a pdf formatted page where I want it?

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

PHP Image not showing in HTML using img element

Hello there i have a php file with the included:
The image shows properly when i access the PHP file, however when I try to show it in the HTML template, it shows as the little img with a crack in it, so basically saying "image not found"
<img src="http://konvictgaming.com/status.php?channel=blindsniper47">
is what i'm using to display it in the HTML template, however it just doesn't seem to want to show, I've tried searching with next to no results for my specific issue, although I'm certain I've probably searched the wrong title
adding code from the OP below
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
echo "<img src='$online' />";
} else {
echo "<img src='$offline' />";
}
The url is not an image, it is a webpage with the following content
<img src='offline.png' alt='Offline' />
Webpages cannot be displayed as images. You will need to edit the page to only transmit the actual image, with the correct http-headers.
You can probably find some help on this by googling for "php dynamic image".
Specify in the HTTP header that it's a PNG (or whatever) image!
(By default they are interpreted as text/html)
in your status.php file, where you output the markup of <img src=... change it to read as follows
$image = file_get_contents("offline.png");
header("Content-Type: image/png");
echo $image;
Which will send an actual image for the request instead of sending markup. markup is not valid src for an img tag.
UPDATE your code modified below.
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
header("Content-Type: image/png");
$image = null;
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
$image = file_get_contents($online);
} else {
$image = file_get_contents($offline);
}
echo $image;
I suppose you change the picture dynmaclly on this page.
Easiest way with least changes will just be using an iframe:
<iframe src="http://konvictgaming.com/status.php?channel=blindsniper47"> </iframe>

Simple-html-dom skips attributes

I am trying to parse html page of Google play and getting some information about apps. Simple-html-dom works perfect, but if page contains code without spaces, it completely ingnores attributes. For instance, I have html code:
<div class="doc-banner-icon"><img itemprop="image"src="https://lh5.ggpht.com/iRd4LyD13y5hdAkpGRSb0PWwFrfU8qfswGNY2wWYw9z9hcyYfhU9uVbmhJ1uqU7vbfw=w124"/></div>
As you can see, there is no any spaces between image and src, so simple-html-dom ignores src attribute and returns only <img itemprop="image">. If I add space, it works perfectly. To get this attribute I use the following code:
foreach($html->find('div.doc-banner-icon') as $e){
foreach($e->find('img') as $i){
$bannerIcon = $i->src;
}
}
My question is how to change this beautiful library to get full inner text of this div?
I just create function which adds neccessary spaces to content:
function placeNeccessarySpaces($contents){
$quotes = 0; $flag=false;
$newContents = '';
for($i=0; $i<strlen($contents); $i++){
$newContents.=$contents[$i];
if($contents[$i]=='"') $quotes++;
if($quotes%2==0){
if($contents[$i+1]!== ' ' && $flag==true) {
$newContents.=' ';
$flag=false;
}
}
else $flag=true;
}
return $newContents;
}
And then use it after file_get_contents function. So:
$contents = file_get_contents($url, $use_include_path, $context, $offset);
$contents = placeNeccessarySpaces($contents);
Hope it helps to someone else.

Creating/Saving an inline base64 encoded image

I am trying to create & save images from data in an email from the base64 data of an actual image that was in the html body that appears inline such as:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAE==">
But i'm trying to create them sequentially, as there could be more than one image tag in the html body, where the variable $html_part is the html body of the email.
I just need some assistance in coming to a solution on what i'm doing wrong.
$img_tags = preg_match('/<img\s+(.*)>/', $html_part, $num_img_tags);
$num_img_tags = count($num_img_tags);
echo $html_part;
for ($i = 1; $i <= $num_img_tags; $i++) {
preg_match('/<img\s+(.*)\s+src="data:image\/(.*);(.*),(.*)"\s+(.*)>/i', $html_part, $srcMatch);
{
foreach($srcMatch[4] as $im_data)
{
$ufname = "image0".$num_img_tags.".jpg";
echo "<h1>$ufname</h1>";
$im_data = base64_decode($im_data);
$im = imagecreatefromstring($im_data);
if ($im !== false) {
header('Content-Type: image/jpeg');
imagejpeg($im, $ufname);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
}
}
}
Your code is impossible - you cannot do a header() call after you've performed ANY output. You can also not output multiple images in the same 'document'. You also cannot output html (the <h1> stuff), images (header('Content-type:...'), etc... all within the same document.
As well, parsing/processing HTML with regexes is dangerous. A single malformation of the source document and your regexes will happily feast on garbage and produce garbage for you. Do not use regexes on html... every time you do, Alan Turing kills a kitten. Use a DOM parser instead.
Pretty sure you want to use a preg_match_all, not a preg_match
http://php.net/manual/en/function.preg-match-all.php
Also, solution using the above.
<?php
$html_part=<<<END
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=">
END;
preg_match_all('/<img.*?src="data:image\/.*;.*,(.*)".*?>/i', $html_part, $img_tags, PREG_PATTERN_ORDER);
echo $html_part;
$img_num = 0;
foreach($img_tags[1] as $im_data)
{
$ufname = "image0".$img_num.".jpg";
echo "<h1>$ufname</h1>";
$im_data = base64_decode($im_data);
$im = imagecreatefromstring($im_data);
if ($im !== false) {
imagejpeg($im, $ufname);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
$img_num++;
}

Categories