2011-05-06 49 views
5

Estoy buscando la posibilidad de que los usuarios ingresen cierta información en un formulario y lo envíen por mail().Creación de un PDF y envío por correo electrónico

Lo que me gustaría es que los detalles se envíen como un archivo PDF adjunto. Posiblemente con el nombre del remitente y una fecha/hora. test_user_06052011.pdf

Tengo un diseño para el PDF, pero no estoy seguro de cómo integraría este diseño para crear un PDf en PHP.

¿Alguien tiene ejemplos o formas en que podría hacer esto?

+2

duplicado Posible de http://stackoverflow.com/questions/2132015/best-way-to -create-a-pdf-with-php –

+1

Bienvenido a SO, sipher_z! Por favor deja de escribir etiquetas en los títulos de las preguntas. Lo has hecho para la mayoría de tus 11 preguntas. >. < –

+0

@Tomalak Geret'kal se disculpa por las etiquetas en el título. Me aseguraré de no hacer esto en el futuro –

Respuesta

1

Tener una mirada en FPDF - http://www.fpdf.org/ - Es gratis y una gran herramienta para la generación de PDF

Hay un generador de PDF que está recomendado por PHP, sin embargo que sería muy caro y sin embargo, el nombre me elludes ahora, He usado FPDF varias veces con gran éxito.

4

Una manera muy fácil de crear un sitio de servidor PDF es usando wkhtmltopdf. Sin embargo, necesitará un acceso de shell al servidor para configurarlo.

Para crear un PDF necesita dos archivos: uno es PHP que genera HTML que desea convertir a PDF. Digamos que este es invoice.php:

<?php 
    $id = (int) $_GET['id']; 
?> 
<h1>This is invoice <?= $id ?></h1> 
<p>some content...</p> 

Y el otro, para que se capturen la factura y convertirlo en PDF utilizando wkhtmltopdf:

<?php 

$tempPDF = tempnam('/tmp', 'generated-invoice'); 
$url = 'http://yoursite.xx/invoice.php?id=123'; 

exec("wkhtmltopdf $url $tempPDF"); 

header('Content-Type: application/pdf'); 
header('Content-Disposition: attachment; filename=invoice.pdf'); 

echo file_get_contents($tempPDF); 
unlink($tempPDF); 

Una vez que haya creado un archivo PDF que también puede enviar correo con el accesorio de esta manera:

<?php 

$to = "[email protected]"; 
$subject = "mail with attachment"; 

$att = file_get_contents('generated.pdf'); 
$att = base64_encode($att); 
$att = chunk_split($att); 

$BOUNDARY="anystring"; 

$headers =<<<END 
From: Your Name <[email protected]> 
Content-Type: multipart/mixed; boundary=$BOUNDARY 
END; 

$body =<<<END 
--$BOUNDARY 
Content-Type: text/plain 

See attached file! 

--$BOUNDARY 
Content-Type: application/pdf 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment; filename="your-file.pdf" 

$att 
--$BOUNDARY-- 
END; 

mail($to, $subject, $body, $headers); 
1

Dependiendo de sus necesidades, también se puede echar un vistazo a TCPDF, lo uso mucho para crear archivos PDF sobre la marcha desde PHP ... se h como funcionalidad (limitada) de HTML a PDF incorporada y es muy fácil de usar (basta con ver los ejemplos). Y otro gran beneficio: todavía está en desarrollo activo (un poco demasiado activo para algunos, probablemente: p).

+0

TCPDF hizo el trabajo por mí, ¡gracias! –

3

Si creó un PDF rellenable con Acrobat, aquí hay una buena porción de código que lo ayudará a comenzar. Este código requiere la versión más nueva de phpmailer para funcionar, así que simplemente descárguelo y póngalo en una carpeta de clase en el mismo directorio donde puso este código. Haga que su formulario en pdf se envíe a una página con este código.

/* Branden Sueper 2012 
// PDF to Email - PHP 5 
// Includes: PHPMailer 5.2.1 
*/ 
<?php 
if(!isset($HTTP_RAW_POST_DATA)) { 
    echo "The Application could not be sent. Please save the PDF and email it manually."; 
    exit; 
} 
echo "<html><head></head><body><img src='loading.gif'>"; 

//Create PDF file with data 
$semi_rand = md5(time()); 
$pdf = $HTTP_RAW_POST_DATA; 

$file = $semi_rand . ".pdf"; 
$handle = fopen($file, 'w+'); 
fwrite($handle, $pdf); 
fclose($handle); 
// 

require_once('class/class.phpmailer.php'); 
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded 

$mail = new PHPMailer(false); // the true param means it will throw exceptions on errors, which we need to catch 

$mail->IsSMTP(); // telling the class to use SMTP 

try { 
    $mail->Host  = "mail.xxxxxxx.com"; // SMTP server 
    $mail->SMTPDebug = 2;      // enables SMTP debug information (for testing) 
    $mail->SMTPAuth = true;     // enable SMTP authentication 
    $mail->SMTPSecure = "ssl";     // sets the prefix to the servier 
    $mail->Host  = "smtp.gmail.com";  // sets GMAIL as the SMTP server 
    $mail->Port  = 465;     // set the SMTP port for the GMAIL server 
    $mail->Username = "[email protected]"; // GMAIL username 
    $mail->Password = "xxxxxxxx";   // GMAIL password 
    $mail->AddAddress('[email protected]', 'First Last'); 
    $mail->SetFrom('[email protected]', 'First Last'); 
    $mail->Subject = 'Your Subject'; 
    $mail->Body = 'Hello!'; 
    $mail->AddAttachment($file); // attachment 
    $mail->Send(); 

    //Delete the temp pdf file then redirect to the success page 
    unlink($file); 
    echo '<META HTTP-EQUIV="Refresh" Content="0; URL="success.php">';  
    exit;  
} catch (phpmailerException $e) { 
    //you can either report the errors here or redirect them to an error page 
    //using the above META tag 
    echo $e->errorMessage(); //Pretty error messages from PHPMailer 
} catch (Exception $e) { 
    echo $e->getMessage(); //Boring error messages from anything else! 
} 
    //Verify the temporary pdf file got deleted 
    unlink($file); 
?> 

PHPMailer sólo tiene que descargar PHP Mailer y ajustar el código anterior a su gusto. Para obtener más información sobre cómo crear un PDF rellenable, vaya a http://www.adobe.com/products/acrobatpro/create-fillable-pdf-forms.html

¡Buena suerte! Recuerdo pasar más de 3 días tratando de descubrir un problema muy similar.

1

No se puede encontrar la razón para usar la función nativa mail() hoy. En situaciones casi triviales podemos usar la biblioteca PHPMailer, que en el estilo OOP nos da la oportunidad de enviar correos electrónicos incluso sin entender el encabezado.La solución aun sin guardar archivo físico es

$mail = new PHPMailer(); 
... 
$doc = $pdf->Output('S'); 
$mail->AddStringAttachment($doc, 'doc.pdf', 'base64', 'application/pdf'); 
$mail->Send(); 
1

Aquí es un código completo http://codexhelp.blogspot.in/2017/04/php-email-create-pdf-and-send-with.html

/**/ 
    $mailto = $_POST['mailto']; 
    $mailfrom = $_POST['mailfrom']; 
    $mailsubject = $_POST['mailsubject']; 
    $firstname = $_POST['firstname']; 
    $lastname = $_POST['lastname']; 
    $description = $_POST['description']; 


    $description = wordwrap($description, 100, "<br />"); 
    /* break description content every after 100 character. */ 


    $content = ''; 

    $content .= ' 
<style> 
table { 
border-collapse: collapse; 
} 

table{ 
width:800px; 
margin:0 auto; 
} 

td{ 
border: 1px solid #e2e2e2; 
padding: 10px; 
max-width:520px; 
word-wrap: break-word; 
} 


</style> 

'; 
    /* you css */ 



    $content .= '<table>'; 

    $content .= '<tr><td>Mail To</td> <td>' . $mailto . '</td> </tr>'; 
    $content .= '<tr><td>Mail From</td> <td>' . $mailfrom . '</td> </tr>'; 
    $content .= '<tr><td>Mail Subject</td> <td>' . $mailsubject . '</td> </tr>'; 
    $content .= '<tr><td>Firstname</td> <td>' . $firstname . '</td> </tr>'; 
    $content .= '<tr><td>Lastname</td> <td>' . $lastname . '</td> </tr>'; 
    $content .= '<tr><td>Description</td> <td>' . $description . '</td> </tr>'; 

    $content .= '</table>'; 


    require_once('html2pdf/html2pdf.class.php'); 


    $to = $mailto; 
    $from = $mailfrom; 
    $subject = $mailsubject; 

    $html2pdf = new HTML2PDF('P', 'A4', 'fr'); 

    $html2pdf->setDefaultFont('Arial'); 
    $html2pdf->writeHTML($content, isset($_GET['vuehtml'])); 

    $html2pdf = new HTML2PDF('P', 'A4', 'fr'); 
    $html2pdf->WriteHTML($content); 


    $message = "<p>Please see the attachment.</p>"; 
    $separator = md5(time()); 
    $eol = PHP_EOL; 
    $filename = "pdf-document.pdf"; 
    $pdfdoc = $html2pdf->Output('', 'S'); 
    $attachment = chunk_split(base64_encode($pdfdoc)); 




    $headers = "From: " . $from . $eol; 
    $headers .= "MIME-Version: 1.0" . $eol; 
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol; 

    $body = ''; 

    $body .= "Content-Transfer-Encoding: 7bit" . $eol; 
    $body .= "This is a MIME encoded message." . $eol; //had one more .$eol 


    $body .= "--" . $separator . $eol; 
    $body .= "Content-Type: text/html; charset=\"iso-8859-1\"" . $eol; 
    $body .= "Content-Transfer-Encoding: 8bit" . $eol . $eol; 
    $body .= $message . $eol; 


    $body .= "--" . $separator . $eol; 
    $body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol; 
    $body .= "Content-Transfer-Encoding: base64" . $eol; 
    $body .= "Content-Disposition: attachment" . $eol . $eol; 
    $body .= $attachment . $eol; 
    $body .= "--" . $separator . "--"; 

    if (mail($to, $subject, $body, $headers)) { 

     $msgsuccess = 'Mail Send Successfully'; 
    } else { 

     $msgerror = 'Main not send'; 
    } 
Cuestiones relacionadas