Création pdf avec envoi mail (TCPDF) - PHP - Programmation
Marsh Posté le 30-07-2015 à 00:44:46
Je ne pourrai pas t'aider, mais personnellement j'ai abandonné cette librairie y'a des année par HTML2pdf, qui est très simple d'utilisation
Marsh Posté le 30-07-2015 à 09:50:42
wKhtmlToPdf (c'est un binaire qui convertit un fichier html/css en PDF direct comme une imprimante virtuelle) ou HTML2pdf : ces 2 outils sont très bien.
Marsh Posté le 30-07-2015 à 10:11:30
Bonjour !
Je suis loin d'être expert, mais le message d'erreur, couplé à cette ligne :
Code :
|
me font penser que le fichier $logo_doc doit être un fichier JPEG, avec l'extension ".jpeg", et la récupération est donc incorrecte, puisqu'elle ne prend que les 3 derniers caractères. Il faudrait, dans ce cas, utiliser une fonction plus robuste pour la récupérer
Marsh Posté le 29-07-2015 à 23:07:16
Bonjour,
http://forum-images.hardware.fr/ic [...] icon15.gif
Bonjour je planche sur la création d'un PDF avec envoi mail,
j'ai un écran blanc sous Apache avec l'erreur suivante : TCPDF error: Unsupported image type: peg
J'utilise la bibliothèque : TCPDF => Easyphp 1.2.1 (Apache + Mysql)
Merci d'avance à ceux qui pourront éclairer ma lanterne!
code source de ces fonctions :
bon_pdf.php
<?php ?>
<?php
session_cache_limiter('private');
$user=isset($_POST['user'])?$_POST['user']:"";
if ($user=='adm') {
require_once(dirname(__FILE__) . "/../include/verif.php" );
} else {
$type_verif="bon";
$num_doc=$_POST['num_bon'];
require_once(dirname(__FILE__) . "/../client/verif_client.php" );
}
$conf_xml=simplexml_load_file('../include/config.xml');
$lang=$_SESSION['lang'];
//error_reporting(0);
require_once("mysql_table.php" );
require_once("../include/config/common.php" );
require_once("../include/config/var.php" );
require_once("../include/language/$lang.php" );
require_once("entete_doc.php" );
$ratio_page=option("commandes->nb_ligne_cde" ); //nombre de ligne de commande par page
//echo $ratio_page;
$num_bon=isset($_POST['num_bon'])?$_POST['num_bon']:"";
$nom=isset($_POST['nom'])?$_POST['nom']:"";
//define('FPDF_FONTPATH','font/');
$euro= '€';
$devise = preg_replace('/€/', $euro, $devise);
/*$slogan = stripslashes($slogan);
$entrep_nom= stripslashes($entrep_nom);
$social= stripslashes($social);
$tel= stripslashes($tel);
$tva_vend= stripslashes($tva_vend);
$compte= stripslashes($compte);
$reg= stripslashes($reg);
$mail= stripslashes($mail);
*/
//on compte le nombre de ligne
$sql = "SELECT ${tblpref}cont_bon.num, quanti, uni, article, prix_htva, tot_art_htva FROM ${tblpref}cont_bon RIGHT JOIN ${tblpref}article on ${tblpref}cont_bon.article_num = ${tblpref}article.num WHERE bon_num = $num_bon";
$req = mysql_query($sql) or die("Erreur SQL !<br/>$sql2<br/>" . mysql_error());
$nb_li = mysql_num_rows($req);
$nb_pa1 = $nb_li / $ratio_page ;
$nb_pa = ceil($nb_pa1);
if ($nb_pa==0)
{
$nb_pa=1; //pour afficher les pdf vide
}
$nb_li =$nb_pa * $ratio_page ;
//pour la date
$sql = "select reference, coment, tot_htva, tot_tva, DATE_FORMAT(date,'%d/%m/%Y') AS date_2 from ${tblpref}bon_comm where num_bon = $num_bon";
$req = mysql_query($sql) or die("Erreur SQL !<br/>$sql<br/>" . mysql_error());
$data = mysql_fetch_array($req);
$date_bon = $data['date_2'];
$total_htva = $data['tot_htva'];
$total_tva = $data['tot_tva'];
$tot_tva_inc = $total_htva + $total_tva ;
$coment = $data['coment'];
$reference = $data['reference'];
//pour le nom de client
$sql1 = "SELECT mail, nom, nom2, rue, ville, cp, num_tva FROM ${tblpref}client RIGHT JOIN ${tblpref}bon_comm on client_num = num_client WHERE num_bon = $num_bon";
$req = mysql_query($sql1) or die("Erreur SQL !<br/>$sql1<br/>" . mysql_error());
$data = mysql_fetch_array($req);
$nom = $data['nom'];
$nom2 = $data['nom2'];
$rue = $data['rue'];
$ville = $data['ville'];
$cp = $data['cp'];
$num_tva = $data['num_tva'];
$mail_client = $data['mail'];
class PDF extends PDF_MySQL_Table
{
function Header()
{ }
//debut Js
var $javascript;
var $n_js;
function IncludeJS($script) {
$this->javascript=$script;
}
function _putjavascript() {
$this->_newobj();
$this->n_js=$this->n;
$this->_out('<<');
$this->_out('/Names [(EmbeddedJS) '.($this->n+1).' 0 R ]');
$this->_out('>>');
$this->_out('endobj');
$this->_newobj();
$this->_out('<<');
$this->_out('/S /JavaScript');
$this->_out('/JS '.$this->_textstring($this->javascript));
$this->_out('>>');
$this->_out('endobj');
}
function _putresources() {
parent::_putresources();
if (!empty($this->javascript)) {
$this->_putjavascript();
}
}
function _putcatalog() {
parent::_putcatalog();
if (isset($this->javascript)) {
$this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
}
}
function AutoPrint($dialog=false, $nb_impr)
{
//Ajoute du JavaScript pour lancer la boîte d'impression ou imprimer immediatement
$param=($dialog ? 'true' : 'false');
$script=str_repeat("print($param);",$nb_impr);
$this->IncludeJS($script);
}
//fin js
}
$pdf=new PDF('p','mm','a4');
$pdf->Open();
for ($i=0;$i<$nb_pa;$i++)
{
$nb = $i *$ratio_page;
$num_pa = $i;
$num_pa2 = $num_pa +1;
$pdf->AddPage();
//la date
$pdf->SetFillColor(255,238,204);
$pdf->SetFont('vera','B',10);
$pdf->SetY(4);
$pdf->SetX(135);
$pdf->MultiCell(50,6,"$lang_date: $date_bon",1,'C',1);
//le logo
$extention=substr($logo_doc, -3, 3);
$pdf->Image("../image/$logo_doc",10,8,0, 0,$extention);
/*
//Troisieme cellule le slogan
$pdf->SetFont('vera','B',15);
$pdf->SetY(45);
$pdf->SetX(10);
$pdf->MultiCell(71,4,"$slogan",0,'C',0);
*/
//deuxieme cellule les coordoné clients
$pdf->SetFont('vera','B',10);
$pdf->SetY(27);
$pdf->SetX(120);
$pdf->MultiCell(65,6,"$nom \n $nom2 \n $rue \n $cp $ville \n ",1,'C',1);
/*
//Troisieme cellule les coordonées vendeur
$pdf->SetFont('vera','B',8);
$pdf->SetY(70);
$pdf->SetX(10);
$pdf->MultiCell(40,4,"$lang_dev_pdf_soc",1,'R',1);
//le cntenu des coordonées vendeur
$pdf->SetFont('vera','',8);
$pdf->SetY(70);
$pdf->SetX(51);
$pdf->MultiCell(50,4,"$entrep_nom\n$social\n $tel\n $tva_vend \n$compte \n$mail",1,'L',1);
$pdf->Line(20,65,200,65);
*/
//$pdf->ln(10);
//premiere celule le numero de bon
$pdf->SetFont('vera','B',10);
$pdf->SetY(85);
$pdf->SetX(120);
$pdf->Cell(65,6,"$lang_num_bon_ab $num_bon",1,0,'C',1);
//cellule la tva client
$pdf->SetFont('vera','B',10);
$pdf->SetY(70);
$pdf->SetX(120);
$pdf->MultiCell(65,6,"$lang_tva: $num_tva",1,'C',1);
//$pdf->ln(5);
insere_entete();
$pdf->SetY(100);
//Référence
if ($reference != "" )
{
$pdf->SetFont('vera','',8);
//$pdf->SetY(100);
//$pdf->SetX(10);
$pdf->Cell(0,4,"Référence : $reference",0,'L',1);
}
//$pdf->ln(5);
//la grande cellule sous le tableau
$pdf->SetY(105);
$pdf->SetX(12);
$pdf->Cell(186,95,"",1,0,'C',1);
//Le tableau : on définit les colonnes
$pdf->AddCol('quanti',15,get_lang("Qte" ),'R');
if(option("lots->lot_actif" )=="oui" )
{
$pdf->AddCol('uni',10,"$lang_unite",'C');
$pdf->AddCol('article',76,"$lang_article",'C');
$pdf->AddCol('num_lot',20,"$lang_num_lot",'C');
$pdf->AddCol('taux_tva',15,get_lang("Tx tva" ),'R');
$pdf->AddCol('prix_htva',25,get_lang("Prix U. HT" ),'R');
} else {
$pdf->AddCol('uni',15,"$lang_unite",'C');
$pdf->AddCol('article',81,"$lang_article",'C');
$pdf->AddCol('taux_tva',20,get_lang("Tx tva" ),'R');
$pdf->AddCol('prix_htva',30,get_lang("Prix U. HT" ),'R');
}
$pdf->AddCol('tot_art_htva',25,get_lang("Prix HT" ),'R');
$prop=array('HeaderColor'=>array(255,150,100),'color1'=>array(255,255,210),'color2'=>array(255,238,204),'padding'=>2);
$pdf->Table("SELECT ${tblpref}cont_bon.num, num_lot, quanti, uni, article, taux_tva, prix_htva, tot_art_htva FROM ${tblpref}cont_bon RIGHT JOIN ${tblpref}article ON ${tblpref}cont_bon.article_num = ${tblpref}article.num WHERE bon_num = $num_bon LIMIT $nb, $ratio_page",$prop);
//les coordonnées vendeurs 2
/*$pdf->SetFillColor(255,238,204);
$pdf->SetFont('vera','',8);
$pdf->SetY(240);
$pdf->SetX(25);
$pdf->MultiCell(35,4,"$social\n $tel\n $tva_vend \n$compte \n$reg",0,C,0);*/
//Pour la signature
$pdf->SetFont('vera','B',10);
$pdf->SetY(230);
$pdf->SetX(100);
$pdf->MultiCell(50,10,"$lang_po_rec",1,'C',1);
//Place libre pour la signature
$pdf->SetFont('vera','B',10);
$pdf->SetY(230);
$pdf->SetX(148);
$pdf->MultiCell(40,10,"\n\n",1,'C',1);
if($num_pa2 >= $nb_pa)
{
//Quatrieme cellule les enoncés de totaux
$pdf->SetFont('vera','B',10);
$pdf->SetY(200);
$pdf->SetX(158);
$pdf->MultiCell(40,4,"$total_htva $devise\n $total_tva $devise\n $tot_tva_inc $devise",1,'R',1);
//Cinquième cellule les totaux
$pdf->SetFont('vera','B',10);
$pdf->SetY(200);
$pdf->SetX(110);
$pdf->MultiCell(48,4,"$lang_totaux",1,'R',1);
$pdf->Line(20,266,200,266);
//pour les commentaires
$pdf->SetFont('vera','',10);
$pdf->SetY(217);
$pdf->SetX(10);
$pdf->MultiCell(190,4,"$coment",0,'C',0);
}
//la derniere cellule conditions de facturation
/* $pdf->SetFont('vera','B',10);
$pdf->SetY(268);
$pdf->SetX(30);
$pdf->MultiCell(160,4,"$lang_condi",0,C,0);*/
//le nombre de page
$pdf->SetFont('vera','B',10);
$pdf->SetY(274);
$pdf->SetX(30);
$pdf->MultiCell(160,0,"$lang_page $num_pa2 $lang_de $nb_pa\n",0,'R',0);
$pdf->SetY(267);
$pdf->SetX(30);
insere_pied();
}
/*
if($_POST['mail'] =='y'){
$pdf->AddPage();
$pdf->SetFont('vera','B',10);
$pdf->SetY(10);
$pdf->SetX(30);
$pdf->MultiCell(160,4,"Conditions génerales de vente\n",0,C,0);
$pdf->SetY(70);
$pdf->SetX(10);
$pdf->MultiCell(160,4,"$lang_condi_ven",0,C,0);
}
if($_POST['mail']!='y' and $_POST['user']=='adm'){
$pdf->AutoPrint(false, $nbr_impr);
}
*/
$file="Commande $num_bon ${nom}.pdf";
//Sauvegarde du PDF dans le fichier
//
//Redirection JavaScript
//echo "<HTML><SCRIPT>document.location='$file';</SCRIPT></HTML>";
if (isset($_POST['mail']) && $_POST['mail']=='y')
{
$from = option("generale->mail" );
$soc = option("generale->nom_societe" );
$pdf->Output($file);
$to = "$mail_client";
$sujet = "Bon de commande de $soc";
$message = "Bonjour, \n\n";
$message .= "Une commande vous a été adressé par $soc.\n";
$message .= "Vous la trouverez en pièce jointe de ce mail.\n\n";
$message .= "Cordialement \n\n $soc";
require "../include/CMailFile.php";
$newmail = new CMailFile("$sujet","$to","$from","$message","$file","application/pdf" );
$newmail->sendfile();
echo "<HTML><SCRIPT>document.location='../bon_lister.php';</SCRIPT></HTML>";
unlink($file);
} else {
$pdf->Output($file,"I" ); //I permet d'afficher le pdf en flux, sans sauvegarde.
flush();
//echo "<HTML><SCRIPT>document.location='$file';</SCRIPT></HTML>";
}
?>
mysql_table.php
<?php ?>
<?php
//require_once ('ufpdf.php');
require_once ('tcpdf/tcpdf.php');
require_once (dirname(__FILE__) ."/../include/utils.php" );
//class PDF_MySQL_Table extends UFPDF
class PDF_MySQL_Table extends TCPDF
{
var $ProcessingTable=false;
var $aCols=array();
var $TableX;
var $HeaderColor;
var $RowColors;
var $ColorIndex;
function Header()
{
//Imprime l'en-tête du tableau si nécessaire
if($this->ProcessingTable)
$this->TableHeader();
}
function TableHeader()//parametre de l'entete du tableau
{
$this->SetFont('vera','B',10);
$this->SetX($this->TableX);
$fill=!empty($this->HeaderColor);
if($fill)
$this->SetFillColor($this->HeaderColor[0],$this->HeaderColor[1],$this->HeaderColor[2]);
foreach($this->aCols as $col)
$this->Cell($col['w'],6,$col['c'],1,0,'C',$fill);
$this->Ln();
}
function Row($data)
{
$this->SetX($this->TableX);
$ci=$this->ColorIndex;
$fill=!empty($this->RowColors[$ci]);
if($fill)
$this->SetFillColor($this->RowColors[$ci][0],$this->RowColors[$ci][1],$this->RowColors[$ci][2]);
foreach($this->aCols as $col)
{
$value = $data[$col['f']];
if (substr ($col['f'], 0, 4) == 'taux') $value = montant_taux ($value);
if (substr ($col['f'], 0, 2) == 'to') $value = montant_financier ($value);
if (substr ($col['f'], 0, 3) == 'p_u') $value = montant_financier ($value);
if (substr ($col['f'], 0, 3) == 'SUM') $value = montant_financier ($value);
//( (is_numeric ($value)) && (! is_int ($value) ) )
//print_r($col);
$this->Cell($col['w'],5,$value,1,0,$col['a'],$fill);
}
$this->Ln();
$this->ColorIndex=1-$ci;
}
function CalcWidths($width,$align)
{
//Calcule les largeurs des colonnes
$TableWidth=0;
foreach($this->aCols as $i=>$col)
{
$w=$col['w'];
if($w==-1)
$w=$width/count($this->aCols);
elseif(substr($w,-1)=='%')
$w=$w/100*$width;
$this->aCols[$i]['w']=$w;
$TableWidth+=$w;
}
//Calcule l'abscisse du tableau
if($align=='C')
$this->TableX=max(($this->w-$TableWidth)/2,0);
elseif($align=='R')
$this->TableX=max($this->w-$this->rMargin-$TableWidth,0);
else
$this->TableX=$this->lMargin;
}
function AddCol($field=-1,$width=-1,$caption='',$align='L')
{
//Ajoute une colonne au tableau
if($field==-1)
$field=count($this->aCols);
$this->aCols[]=array('f'=>$field,'c'=>$caption,'w'=>$width,'a'=>$align);
}
function Table($query,$prop=array())
{
//Exécute la requête
$res=mysql_query($query) or die('Erreur: '.mysql_error()."<br/>Requête: $query" );
//Ajoute toutes les colonnes si aucune n'a été définie
if(count($this->aCols)==0)
{
$nb=mysql_num_fields($res);
for($i=0;$i<$nb;$i++)
$this->AddCol();
}
//Détermine les noms des colonnes si non spécifiés
foreach($this->aCols as $i=>$col)
{
if($col['c']=='')
{
if(is_string($col['f']))
$this->aCols[$i]['c']=ucfirst($col['f']);
else
$this->aCols[$i]['c']=ucfirst(mysql_field_name($res,$col['f']));
}
}
//Traite les propriétés
if(!isset($prop['width']))
$prop['width']=0;
if($prop['width']==0)
$prop['width']=$this->w-$this->lMargin-$this->rMargin;
if(!isset($prop['align']))
$prop['align']='C';
if(!isset($prop['padding']))
$prop['padding']=$this->cMargin;
$cMargin=$this->cMargin;
$this->cMargin=$prop['padding'];
if(!isset($prop['HeaderColor']))
$prop['HeaderColor']=array();
$this->HeaderColor=$prop['HeaderColor'];
if(!isset($prop['color1']))
$prop['color1']=array();
if(!isset($prop['color2']))
$prop['color2']=array();
$this->RowColors=array($prop['color1'],$prop['color2']);
//Calcule les largeurs des colonnes
$this->CalcWidths($prop['width'],$prop['align']);
//Imprime l'en-tête
if(!isset($prop['entete']))
$this->TableHeader();
//Imprime les lignes
$this->SetFont('vera','',8); //police des lignes du tableau
$this->ColorIndex=0;
$this->ProcessingTable=true;
while($row=mysql_fetch_array($res))
{
$this->Row($row);
}
$this->ProcessingTable=false;
$this->cMargin=$cMargin;
$this->aCols=array();
}
}
?>
entete_doc.php
<?php ?>
<?php
require_once("../include/config/common.php" );
require_once("../include/utils.php" );
function insere_entete()
{
global $pdf;
global $tblpref;
$posx=10;
$posy=45;
$larg_col=45;
$sql = "SELECT * FROM ${tblpref}coordonnees WHERE ligne >= 1 AND ligne <= 7";
$result=mysql_query($sql) or die ("Erreur selection coordonnées <br/>$sql</br/>" . mysql_error());
$hauteur=0; //permet de connaitre la taille du rectangle à créer
$pdf->SetX($posx);
$pdf->SetY($posy);
while ($tab_coor=mysql_fetch_array($result))
{
$nom_1 = $tab_coor['col1_nom'];
$size_1 = $tab_coor['col1_size'];
$align_1 = $tab_coor['col1_align'];
$nom_2 = $tab_coor['col2_nom'];
$size_2 = $tab_coor['col2_size'];
$align_2 = $tab_coor['col2_align'];
//echo "$nom $size $align <br/>";
$max=max($size_1,$size_2) - 4; // besoin du max entre les 2 colonnes afin de placer la hauteur de la ligne
$pdf->SetX($posx);
$pdf->SetFont('vera','B',$size_1);
$pdf->Cell($larg_col,$max,"$nom_1",0,0,$align_1,0);
$pdf->SetX($larg_col + 9); // pas 50 ? pourtant 10 + 40 = 50 ... ben oui et pourtant 48 est mieux.
$pdf->SetFont('vera','B',$size_2);
$pdf->Cell($larg_col,$max,"$nom_2",0,1,$align_2,0);
$hauteur+=$max;
}
$pdf->rect($posx,$posy,$larg_col * 2,$hauteur);
}
function insere_pied()
{
global $pdf;
global $tblpref;
$posy=50;
$sql = "SELECT * FROM ${tblpref}coordonnees WHERE ligne >= 8 AND ligne <= 10";
$result=mysql_query($sql) or die ("Erreur selection coordonnées <br/>$sql</br/>" . mysql_error());
while ($tab_coor=mysql_fetch_array($result))
{
$nom = $tab_coor['col1_nom'];
$pdf->SetX(30);
$pdf->SetFont('vera','',7);
$pdf->Cell(160,3,"$nom",0,1,'C',0);
}
}
cmailfile.php
class CMailFile {
var $subject;
var $addr_to;
var $text_body;
var $text_encoded;
var $mime_headers;
var $mime_boundary = "--==================_846811060==_";
var $smtp_headers;
function CMailFile($subject,$to,$from,$msg,$filename,$mimetype = "application/octet-stream", $mime_filename = false) {
$this->subject = $subject;
$this->addr_to = $to;
$this->smtp_headers = $this->write_smtpheaders($from);
$this->text_body = $this->write_body($msg);
$this->text_encoded = $this->attach_file($filename,$mimetype,$mime_filename);
$this->mime_headers = $this->write_mimeheaders($filename, $mime_filename);
}
function attach_file($filename,$mimetype,$mime_filename) {
$encoded = $this->encode_file($filename);
if ($mime_filename) $filename = $mime_filename;
$out = "--" . $this->mime_boundary . "\n";
$out = $out . "Content-type: " . $mimetype . "; name=\"$filename\";\n";
$out = $out . "Content-Transfer-Encoding: base64\n";
$out = $out . "Content-disposition: attachment; filename=\"$filename\"\n\n";
$out = $out . $encoded . "\n";
$out = $out . "--" . $this->mime_boundary . "--" . "\n";
return $out;
// added -- to notify email client attachment is done
}
function encode_file($sourcefile) {
if (is_readable($sourcefile)) {
$fd = fopen($sourcefile, "r" );
$contents = fread($fd, filesize($sourcefile));
$encoded = my_chunk_split(base64_encode($contents));
fclose($fd);
}
return $encoded;
}
function sendfile() {
$headers = $this->smtp_headers . $this->mime_headers;
$message = $this->text_body . $this->text_encoded;
mail($this->addr_to,$this->subject,$message,$headers);
}
function write_body($msgtext) {
$out = "--" . $this->mime_boundary . "\n";
$out = $out . "Content-Type: text/plain; charset=\"utf-8\"\n\n";
$out = $out . $msgtext . "\n";
return $out;
}
function write_mimeheaders($filename, $mime_filename) {
if ($mime_filename) $filename = $mime_filename;
$out = "MIME-version: 1.0\n";
$out = $out . "Content-type: multipart/mixed; ";
$out = $out . "boundary=\"$this->mime_boundary\"\n";
$out = $out . "Content-transfer-encoding: 7BIT\n";
$out = $out . "X-attachments: $filename;\n\n";
return $out;
}
function write_smtpheaders($addr_from) {
$out = "From: $addr_from\n";
$out = $out . "Reply-To: $addr_from\n";
$out = $out . "X-Mailer: PHP5\n";
$out = $out . "X-Sender: $addr_from\n";
return $out;
}
}
// usage - mimetype example "image/gif"
// $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filename,$mimetype);
// $mailfile->sendfile();
// Splits a string by RFC2045 semantics (76 chars per line, end with \r\n).
// This is not in all PHP versions so I define one here manuall.
function my_chunk_split($str)
{
$stmp = $str;
$len = strlen($stmp);
$out = "";
while ($len > 0) {
if ($len >= 76) {
$out = $out . substr($stmp, 0, 76) . "\r\n";
$stmp = substr($stmp, 76);
$len = $len - 76;
}
else {
$out = $out . $stmp . "\r\n";
$stmp = ""; $len = 0;
}
}
return $out;
}
// end script
?>
Cordialement,