Unable to output MySQL data to FPDF table - php

I've tried the tutorials on fpdf and searched all over for helpful code. And I found what I thought would do the trick here on SO. That said, following the example here didn't produce good results. I definitely need help with this.
Here's my code:
<?php
require_once '../root_login.php';
require('fpdf.php');
class PDF extends FPDF
{
// Page header
function Header()
{
// Logo
//$this->Image('images/bg_all.jpg',10,6,30);
// Arial bold 15
$this->SetFont('Times','B',20);
// Move to the right
$this->Cell(80);
// Title
$this->Cell(40,10,'B A S E B A L L',0,0,'C');
// Line break
$this->Ln(6);
// Arial bold 15
$this->SetFont('Arial','B',9);
$this->Cell(200,10,'LITTLE LEAGUE ROSTERS',0,0,'C');
$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');
}
}
// Instanciation of inherited class
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',8);
$stmt = $db->prepare('SELECT fname, lname
FROM rosters
ORDER BY lname');
$stmt->execute();
$result = $stmt->fetchALL(PDO::FETCH_ASSOC);
foreach($result as $row) {
$pdf->Cell(0,10,'F NAME:', $row['fname']);
$pdf->Ln();
$pdf->Cell(0,5,'L NAME:', $row['lname']);
$pdf->Ln();
}
$pdf->Output();
?>
You can view the output here
Does anyone see what I'm doing wrong? And why are those lines being drawn? Thanks.

In FPDF you should fully define all cell options and your text for the cell should be in the third position:
$pdf->Cell(0,5,'L NAME:'. $row['lname'], 0, 0, 'L');
------------------------^
Note the concatenation. Then follow up with the border(0 for no border, which should be the default), the next line definition (Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.) and the alignment of the text in the cell.

Joining the string and doing it with less parameters?
foreach($result as $row) {
$pdf->Cell(0,10,'F NAME: '.$row['fname']);
$pdf->Ln();
$pdf->Cell(0,5,'L NAME: '.$row['lname']);
$pdf->Ln();
}

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).

how to skip a line in a while

I'm trying to convert php into pdf with the function FPDF but I did a select on my data base and I would like to have all the element of this select in PDF:
$query="select organisme,id from client";
$resultats=$db->query($query);
$pdf=new FPDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFillColor(232,232,232);
$pdf->SetFont('Arial','B',12);
$pdf->Cell(20,6,'ID',1,0,'C',100);
$pdf->Cell(70,6,'mes organismes',1,0,'C',1);
$pdf->SetFont('Arial','',10);
while ($row = $resultats->fetch(PDO::FETCH_ASSOC))
{
$pdf->Cell(20,6,utf8_decode($row['id']),1,0,'C',1);
$pdf->Cell(70,6,$row['organisme'],1,0,'C',1);
}
$pdf->Output();
?>
But the problem is that I got the ID and organisme but I have a problem :
i would like to know how I do to skip line into all new id and organisme
Thanks
FPDF's Ln() function performs a line break.
$pdf->Ln();
Add this line below your $pdf->Cell() function calls, both for the header row and inside the while loop.

Using FPDF in an application

I have been testing with FPDF and it's going okay in terms of making the PDF.
In my application I plan to have a button that reads 'Convert to PDF' and when the user clicks it, FPDF will create the PDF in a new window using given variables.
The code to generate the PDF is like the below:
require_once("fpdf.php");
$author = "Test";
$title = "Candidate profile";
$width = 10;
$height = 10;
$text = "Test";
$font_family = 'Arial';
$font_size = 11;
$file_name = "candidate-profile-jesse-orange";
$extension = ".pdf";
$output = "I";
$heading_size = 16;
$subheading_size = 13;
class PDF extends FPDF
{
// Page header
function Header()
{
// Logo
$this->Image('logo.png',10,10,30);
// Arial bold 15
$this->SetFont('Arial','B',16);
// Move to the right
$this->Cell(50);
// Title
$this->Cell(100,8,'Candidate profile for: Jesse Orange',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(),0,0,'R');
}
}
// Create a new instance
$pdf = new PDF("P", "mm", "A4");
// Set some default options
$pdf->setAuthor($author);
$pdf->setTitle($title);
$pdf->AddPage();
$pdf->SetDisplayMode("real",'default');
$pdf->SetFont($font_family, '', $font_size);
// Field
$pdf->SetFont($font_family, 'B', $font_size);
$pdf->Cell(40, $height, "Position applied for:", 0, 0);
// Value
$pdf->SetFont($font_family, '', $font_size);
$pdf->Cell(60, $height, "Innovation Advisor (Job ID: 221)", 0, 0);
// Field
$pdf->SetFont($font_family, 'B', $font_size);
$pdf->Cell(40, $height, "Date of application:", 0, 0);
// Value
$pdf->SetFont($font_family, '', $font_size);
$pdf->Cell(50, $height, "17th July 2017", 0, 1);
$pdf->Output($file_name.$extension, $output);
On a separate page you have the output from a database query and variables for each field eg:
$name = "John";
$surname = "Smith";
Or more correctly...
$name = $row['name'];
My question is: should I post the already stored variables to a seperate script to generate the PDF or should it be on the same page?
Theoretically on button press you could call $pdf->Output();
Addition:
The variables displayed on the page are for viewing in the browser, then when a user would click convert to PDF it would simply grab these variables and use them with FPDF.
A similar example is how Google Analytics allows you to download a report as a PDF.
Given this flow:
Database values are displayed to end user
User reviews values and optionally generates the PDF files
... where the user is not allowed to edit the values (i.e. they aren't defaults but final ones), submitting them to the server does not make sense. The server already has direct access to such values, if you make them come from external sources they become untrusted input and you're forced to validate them.
Just make sure you have a reusable design so you don't need to implement the read values code twice.
In fact it's an anti-pattern I've actually seen in the wild now and then. In the worst case, it was a "Modify my profile" page that took user ID from the URL (rather than grabbing the ID of the currently validated user from session). Go figure the risk ;-)

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 :)

FPDF Header Question - Driving me crazy!

I am trying to generate a PDF that outputs Item Names onto a template PDF (using FPDI) with the Username listed on the top of each page. Every user can have a different number of items (i.e. if there are 1-4 items, only output one page; if there 5-8 items, output two pages, etc.)
Here is an example of what I am trying to do: http://www.mediafire.com/?k2ngmqm1jmm
This is what I have so far. I am able to get all of the spacing to work by setting a TopMargin, but this doesn't allow me to put the Username header in.
<?php
require_once('auth.php');
require_once('config.php');
require_once('connect.php');
$username=$_GET['username'];
$sql="SELECT * FROM $tbl_items WHERE username='$username'";
$result=mysql_query($sql);
require_once('pdf/fpdf.php');
require_once('pdf/fpdi.php');
$pdf =& new FPDI();
$pdf->SetTopMargin(30);
$pdf->AddPage('L', 'Letter');
$pdf->setSourceFile('../pdf/files/chart_template.pdf');
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->SetTextColor(0,0,0);
$pdf->SetFont('Arial', 'B');
$pdf->SetFontSize(7);
while($rows=mysql_fetch_array($result)){
$pdf->Cell(20,5,$rows['itemname'],0,0,'C');
$pdf->Ln(45);
}
$pdf->useTemplate($tplIdx);
$pdf->Output('file.pdf', 'I');
?>
Please help!
I've done it previously using the 'header' class extension:
class PDF extends FPDF
{
function Header()
{
//Select Arial bold 15
$this->SetFont('Arial','B',15);
//Move to the right
$this->Cell(80);
//Framed title
$this->Cell(30,10,'Title',1,0,'C');
//Line break
$this->Ln(20);
}
Have a look at the tutorial which explains the header usage at : http://www.fpdf.org/en/tutorial/tuto2.htm

Categories