簡體   English   中英

使用 TCPDF 發送 email 附件

[英]sending an email attachment using TCPDF

PHP 我有一個簡單的課程申請表,填寫后,一個 email 將發送給申請人,其中包含他選擇的課程的費用報價作為 pdf 附件。

我正在使用 TCPDF,並使用 session 變量將數據從表單傳遞到庫。 內容為 html 格式。

PDF 是根據需要生成並作為附件發送的,問題是它是空白的。文檔中只有 header 和頁腳。 在 linux 中尤其如此。 在 windows 中,pdf 文檔在下載時按預期生成。 但是,當您在下載文檔之前單擊“查看”時,只會顯示 header 和頁腳。

這是我的代碼。 請有人幫忙。 謝謝你。

<?php
session_start();
require_once('../config/lang/eng.php');
require_once('../tcpdf.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Josiah Njuki');
$pdf->SetTitle('Quotation Request');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, '', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

//set some language-dependent strings
$pdf->setLanguageArray($l);

// ---------------------------------------------------------

// set default font subsetting mode
$pdf->setFontSubsetting(true);

// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);

// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();

// Set some content to print
$html = '<span style="font-size:7pt;">' . $_SESSION['content'] . '</span>';
$html .= <<<EOD
EOD;

// Print text using writeHTMLCell()
$pdf->writeHTMLCell($w=0, $h=0, $x='', $y='', $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true);

// ---------------------------------------------------------

// Close and output PDF document
// This method has several options, check the source code documentation for more information.
//$pdf->Output('example_001.pdf', 'I');
$doc = $pdf->Output('quotation.pdf', 'S');

//define the receiver of the email
$name = "Name goes here";
$email = "jnjuki103@gmail.com";

$to = "$name <{$_SESSION['email']}>";

$from = "John-Smith ";

$subject = "Here is your attachment";

$fileatt = $pdf->Output('quotation.pdf', 'S');
//$fileatt = "./test.pdf";

$fileatttype = "application/pdf";

$fileattname = "newname.pdf";

$headers = "From: $from";

$file = fopen($fileatt, 'rb');

$data = fread($file, filesize($fileatt));

fclose($file);

$semi_rand = md5(time());

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";

$message = "This is a multi-part message in MIME format.\n\n" .
    "-{$mime_boundary}\n" .
    "Content-Type: text/plain; charset=\"iso-8859-1\n" .
    "Content-Transfer-Encoding: 7bit\n\n" .
    $message .= "\n\n";

$data = chunk_split(base64_encode($data));

$message .= "–{$mime_boundary}\n" .
    "Content-Type: {$fileatttype};\n" .
    " name=\"{$fileattname}\"\n" .
    "Content-Disposition: attachment;\n" .
    " filename=\"{$fileattname}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" .
    "-{$mime_boundary}-\n";

if (mail($to, $subject, $message, $headers)) {
    echo "The email was sent.";
} else {
    echo "There was an error sending the mail.";
}
//============================================================+
// END OF FILE
//============================================================+

1.你可以這樣做:

$fileatt = $pdf->Output('quotation.pdf', 'E');

選項 E:將文檔返回為 base64 mime multi-part email 附件(RFC 2045),我在以下位置找到此信息: tcpdf 文檔

之后你只需要做:

$data = chunk_split($fileatt);

並且您的文件已准備好附加到郵件中,無需處理文件。 只需保留您的標題和其他設置,它就可以完成工作。

或者

2.你可以用F把它保存在你的服務器上,然后得到這樣的數據:

$filename = location_on_server."quotation.pdf";

$fileatt = $pdf->Output($filename, 'F');

$data = chunk_split( base64_encode(file_get_contents($filename)) );

Output($name='yourfilename.pdf', $dest='E')

E是解決您遇到的問題的方法。 以下是 $dest 字符串的可能值列表(發送文檔的目的地):

  • I :將文件內聯發送到瀏覽器(默認)。
  • D :發送到瀏覽器並使用 name 給出的名稱強制下載文件。
  • F : 以 name 給定的名稱保存到本地服務器文件。
  • S :將文檔作為字符串返回(名稱被忽略)。
  • FI : 相當於 F + I 選項
  • FD : 相當於 F + D 選項
  • E :將文檔作為 base64 mime multi-part email 附件返回(RFC 2045)

我嘗試了很多選擇。 一個有效的方法是當我使用 tcpdf output 設置“F”設置保存到文件夾時。 包括 phpmailer 文件並使用下面的代碼。

$pdf->Output("folder/filename.pdf", "F"); //save the pdf to a folder setting `F`
require_once('phpmailer/class.phpmailer.php'); //where your phpmailer folder is
$mail = new PHPMailer();                    
$mail->From = "email.com";
$mail->FromName = "Your name";
$mail->AddAddress("email@yahoo.com");
$mail->AddReplyTo("email@gmail.com", "Your name");               
$mail->AddAttachment("folder/filename.pdf");      
// attach pdf that was saved in a folder
$mail->Subject = "Email Subject";                  
$mail->Body = "Email Body";
if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
   echo "Message sent";
} //`the end`
First generate the PDF using tcpdf library.Here is the example for generate PDF:

<?php
    ini_set("display_errors", 1);

    require_once('./TCPDF/tcpdf.php');

    class MYPDF extends TCPDF {
        public function Footer() {
            $this->SetY(-15);
            $this->SetFont('helvetica', 'I', 8);
            $this->Cell(0, 0, 'Product Company - Spider india, Phone : +91 9940179997, TIC : New No.7, Old No.147,Mount Road, Little Mount,Saidapet, Chennai, Tamilnadu,Pin - 600015, India.', 0, 0, 'C');
            $this->Ln();
            $this->Cell(0,0,'www.spiderindia.com - TEL : +91-44-42305023, 42305337  - E : marketing@spiderindia.com', 0, false, 'C', 0, '', 0, false, 'T', 'M');
            $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        }    
    }

    $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Manikandan');
    $pdf->SetTitle('Quote');
    $pdf->SetSubject('Quote');
    $pdf->SetKeywords('PDF, Quote');

    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    $pdf->SetFont('times', '', 15); 

    $pdf->AddPage();

    // create some HTML content
    $now = date("j F, Y");
    $company_name = 'ABC test company';

    $user_name = 'Mr. Manikandan';
    $invoice_ref_id = '2013/12/03';


    $html = '';
    $html .= '<table style="padding-top:25px;">
                <tr>
                    <td colspan="2" align="left"><h4>Kannama & CO</h4></td>
                    <td colspan="2" align="right"><h1 style="color:#6C8BB5;">Quote</h1></td>
                </tr>

                <tr>
                    <td colspan="2" align="left"><table><tr><td>'.$user_name.'</td></tr><tr><td>Mob NO : 9791564278</td></tr></table></td>
                    <td colspan="2" align="right"><table border="1" align="center"><tr><td>Date</td><td>'.$now.'</td></tr><tr><td>Quote</td><td>#0041</td></tr></table></td>
                </tr>

                <tr>
                    <td colspan="2" align="left"><table><tr><td style="background-color: #2B7DB9;color:white;width:75%;">Customer</td></tr><tr><td>Dear senthil kumar,</td></tr><tr><td>39,Jawahar sangam street,Chockalingapuram,Aruppukottai.</td></tr><tr><td><b>Mob no : </b> 9791564821</td></tr></table></td>
                </tr>


             </table>';

    $html .= '<br><br>
              <table border="1" cellpadding="5">
                <tr style="background-color: #2B7DB9;color:white;">
                    <td colspan="4">Quote # Quote 001</td>            
                </tr>
                <tr>
                    <td><b>Product</b></td>
                    <td><b>Quantity</b></td>
                    <td><b>Subtotal</b></td>
                    <td align="right"><b>Amount (Rs.)</b></td>
                </tr>
                <tr style="background-color: #C1E1F8;">
                    <td>Product 1</td>
                    <td>30</td>
                    <td>10</td>
                    <td align="right">300</td>
                </tr>
                <tr>
                    <td>Product 3</td>
                    <td>15</td>
                    <td>3</td>
                    <td align="right">75</td>
                </tr>
                <tr style="background-color: #C0E1F8;">
                    <td>Product 2</td>
                    <td>15</td>
                    <td>3</td>
                    <td align="right">75</td>
                </tr>
                <tr>
                    <td colspan="3" align="right"><b>Sub Total:</b></td>
                    <td align="right"><b> 375</b></td>
                </tr>
                <tr>
                    <td colspan="3" align="right"><b>GST:</b></td>
                    <td align="right"><b> 5</b></td>
                </tr>
                <tr>
                    <td colspan="3" align="right"><b>CGST:</b></td>
                    <td align="right"><b> 10</b></td>
                </tr>
                <tr>
                    <td colspan="3" align="right"><b>Delivery:</b></td>
                    <td align="right"><b> 100</b></td>
                </tr>
                <tr>
                    <td colspan="3" align="right"><b>Total:</b></td>
                    <td align="right"><b> 1000</b></td>
                </tr>
             </table>';

    $html = str_replace('{now}',$now, $html);
    $html = str_replace('{company_name}',$company_name, $html);
    $html = str_replace('{user_name}',$user_name, $html);
    $html = str_replace('{invoice_ref_id}',$invoice_ref_id, $html);

    $pdf->writeHTML($html, true, false, true, false, '');

    $pdf->lastPage();

    $fileName = time() . '.pdf';
    ob_clean();
    $pdf->Output(FCPATH . 'files/' . $fileName, 'F');

    if (file_exists(FCPATH . 'files/' . $fileName)) {
        if (!empty($data->email)) {
            $status = $this->sendReceiptEmail($fileName, $data->email);
            return $status;   
        } else {
            return false;
        }
    } else {
        return false;
    }

    Use PHP Mailer library to send email. Here is the example to send mail with attachment.

    function sendReceiptEmail($fileName, $mailto)
    {
        $file = FCPATH . 'files/' . $fileName;
        date_default_timezone_set('Asia/Kolkata');

        require __DIR__.'/../libraries/phpmailer/PHPMailerAutoload.php';

        $mail = new PHPMailer;

        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->IsSMTP();
        $mail->Host = "xxx.xxx.com";
        $mail->Port = 587;
        $mail->SMTPAuth = true;
        $mail->Username = "info@xxx.com";
        $mail->Password = "xxxxx";
        $mail->setFrom('info@xxx.com', 'Company Quote');
        $mail->addReplyTo('info@xxx.com');
        $mail->addAddress($mailto);
        $mail->Subject = 'Quote';
        $mail->Body = 'Here we attached quote detail.Please find the attachment.';

        $mail->addAttachment($file);

        //send the message, check for errors
        if (!$mail->send()) {
            return false;
        } else {
            $file = FCPATH . 'files/' . $fileName;
            if (file_exists($file)) {
                unlink($file);
            }
            return true;
        }
    }

我知道這是一個老問題(老了。)。 但我設法做到這一點。

function createPDF($html){
    $pdf = new TCPDF();
    $pdf->AddPage();
    $pdf->writeHTML($html, true, false, true, false, '');

    return $pdf->Output('filename.pdf', 'S'); //S: return the document as a string (name is ignored).
}


function sendEmail() {

    $pdf = createPDF('<a>Hello</a>');
    $filename = 'hello.pdf';
    $encoding = 'base64';
    $type = 'application/pdf';

    //using PHPMailer
    $mail->AddStringAttachment($pdf,$filename,$encoding,$type);
}

由於官方記錄的使用'S''E'方法為我返回null ,我繼續使用久經考驗的 output 緩沖技巧,例如:

protected function PDF_string($pdf, $base64 = false) {
    ob_start();
    $pdf->Output('file.pdf', 'I');
    $pdf_data = ob_get_contents();
    ob_end_clean();

    return ($base64) ? base64_encode($pdf_data) : $pdf_data;
}

以我的方式做這件事還有很多工作要做,但我想給用戶 Output 選項 D:發送到瀏覽器並強制使用名稱給出的名稱下載文件,或立即將其保存為 PDF 文件以供編輯。

Example_054.php。

然后我用 DOMPDF 從 TCPDF 創建了一個相同的表單。

提交表單后,表單將調用我的提交腳本,提交腳本將訪問填充的值,進而填充我相同的 DOMPDF 文檔。 然后我用新的填充值保存我的 DOMPDF 文檔。 保存的 DOMPDF 文件現在可以通過 PHPMailer 作為完全填充的 PDF 文件 email 附件通過電子郵件發送。

通過 TCPDF 本身可能有一種更簡單的方法來做到這一點,但這完全滿足了我的要求。 我必須同時學習 DOMPDF 和 TCPPDF。

作為對我上一篇文章的修正,這僅適用於用戶選擇從瀏覽器訪問 PDF 文件 Output 選項 D:Example_054.ZE1BFD762321E409CEE4AC0B6E849。 I did NOT see any other way of emailing as a PDF created on the browser and send that as the actual PDF file email attachment without re-creating the PDF with DOMPDF and saving the populated PDF so it could be sent then as the email attachment. 如果用戶選擇在填充之前保存 PDF,那么這不是問題,因為填充的文件將存在於附件中。 如果有更簡單的方法來處理這種情況,請告訴我!!

有來自tcpdf.php的代碼。 我們可以看到E選項在Output function 中做了什么。 它使用base64_encodechunk_split並且還使用它添加headers ,因此無需再次添加標頭。

case 'E': {
            // return PDF as base64 mime multi-part email attachment (RFC 2045)
            $retval = 'Content-Type: application/pdf;'."\r\n";
            $retval .= ' name="'.$name.'"'."\r\n";
            $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
            $retval .= 'Content-Disposition: attachment;'."\r\n";
            $retval .= ' filename="'.$name.'"'."\r\n\r\n";
            $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
            return $retval;
        }

所以在上面的問題中

$attachFile = $pdf->Output('quotation.pdf', 'E');
$html_message = '<p> Your HTML/ Plain message Here </p>' ;
$uid = md5() ;

$header = "From: <user@example.com>\r\n";
$header .= "Reply-to: <user@example.com>\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/html ;charset=UTF-8\r\n";
$nmessage .= $html_message."\r\n\r\n"; //Your message

$nmessage .= "--".$uid."\r\n";
$nmessage .= $attachFile."\r\n\r\n"; //adding Your PDF file
$nmessage .= "--".$uid."--" ;

使用CodeIgniterTCPDF ,這對我有用。

  1. 步驟 1:將文檔保存在服務器中。
  2. 第二步:獲取文件路徑,將文件路徑發送到function,用於發送email。

     <?php function GenerateQuotation(){ session_start(); require_once('../config/lang/eng.php'); require_once('../tcpdf.php'); // create new PDF document $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); // set document information $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('Name of Author'); $pdf->SetTitle('Quotation Request'); $pdf->SetSubject('TCPDF Tutorial'); $pdf->SetKeywords('TCPDF, PDF, example, test, guide'); $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, '', PDF_HEADER_STRING); $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); $pdf->setLanguageArray($l); $pdf->setFontSubsetting(true); $pdf->SetFont('dejavusans', '', 14, '', true); $pdf->AddPage(); $html = '<span style="font-size:7pt;">'. $_SESSION['content']. '</span>'; $html.= <<<EOD EOD; $pdf->writeHTMLCell($w=0, $h=0, $x='', $y='', $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true); //Change this according to where you want your document to be uploaded to $LocationOnServer = 'C:\wamp64\www\projectname\uploads\invoices/\/'; $FileNamePath = $LocationOnServer.'quotation.pdf'; //Save the document to the server $QuotationAttachment = $pdf->Output($FileNamePath, 'F'); $EmailAddress = $_SESSION['email']; if(,empty($FileNamePath)){ $this->SendQuotation($EmailAddress;$FileNamePath); } else{ print_r('Could not trace file path'), } } function SendQuotation($EmailAddress;$FileNamePath){ $Subject = 'My subject here'; $Message = 'My Email body message here'. $this->email ->from('xxxxx@xxxx,com'; 'From Who') ->to($EmailAddress) ->subject($Subject) ->message($Message); $this->email->attach($FileNamePath); if($this->email->send()){ print_r('Email Sent'); }else{ print_r($this->email->print_debugger())? } } } ?>

調用GenerateQuotation() function 生成報價和 email 它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM