Page 1 of 1

Create PDF from an item (FPDF)

Posted: 2019-10-27 17:29
by mghielmi
Hi, a quick example for export an item in PDF (I use in my CRM).

Difficulty: ****

Useful Links and Tips
  • Item who you can found in this post code is the name of tours table name, check before use!
File changed and added
  • Add in hook a folder "includes" and inside a folder "pdf" with fpdfh.php and font from FPDF.
  • In your /hook folder add a new file as item-dv.js and add a new button who point at a new PHP file (complete code before use).

Code: Select all

function create_pdf() {
	var template = option.toLowerCase().replace(/\s/g, '_') + ".php";
	window.location = "hooks/includes/pdf/pdf.php?id=" + selected_id;
}

$j(function() { 
        var selected_id = $j('[name=SelectedID]').val();
        
	$j('#Item_dv_action_buttons .btn-toolbar').append(
		'<p></p><div class="btn-group-vertical btn-group-lg" style="width: 100%;">' +
			'<button type="button" class="btn btn-default btn-lg" onclick="create_pdf()">' +
			'<i class="glyphicon glyphicon-print"></i> Create PDF</button>' +
		'</div>'
	);
});
  • Add in /hook/includes/pdf/ a new file called pdf.php with this code (you must change for your use, check FPDF doc).

Code: Select all

<?php

	include(dirname(__FILE__) . '/../../../lib.php');
	require(dirname(__FILE__) . 'fpdfh.php');


	/* grant access to the groups 'Admins' and 'Editor' */
	$mi = getMemberInfo();
		if(in_array($mi['group'], array('Admins', 'Editor'))){
		$id = max(0, intval($_REQUEST['id']));
		if(!$id){
			header('Location: ' . PREPEND_PATH . 'Item_view.php');
			exit;
		}

		$results = print_item_query($id);

		$pdf = new PDF_HTML();
		$pdf->AddPage();
		$pdf->SetFont('Times','B',14);
		$pdf->Cell(0,10,'Item: '. $results['id'],1,1);
		$pdf->Cell(0,10,'Description: '. $results['description'],1,1);
		$pdf->Output();
		exit;
	}

Re: Create PDF from an item (FPDF)

Posted: 2021-03-31 14:08
by pasbonte
hello
I can't make this button, I do everything that is written and impossible well.

GOOD: Create PDF from an item (FPDF)

Posted: 2021-04-07 09:02
by pasbonte
Bonjour
J'ai enfin réussi.

Voici la mode d'emploi:
Bien mettre la librairie FPDF sur votre serveur, fpdf.php à la racine

et voici le code:

Code: Select all

<?php
// Connexion à la BDD (à personnaliser)
$host_name = 'xxxxxxx';
	$database = 'xxxxxxx';
	$user_name = 'xxxxxxx';
	$password = 'xxxxxxxxxxx';

$link = new mysqli($host_name, $user_name, $password, $database);
// Si base de données en UTF-8, utiliser la fonction utf8_decode pour tous les champs de texte à afficher
$id = $_REQUEST["SelectedID"];
// extraction des données à afficher dans le sous-titre (nom du voyageur et dates de son voyage)

$requete = 'SELECT * FROM DEBIT_HSE WHERE id ='.$id;
$result = mysqli_query($link, $requete);
// tableau des résultats de la ligne > $data_HSE['nom_champ']
$data_HSE = mysqli_fetch_array($result);
mysqli_free_result($result);

// Appel de la librairie FPDF
//require("fpdf/fpdf.php");
require('xxxxxxx/fpdf/fpdf.php');
// Création de la class PDF
class PDF extends FPDF {
	// Header
	function Header() {
		// Logo : 8 >position à gauche du document (en mm), 2 >position en haut du document, 80 >largeur de l'image en mm). La hauteur est calculée automatiquement.
		$this->Image('xxxxxx.png',8,2);
		 //Saut de ligne 20 mm;
		$this->Ln(20);

		// Titre gras (B) police Helbetica de 11
		$this->SetFont('Helvetica','B',11);
		// fond de couleur gris (valeurs en RGB)
		$this->setFillColor(230,230,230);
 		// position du coin supérieur gauche par rapport à la marge gauche (mm)
		$this->SetX(70);
		// Texte : 60 >largeur ligne, 8 >hauteur ligne. Premier 0 >pas de bordure, 1 >retour à la ligneensuite, C >centrer texte, 1> couleur de fond ok	
		$this->Cell(60,8,'GESTION HSE',0,1,'C',1);
		// Saut de ligne 10 mm
		$this->Ln(10);		
	}
	// Footer
	function Footer() {
		// Positionnement à 1,5 cm du bas
		$this->SetY(-15);
		// Police Arial italique 8
		$this->SetFont('Helvetica','I',9);
		// Numéro de page, centré (C)
		$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
	}
}


// On active la classe une fois pour toutes les pages suivantes
// Format portrait (>P) ou paysage (>L), en mm (ou en points > pts), A4 (ou A5, etc.)
$pdf = new PDF('P','mm','A4');

// Nouvelle page A4 (incluant ici logo, titre et pied de page)
$pdf->AddPage();
// Polices par défaut : Helvetica taille 9
$pdf->SetFont('Helvetica','',9);
// Couleur par défaut : noir
$pdf->SetTextColor(0);
// Compteur de pages {nb}
$pdf->AliasNbPages();


// Sous-titre calées à gauche, texte gras (Bold), police de caractère 11
$pdf->SetFont('Helvetica','B',11);
// couleur de fond de la cellule : gris clair
$pdf->setFillColor(230,230,230);
// Cellule avec les données du sous-titre sur 2 lignes, pas de bordure mais couleur de fond grise
//$pdf->Cell(75,6,'DU '.$data_voyageur['date_deb'].' AU '.$data_voyageur['date_fin'],0,1,'L',1);		
$pdf->Cell(75,6,strtoupper(utf8_decode($data_HSE['PRENOM'].' '.$data_HSE['NOM'])),0,1,'L',1);				
$pdf->Ln(10); // saut de ligne 10mm	



// Fonction en-tête des tableaux en 3 colonnes de largeurs variables
function entete_table($position_entete) {
	global $pdf;
	$pdf->SetDrawColor(183); // Couleur du fond RVB
	$pdf->SetFillColor(221); // Couleur des filets RVB
	$pdf->SetTextColor(0); // Couleur du texte noir
	$pdf->SetY($position_entete);
	// position de colonne 1 (10mm à gauche)	
	$pdf->SetX(10);
	$pdf->Cell(60,8,'Ville',1,0,'C',1);	// 60 >largeur colonne, 8 >hauteur colonne
	// position de la colonne 2 (70 = 10+60)
	$pdf->SetX(70); 
	$pdf->Cell(60,8,'Pays',1,0,'C',1);
	// position de la colonne 3 (130 = 70+60)
	$pdf->SetX(130); 
	$pdf->Cell(30,8,'Repas',1,0,'C',1);

	$pdf->Ln(); // Retour à la ligne
}
// AFFICHAGE EN-TÊTE DU TABLEAU
// Position ordonnée de l'entête en valeur absolue par rapport au sommet de la page (60 mm)
$position_entete = 70;
// police des caractères
$pdf->SetFont('Helvetica','',9);
$pdf->SetTextColor(0);
// on affiche les en-têtes du tableau
entete_table($position_entete);



mysqli_free_result($result2);


// Nouvelle page PDF
$pdf->AddPage();
// Polices par défaut : Helvetica taille 9
$pdf->SetFont('Helvetica','',11);
// Couleur par défaut : noir
$pdf->SetTextColor(0);
// Compteur de pages {nb}
$pdf->AliasNbPages();
$pdf->Cell(500,20,utf8_decode('Plus rien à vous dire ;-)'));


$pdf->Output('test.pdf','I'); // affichage à l'écran
// Ou export sur le serveur
// $pdf->Output('F', '../test.pdf');
?>




Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 09:41
by jsetzer
Very well done, congrats!

A few small tipps for more security and perhaps for better future-compatibility:

(1) How to simply get exactly one record

Instead of...

Code: Select all

$requete = 'SELECT * FROM DEBIT_HSE WHERE id ='.$id;
$result = mysqli_query($link, $requete);
// tableau des résultats de la ligne > $data_HSE['nom_champ']
$data_HSE = mysqli_fetch_array($result);
mysqli_free_result($result);
...just use getRecord("TABLENAME", PK) function:

Code: Select all

$data_HSE = getRecord("DEBIT_HSE", $id);


(2) Protect against SQL-injection

For security-reasons, instead of ...

Code: Select all

$id = $_REQUEST["SelectedID"];
...escape the passed-over parameter (otherwise users are able to inject malicious SQL commands)

Code: Select all

$id = isset($_REQUEST["SelectedID"]) ? makeSafe($_REQUEST["SelectedID"]) : null;

...and finally ...

(3) check if the record exists

If the record does not exist, you should not render a PDF but for example throw an exception:

Code: Select all

if (!$data_HSE) throw new Exception("Record not found", 1);
or

Code: Select all

if (!$data_HSE) die("Record not found");

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 10:05
by pasbonte
Merci pour les conseils je corrigé je reposte.

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 13:40
by jsetzer
include(dirname(__FILE__) . '/../../../lib.php');
You have to include lib.php which is in root directory of your app.
In your first post in this thread (see above) you already did it correctly.

PS: OK, I have seen that you have deleted the previous post which I was refering to.
So I guess you have fixed the bug by yourself. :P

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 13:50
by pasbonte
..

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 13:56
by pasbonte
include (dirname (__ FILE__). '/xxx/homepages/18/xxxxxxx/LOG/lib.php');

le FILE ?

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:03
by pasbonte
J'ai mis un include
ok
require('/kunden/homepages/18/xxxxxx/htdocs/LOG/lib.php');
j'ai encore un petit soucis
$id ne passe plus, je cherche..

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:10
by jsetzer
Sorry, I don't speak French. Can you use Google Translate or Deepl for example and ask your questions in English, please?

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:15
by pasbonte
sorry
include it's ok

I still have a little problem
$id doesn't pass anymore, I'm looking for ..

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:18
by jsetzer
Check the passed in parameters:

Code: Select all

var_dump($_REQUEST);
$id = isset($_REQUEST["SelectedID"]) ? makeSafe($_REQUEST["SelectedID"]) : null;
var_dump($id);
exit();

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:21
by pasbonte
array(2) { ["SelectedID"]=> string(2) "36" ["PONSARD"]=> string(32) "eeafd255b3b9e9e7e6ce678305b71ccb" } string(2) "36"
good 36
it's after i think

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:26
by pasbonte
it's new to me, I'm more classic ...
getRecord ..

Code: Select all

// Si base de données en UTF-8, utiliser la fonction utf8_decode pour tous les champs de texte à afficher
//$id = $_REQUEST["SelectedID"];
//var_dump($_REQUEST);
//$id = isset($_REQUEST["SelectedID"]) ? makeSafe($_REQUEST["SelectedID"]) : null;
//var_dump($id);
//exit();

$id = isset($_REQUEST["SelectedID"]) ? makeSafe($_REQUEST["SelectedID"]) : null;

// extraction des données à afficher dans le sous-titre (nom du voyageur et dates de son voyage)
$data_HSE = getRecord("DEBIT_HSE", $id);
//$requete = 'SELECT * FROM DEBIT_HSE WHERE id ='.$id;
//$result = mysqli_query($link, $requete);

// tableau des résultats de la ligne > $data_voyageur['nom_champ']
$data_HSE = mysqli_fetch_array($result);
mysqli_free_result($result);

PS: les librairies JavaScript fonctionnent bien ! merci !

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:42
by jsetzer
Don't mix up your mysqli functions with built-in AppGini functions. It is not necessary to use mysqli function directly! You can use getRecord(), sql(), sqlValue() for example. Those functions already use the configured database, so there is no need to setup connection parameters.

Code: Select all


// include lib.php here
// include required pdf library here

$id = isset($_REQUEST["SelectedID"]) ? makeSafe($_REQUEST["SelectedID"]) : null;
$data_HSE = $id ? getRecord("DEBIT_HSE", $id) : null;

// just for testing purposes ------>
// if you have verified that correct parameters
// have been passed in here, 
// you can remove this whole section
// up to the arrow <------ below
// print out the passed in parameters
var_dump($_REQUEST);
var_dump($id);
var_dump($data_HSE);
exit();
// <------

$pdf = new PDF('P','mm','A4');
// ... your code for pdf creation here ...

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 14:49
by pasbonte
oops I just understood an important trick!
APPGINI is a language on its own.
thank you thank you, I will study it all !!
it's OK !

merci !

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 15:05
by jsetzer
AppGini is not a programming language but it gives us many, many functions, also written in PHP, which encapsulate a whole bunch of logic inside. We all can just use them "as is" instead of (re-) implementing all that code behind.

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 16:31
by pasbonte
Yes bad term on my part, but where do you find the help to see, work on all this, I have browsed the site I can not find.
Eg GetRecord

Re: Create PDF from an item (FPDF)

Posted: 2021-04-07 17:25
by jsetzer
(1) Did you take the UDEMY course? That was very helpful for me in the very beginning.
https://www.udemy.com/course/customizin ... lications/

(2) AppGini documentation
https://bigprof.com/appgini/help

(2.1) Custom pages
https://bigprof.com/appgini/help/advanc ... cess-pages

(2.2) Hooks
https://bigprof.com/appgini/help/advanced-topics/hooks

Additionally, if you want to customize the generated "out-of-the-box" application, it is helpful to have programming skills and some basic knowledge of PHP, SQL, a little bit of Javascript (+JQuery), HTML and CSS. It helps.

Re: Create PDF from an item (FPDF)

Posted: 2022-04-04 22:30
by rpierce
I sure wish I understood all of this. I want to print a PDF.

Re: Create PDF from an item (FPDF)

Posted: 2022-04-08 13:15
by xbox2007
hello
please check this post

viewtopic.php?f=8&t=4702

thanks a lot