Related
I've been having trouble creating a PDF using FPDF with PHP. I managed to fetch the data from my database and make the headers get right, but when the data gets posted it gets all chaotic, the script first puts all results from one column before starting the rest, making the positioning get really wrong.
I am using php 7
Here is one example of how data is being shown:
Column Error 1
Error 2
I can't understand why the first column is shown with the right Y position but all the other ones get like this
Here is the code as is.
$result = $mysqli->query("SELECT * FROM `tb_login`");
$number_of_rows = mysqli_num_rows($result);
//Inicializar as colunas
$column_idlogin = "";
$column_iduser = "";
$column_nome = "";
$column_snome = "";
$column_cpf = "";
$column_email = "";
$column_datahr = "";
//Adicionar a coluna para cada linha presente
while($row = mysqli_fetch_array($result))
{
$idlogin = $row["idLogin"];
$iduser = $row["idUsuario"];
$nome = $row["nmUsuario"];
$snome = $row["sobrenomeUsuario"];
$cpf = $row["cpfUsuario"];
$email = $row["emailUsuario"];
$datahr = $row["data_hora"];
$column_idlogin = $column_idlogin.$idlogin."\n";
$column_iduser = $column_iduser.$iduser."\n";
$column_nome = $column_nome.$nome."\n";
$column_snome = $column_snome.$snome."\n";
$column_cpf = $column_cpf.$cpf."\n";
$column_email = $column_email.$email."\n";
$column_datahr = $column_datahr.$datahr."\n";
}
$mysqli -> close();
//Create a new PDF file
$pdf=new FPDF();
$pdf->AddPage();
//Fields Name position
$Y_Fields_Name_position = 12;
//Table position, under Fields Name
$Y_Table_Position = 24;
//First create each Field Name
//Gray color filling each Field Name box
$pdf->SetFillColor(232,232,232);
//Bold Font for Field Name
$pdf->SetFont('Arial','B',10);
$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(20);
$pdf->Cell(18,12,'ID_LOGIN',1,0,'L',1);
$pdf->SetX(38);
$pdf->Cell(18,12,'ID_USER',1,0,'L',1);
$pdf->SetX(56);
$pdf->Cell(20,12,'NOME',1,0,'C',1);
$pdf->SetX(76);
$pdf->Cell(28,12,'SOBRENOME',1,0,'C',1);
$pdf->SetX(104);
$pdf->Cell(30,12,'CPF',1,0,'C',1);
$pdf->SetX(134);
$pdf->Cell(30,12,'EMAIL',1,0,'C',1);
$pdf->SetX(164);
$pdf->Cell(34,12,'DATA_ACESSO',1,0,'C',1);
$pdf->Ln();
//Agora mostre as colunas
$pdf->SetFont('Arial','',10);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(20);
$pdf->MultiCell(18,12,$column_idlogin,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(38);
$pdf->MultiCell(18,12,$column_iduser,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(56);
$pdf->MultiCell(20,12,$column_nome,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(76);
$pdf->MultiCell(28,12,$column_snome,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(104);
$pdf->MultiCell(30,12,$column_cpf,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(134);
$pdf->MultiCell(30,12,$column_email,1);
$pdf->SetY($Y_Table_Position);
$pdf->SetX(164);
$pdf->MultiCell(34,12,$column_datahr,1);
$pdf->Output()
I tried declaring Sety as $Y_Table_Position for each column, but it doesn't seem to work.
I never used this library and didn't test this code so take it with a grain of salt.
I used your one cell working example and tried to iterate on it.
I cleaned up a bit of your code.
That while loop was strange.
//Create a new PDF file
$pdf=new FPDF();
$pdf->AddPage();
//First create each Field Name
//Gray color filling each Field Name box
$pdf->SetFillColor(232,232,232);
//Bold Font for Field Name
$pdf->SetFont('Arial','B',10);
$pdf->SetY(12);
$pdf->SetX(20);
$pdf->Cell(18,12,'ID_LOGIN',1,0,'L',1);
$pdf->SetX(38);
$pdf->Cell(18,12,'ID_USER',1,0,'L',1);
$pdf->SetX(56);
$pdf->Cell(20,12,'NOME',1,0,'C',1);
$pdf->SetX(76);
$pdf->Cell(28,12,'SOBRENOME',1,0,'C',1);
$pdf->SetX(104);
$pdf->Cell(30,12,'CPF',1,0,'C',1);
$pdf->SetX(134);
$pdf->Cell(30,12,'EMAIL',1,0,'C',1);
$pdf->SetX(164);
$pdf->Cell(34,12,'DATA_ACESSO',1,0,'C',1);
$pdf->Ln();
//Agora mostre as colunas
$pdf->SetFont('Arial','',10);
$result = $mysqli->query("SELECT * FROM `tb_login`");
$number_of_rows = mysqli_num_rows($result);
//Lets just create array of rows first
$rows = [];
while($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
/**
* Custom cell width config
*/
$cells_config_arr = [
'idLogin' => ['x' => 20],
'idUsuario' => ['x' => 20],
'nmUsuario' => ['x' => 20],
'sobrenomeUsuario' => ['x' => 20],
'cpfUsuario' => ['x' => 20],
'emailUsuario' => ['x' => 20],
'data_hora' => ['x' => 20]
];
$cell_y = 24;
foreach($rows as $row){
$cell_x = 0;
foreach($row as $key => $value){
//Lets set coord of by with of last cells sumed
$cell_x = $cell_x + $cells_config_arr[ $key ]['x'];
$pdf->SetY($cell_y);
$pdf->SetX($cell_x);
$pdf->Cell($cells_config_arr[ $key ]['x'], 12, $value, 1, 0, 'L', 1);
}
$pdf->Ln();
$cell_y = $cell_y + $cell_y;
}
$pdf->Output();
I have a html form which sends the answers onto a pdf document. Everything is working fine but I would like the questions to be on the pdf document as well.
currently it looks like this on the pdf:
Jurgen
Yes
No
4
No
I would like it to be:
Name: Jurgen
Do you own a vehicle? Yes
etc
(SOLVED)
my current code for the fpdf file:
<?php
class PDF extends FPDF
{
// Page header
function Header()
{
// Logo
$this->Image('images/logo.png', 10, 6, 30);
$this->SetFont('Arial', 'B', 15);
$this->Cell(50);
$this->Cell(90, 10, 'Document Title', 'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial', 'I', 8);
$this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
}
}
?>
<?php
//set the question values
$questions = array(
'name' => "Name: ",
'date' => "Date: ",
'first' => "First Day of Leave: ",
'last' => "Last Day of Leave: ",
'days' => "Number of Days Taken: ",
'email' => "Managers Email: ",
'sig' => "Signed: ",
);
//set the question answers
$date = $_POST['date'];
$first = $_POST['first'];
$last = $_POST['last'];
$days = $_POST['days'];
$email = $_POST['email'];
$sig = $_POST['sig'];
$name = $_POST['name'];
//set the question names
$questionName = $questions['name'];
$questionDate = $questions['date'];
$questionFirst = $questions['first'];
$questionLast = $questions['last'];
$questionDays = $questions['days'];
$questionEmail = $questions['email'];
$questionSig = $questions['sig'];
//Create the PDF
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
//insert questions and answers
$pdf->MultiCell(150,10,sprintf("%s %s", $questionDate, $date));
$pdf->Ln();
$pdf->MultiCell(150,10,sprintf("%s %s", $questionName, $name));
$pdf->Ln();
$pdf->MultiCell(150,10,sprintf("%s %s", $questionFirst, $first));
$pdf->Ln();
$pdf->MultiCell(150,10,sprintf("%s %s", $questionLast, $last));
$pdf->Ln();
$pdf->MultiCell(150,10,sprintf("%s %s", $questionDays, $days));
$pdf->Ln();
$pdf->MultiCell(150,10,sprintf("%s %s", $questionEmail, $email));
$pdf->Ln();
$pdf->MultiCell(50,10,sprintf("%s %s", $questionSig, $sig));
//display pdf
$pdf->Output();
I am still learning about FPDF since their documentation isn't the best. If I have made some mistakes please let me know. Thank you
To do so you can have your question in an associative array where the key matches with name attribute in your html form.
form.html
<form action="your_post.php" method="POST">
<!-- Your first question about age -->
<label>
What's your name?
<input name="name" type="text" />
</label>
<!-- Your second question -->
<label>
How old are you ?
<input name="yo" type="text" />
</label>
<input type="submit" />
</form>
your_post.php
<?php
$questions = array(
'name' => "What's your name?",
'yo' => 'How old are you?'
);
//Get you question and answer about name
$name = $_POST['name'];
$questionName = $questions['name'];
//You can of course use a foreach through $_POST to get every question
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
//Here concatenate $questionName and $name
$pdf->MultiCell(40,10,sprintf("%s %s", $questionName, $name));
$pdf->Output();
i can't help you with that explicit question, but i had to write a script a few days ago, which also creates a pdf.
I found a very nice tool to do this, which i decided to use instead of fpdf. It directly converts html code to a pdf. (you can also link css into it) maybe this can be also interesting for you.
https://github.com/spipu/html2pdf
This should do
<?php
$pdf = new PDF();
$pdf->Cell(20, 10, 'Name : ' . $name . '');
$pdf->Ln();
$pdf->cell(20, 10, 'Do you own a vehicle? : ' . $question1);
$pdf->Ln();
$pdf->Output();
?>
adding header, the problem you facing now
<?php
class PDF extends FPDF
{
// Page header
function Header()
{
// Logo
$this->Image('images/logo.png', 10, 6, 30);
$this->SetFont('Arial', 'B', 15);
$this->Cell(50);
$this->Cell(90, 10, 'Document Title', 'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial', 'I', 8);
$this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
}
}
?>
Update this is how your final code should look
<?php
//set the question values
$questions = array(
'name' => "Name: ",
'date' => "Date: ",
'first' => "First Day of Leave: ",
'last' => "Last Day of Leave: ",
'days' => "Number of Days Taken: ",
'email' => "Managers Email: ",
'sig' => "Signed: "
);
//set the question answers
$date = $_POST['date'];
$first = $_POST['first'];
$last = $_POST['last'];
$days = $_POST['days'];
$email = $_POST['email'];
$sig = $_POST['sig'];
$name = $_POST['name'];
//set the question names
$questionName = $questions['name'];
$questionDate = $questions['date'];
$questionFirst = $questions['first'];
$questionLast = $questions['last'];
$questionDays = $questions['days'];
$questionEmail = $questions['email'];
$questionSig = $questions['sig'];
//Create the PDF
require('fpdf.php');
class PDF extends FPDF
{
// Page header
function Header()
{
// Logo
$this->Image('images/logo.png', 10, 6, 30);
$this->SetFont('Arial', 'B', 15);
$this->Cell(50);
$this->Cell(90, 10, 'Document Title', 'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial', 'I', 8);
$this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
}
}
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
//insert questions and answers
$pdf->MultiCell(150, 10, sprintf("%s %s", $questionDate, $date));
$pdf->Ln();
$pdf->MultiCell(150, 10, sprintf("%s %s", $questionName, $name));
$pdf->Ln();
$pdf->MultiCell(150, 10, sprintf("%s %s", $questionFirst, $first));
$pdf->Ln();
$pdf->MultiCell(150, 10, sprintf("%s %s", $questionLast, $last));
$pdf->Ln();
$pdf->MultiCell(150, 10, sprintf("%s %s", $questionDays, $days));
$pdf->Ln();
$pdf->MultiCell(150, 10, sprintf("%s %s", $questionEmail, $email));
$pdf->Ln();
$pdf->MultiCell(50, 10, sprintf("%s %s", $questionSig, $sig));
//display pdf
$pdf->Output();
Currently I am working on opencart. And I have to display data in pdf for that I use FPDF.
my function looks like
public function exportPDF(){
require_once(DIR_SYSTEM . 'lib/fpdf.php');
$pdf = new fpdf();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
$category_id = $this->request->get['id'];
$this->load->model('catalog/product');
$this->load->model('tool/image');
$temp_data = $this->model_catalog_product->getProductscsv($category_id);
foreach($temp_data as $data)
{
if ($data['image']) {
$image = $this->model_tool_image->resize($data['image'], 178, 276);
} else {
$image = $this->model_tool_image->resize('placeholder.png', 178, 276);
}
$data2[] = array(
'product_id' =>$data['product_id'],
'model' =>$data['model'],
'name' =>$data['name'],
'price' =>$data['price'],
'image' =>$image,
);
}
$row = array();
$pdf->SetFont('Arial','',12);
$pdf->Ln();
$pdf->Cell(35,10,'id',1);
$pdf->Cell(35,10,'model',1);
$pdf->Cell(35,10,'name',1);
$pdf->Cell(35,10,'price',1);
$pdf->Cell(35,10,'image',1);
foreach($data2 as $row)
{
$pdf->SetFont('Arial','',10);
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(35,50,$column,1);
}
$pdf->Output();
}
And current output pdf looks like:
My need is I need to display the images in image column instead of link. how can it make possible. I am new to this, and trying for long time.
How to use $pdf->Image(); in the $data2 array. How to display images in image column in the pdf.
Try this,
foreach($data2 as $row)
{
$pdf->SetFont('Arial','',10);
$pdf->Ln();
foreach($row as $key=>$column)
{
if($key == "image"){
$pdf->Cell(35,50,$this->Image($column,$this->GetX(),$this->GetY()),1);
}else{
$pdf->Cell(35,50,$column,1);
}
}
}
and also read this : reference
Try this code
$this->Cell( 35,10, $pdf->Image($image, $pdf->GetX(), $pdf->GetY()), 0, 0, 'L', false );
I create a form letter from an order table. Each order can have either 1 or 2 pages. The PDF contains all orders. Now I want to put the page numbers for every order on the PDF.
First Order: Pages 1 and 2,
Second Order: Page 3,
Third Order: Page 4.
The number of pages depends on how many articles a customer ordered (max 2 pages).
PageNo() uses the whole document for numbering. Maybe someone had the same problem?
The expected result can be achieved by subclassing FPDF's FPDF class, and adding an $orderPageNo property to keep track of the current order's "sub-page number". You can then use that property in your customized Header or Footer method.
Example:
<?php
require('fpdf/fpdf.php');
class PDF extends FPDF {
protected $orderNumber, $orderPageNo;
function AcceptPageBreak() {
$accept = parent::AcceptPageBreak();
if ($accept) {
$this->orderPageNo++;
}
return $accept;
}
function Header() {
$this->Cell(50, 30, 'Order #'.$this->orderNumber);
$this->Cell(50, 30, 'Page '.$this->orderPageNo, 0, 1);
}
function Order($orderNumber, $items) {
$this->orderNumber = $orderNumber;
$this->orderPageNo = 1;
$this->AddPage();
for ($i = 1; $i <= $items; $i++) {
$this->Cell(30, 12, 'Item #'.$i, 1, 1);
}
}
}
$pdf = new PDF();
$pdf->SetFont('Arial', '', 12);
$orders = array(1 => 15, 2 => 25, 3 => 35);
foreach ($orders as $orderNumber => $items) {
$pdf->Order($orderNumber, $items);
}
$pdf->Output();
I am currently using FPDF to output data into a table, however i am running into issues with table cell wrapping.
My current table function is below:
function ImprovedTableCol2($header, $data, $cols ,$colWidth1, $colWidth2, $tableHeader, $closeTable, $fontSize, $icon)
{
// Table Header
if ($tableHeader==true) {
$this->SetFontSize(12);
$this->Cell(90,7,$header[0],1,0,'L');
$this->Cell(90,7,$header[1],1,0,'L');
$this->Ln();
}
// Table body
$this->SetFontSize($fontSize);
$this-> MultiCell(90,6,$data[0],'LRB');
$this->MultiCell(90,6,$data[1],'LRB');
$this->Ln();
}
My table page is as follows:
$pdf->AddPage();
$pdf->SetFont('Arial','B');
$pdf->SetFontSize(18);
$pdf->Cell(0,10,'Method Statement','B',1,'L');
$pdf->SetFont('');
$pdf->SetFontSize(10);
$pdf->Ln();
$header = array('', '');
$intTotalSCRows = "{method_statement:total_rows}";
$arrSafetyCheck = array();
array_push($arrSafetyCheck, array(
"day" => "{method_statement:day}",
"statement" => "{method_statement:statement}",
"engineer" => "{method_statement:engineer}",
"count" => "{method_statement:count}")
);
foreach ($arrSafetyCheck as $key => $list) {
if ($list['count']=="1") {
$data = array(utf8_decode($list['day']), $list['statement']);
$pdf->ImprovedTableCol2($header,$data,2,130,50,true,false,9,false);
} else if ($list['count']==$intTotalSCRows) {
$data = array(utf8_decode($list['day']), $list['statement']);
$pdf->ImprovedTableCol2($header,$data,2,130,50,false,true,9,false);
} else {
$data = array(utf8_decode($list['day']), $list['statement']);
$pdf->ImprovedTableCol2($header,$data,2,130,50,false,false,9,false);
}
}
The MultiCell function does wrap the text, but i cannot get the 2 table columns to sit side by side.
You will need to manually set the position of the cell (see the updated method below)
function ImprovedTableCol2($header, $data, $cols ,$colWidth1, $colWidth2, $tableHeader, $closeTable, $fontSize, $icon)
{
// Table Header
if ($tableHeader==true) {
$this->SetFontSize(12);
$this->Cell(90,7,$header[0],1,0,'L');
$this->Cell(90,7,$header[1],1,0,'L');
$this->Ln();
}
// Table body
$this->SetFontSize($fontSize);
// Get X,Y coordinates
$x = $this->GetX();
$y = $this->GetY();
$this->MultiCell(90,6,$data[0],'LRB');
// update the X coordinate to account for the previous cell width
$x += 90;
// set the XY Coordinates
$this->SetXY($x, $y);
$this->MultiCell(90,6,$data[1],'LRB');
$this->Ln();
}