How to display images from mysql database without overlapping, FPDF? - php

I have a problem. I write codes of to display images from mysql database to FPDF but the images are displayed as overlapping (in same position)
<?php
include("connection.php");
$que1=mysql_query("select * from TableName);
ob_start();
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
while($rw=mysql_fetch_array($que1))
{
$profile=$rw['profile'];
$pdf->Image($profile,10,'',30);
}
$pdf->Output();
ob_end_flush();
?>
How can I display my images in vertical form?
Please anyone can help me.

The problem is with line
$pdf->Image($profile,10,'',30);
The first attribute is "file", Second is the axis X position, 3rd is axis Y, fourth is width.
Refference: Documentation
Please give different x,y values to prevent overlapping

From documentation I can see that Image method take [x, y] coordinates. So just for every image calculate new position:
$currentY = 0;
while ($rw = mysql_fetch_array()) {
$imageSize = $this->getSize($rw['profile']);
$pdf->Image($profile, 10, $currentY, 30);
$currentY += $imageSize['height'];
}
OR try setting y to null - Image($profile, 10, null, 30)

Related

FPDF PHP MYSQL Text Does Not Fit In Cell

I want to export data from MySql database in pdf format. I can do this from within the mysql database, it's very nice. I tried to automate this. I used the FPDF library but the data does not fit into the tables. I searched but couldn't fix it.
What should I do ?
Images :
My Columns :
Sample Content :
My Code :
<?php
require('./fpdf/fpdf.php');
//Database
require_once __DIR__ . '/db_config.php';
$connection =
mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
if(!$connection){
die("Connection error : " . mysqli_connect_eror());
}
class PDF extends FPDF
{
// Page header
function Header()
{
$ImagePath ='image url';
// Logo
$this->Image($ImagePath,10,70,0,90);
$this->SetFont('Arial','B',13);
// Move to the right
$this->Cell(80);
// Title
$this->Cell(80,10,'title',1,0,'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer()
{
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial','I',8);
// Page number
$this->Cell(0,10,'Page '.$this-
>PageNo().'/{nb}',0,0,'C');
}
}
// Columns
$display_heading = array('JobId'=>'JobId','ReleaseDate'=>
'ReleaseDate',
'StartingDate'=>
'StartingDate','TargetTime'=>'TargetTime','JobContent'=>
'JobContent','KindId'=>'KindId','JobStatus'=>'JobStatus','CustomerId'
=>'CustomerId');
// Database Result
$result = mysqli_query($connection, "SELECT * FROM Jobs;") or die("database
error:". mysqli_error($connection));
$header = mysqli_query($connection, "SHOW columns FROM Jobs");
// Settings
$pdf = new PDF();
//header
$pdf->AddPage();
//foter page
$pdf->AliasNbPages();
$pdf->SetFont('Arial','B',8);
foreach($header as $heading) {
$pdf->Cell(24,7,$display_heading[$heading['Field']],1);
}
foreach($result as $row) {
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(24,7,$column,1);
}
$pdf->Output();
//Connection close
mysqli_close($connection);
?>
You can use GetStringWidth() to determine how many mm wide a given string in the current font configuration is. Based on that, you can decrease the font size or insert line breaks, if the string width is wider than you threshold (in your case the cell width).
$fontSize = 14;
while($pdf->GetStringWidth($text) > 80){
$pdf->setFontSize(--$fontSize);
}
You might want to take a look at the "Fix text to cell" extension at http://www.fpdf.org/en/script/script62.php. See the resulting example PDF at http://www.fpdf.org/en/script/ex62.pdf to see what it looks like.
If you don't want to compress the text like that, something along the lines of what #stui has suggested would likely work best (getting the string width, and splitting the text across multiple lines).

PHPExcel more than one image in a cell

I need to create an excel document with only 2 col. The first one will contain multiple images 150px large and the seconde one will contain a web code. For some reason only one image is added and the file appears to be currupted. Not sure what i am doing wrong ...
<?php
include("../../init.php");
if (is_numeric($_GET[groupe])){
define( 'PCLZIP_TEMPORARY_DIR', $_CONFIG['upload']['root'].'/cache' );
// filename for download
$groupe = mysql_query("SELECT * FROM photographe_groupe WHERE id='$_GET[groupe]'");
$records = "Groupe - $groupe[nom].xlsx";
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition:inline;filename='.$records);
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$i=0;
$select = mysql_query("SELECT * FROM photographe_images WHERE sid='$_GET[groupe]' group by `paire`");
while($photo = mysql_fetch_array($select)){
// Table header
if ($i=="1"){
$sheet->setCellValue("A1",'Photo(s)');
$sheet->setCellValue('B1','Code Web');
$i++;
}
// Set images in col 1
$select1 = mysql_query("SELECT * FROM photographe_images WHERE paire='$photo[paire]'");
while($photo1 = mysql_fetch_array($select1)){
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName($photo1[img]);
$objDrawing->setDescription($photo1[img]);
$objDrawing->setWorksheet($workbook->getActiveSheet());
$objDrawing->setPath($_CONFIG['upload']['root'].'/userfiles/photos/'.$photo1[img]);
$objDrawing->setWidth(150);
$objDrawing->setCoordinates('A'.$i);
}
// Set web code in col 2
$sheet->setCellValue("B$i",$photo[code_web]);
$i++;
}
}
$workbook->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$writer = new PHPExcel_Writer_Excel2007($workbook);
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$writer->save('php://output');
?>
You can download and output demo here
Just a few points to note before I try taking a look at your file:
The first point to note here is that Excel doesn't store images in cells, it "overlays" images, and doesn't particularly care where cell boundaries occur, so an image can be a fixed size irrespective of how many cells it overlays
When you specify a coordinate for a image, you're relating the top-left corner of that image to be placed at the top-left corner of that cell.... where the bottom and/or right corner of the image lies isn't determined by the cells at all. Setting the row height or column width to autosize will not be affected by the image in any way, because the image is overlaid, not a content of the cell
You can, offset the image from the top-left corner of the related cell by using the Drawing object's setOffsetX() and setOffsetY() methods.
You can link more than one image to be placed relative to the same cell's top-left corner using different offset values so they don't overlap, but you need to work out the offsets from the size of the images

FPDF Get page numbers at footer on Every A4 size page

I am creating PDF reports using FPDF. Now how do I generate page numbers on each page of a report at the bottom of the page.
Below is the sample code for generating a 2 page PDF.
<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$start_x=$pdf->GetX();
$current_y = $pdf->GetY();
$current_x = $pdf->GetX();
$cell_width = 25; $cell_height=14;
$j = 20; // This value will be coming from Database so we dont know how many pages the report is going to be
for ($i = 0; $i<$j ; $i++){
$pdf->MultiCell($cell_width,$cell_height,'Hello1',1);
$current_x+=$cell_width;
$pdf->Ln();
}
$pdf->Output();
?>
Note : The $j value will be coming from the database so we don't know how many pages is the report going to be.
To add an A4 page, with portrait orientation, do:
$pdf->AddPage("P","A4");
Create a new class which extends the FPDF class, and override the pre-defined Footer method.
Example:
class PDF extends FPDF
{
function Footer()
{
// Go to 1.5 cm from bottom
$this->SetY(-15);
// Select Arial italic 8
$this->SetFont('Arial','I',8);
// Print centered page number
$this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C');
}
}
According to my comment you can place
$pdf->PageNo();
on your page where ever you like. Also you can add a placeholder to this
$pdf->AliasNbPages();
What would look like
$pdf->AliasNbPages('{totalPages}');
By default it's {nb}. It's not necessary to add a placeholder
Than you could add the pagesum like
$pdf->Cell(0, 5, "Page " . $pdf->PageNo() . "/{totalPages}", 0, 1);
or without your own placeholder
$pdf->Cell(0, 5, "Page " . $pdf->PageNo() . "/{nb}", 0, 1);
this would produce e.g.
Page 1/10
in case there were 10 pages :)
But beware
Using the placeholder will mess up the width of the cell. So if you have e.g. 180 page-width than 90 isn't the mid anymore (In the line where you use the placeholder). You will see if you try :)

Display image in PDF using fpdf

I want to insert an image in my created PDF file. However, it won't position well at all.
If I do this:
$fpdf->Image($row_products['prod_imagelarge'], 10);
The images will appear however, they're too big.
If I do this:
$fpdf->Image($row_products['prod_imagelarge'],30, 40, 40, 40);
Not all images will appear. Only 1 image per page will appear but with
the right size.
Actually, I am inserting an image inside a while loop.
What I would want to display in the pdf file is: (in order)
-product name (works fine)
-product image (the problem is here!)
-product description (works fine)
Similar to Naveed, but a little more complete with the rest of your row data. The trick is to capture the X and Y position before placing the image and then manually set the abscissa ("position") to the proper place, given the new image.
$image_height = 40;
$image_width = 40;
while ($row_products = mysql_fetch_array($products)) {
$fpdf->Cell(0, 0, $row_products['prod_name'], 0, 2);
$fpdf->Cell(0, 0, $row_products['prod_description'], 0, 2);
// get current X and Y
$start_x = $fpdf->GetX();
$start_y = $fpdf->GetY();
// place image and move cursor to proper place. "+ 5" added for buffer
$fpdf->Image($row_products['prod_imagelarge'], $fpdf->GetX(), $fpdf->GetY() + 5,
$image_height, $image_width)
$fpdf->SetXY($start_x, $start_y + $image_height + 5);
}
If one page contains many images then may be your images are placed on each others. You should change position for each image on one page. Try something like this.
for( $i=10; $i<=200; $i=$i+10 ) {
$fpdf->Image($row_products['prod_imagelarge'],30, $i, 40, 40);
}

Dynamic GD image width text

I'm trying to spice up my website by using custom fonts for headings. For me, the most appropriate way to do this is using PHP and GD. I have written a little script which will output the dynamic text based on the $_GET value, however sometimes the image is too wide, which moves everything else about.
How can I get the image to adjust the width of it, based on the width of the text? Here is the code I've written so far:
<?php
// Settings
$sText = $_GET['t']; // Text of heading
$sFont = "font/AvantGarde-Book.ttf"; // Default font for headings
$sMain = $_GET['c'] ? $_GET['c'] : 0xF2AB27; // Get a font or default it
// Create the image
header("content-type: image/png"); // Set the content-type
$hImage = imagecreatetruecolor(200, 24);
ImageFill($hImage, 0, 0, IMG_COLOR_TRANSPARENT);
imagesavealpha($hImage, true);
imagealphablending($hImage, false);
imagettftext($hImage, 20, 0, 0, 24, $sMain, $sFont, $sText); // Draw the text
imagepng($hImage); // Generate the image
imagedestroy($hImage); // Destroy it from the cache ?>
Thanks!
Ok, I figured it out! For anyone else who may have this problem, you need to add:
// Calcuate the width of the image
$arSize = imagettfbbox(24, 0, $sFont, $sText);
$iWidth = abs($arSize[2] - $arSize[0]);
$iHeight = abs($arSize[7] - $arSize[1]);
Before the imagecreatetruecolor()
The function imagettfbbox will calculate the size of what the text will be based on the font you picked. Use the results in your call to imagecreatetruecolor.

Categories